Write Metal's encoding through compressed BGRA10_XR blits under an exact-answers switch

What: a new DevicePolicy switch, `extended_range_blits` (ExtendedRangeBlitPolicy::Kept, the
default, and ::Canonical, which `exact_answers()` selects). Under Canonical a blit or fill through a
BGRA10_XR or BGRA10_XR_sRGB texture Metal keeps losslessly compressed writes Metal's canonical
encoding: each 16-bit field's low six bits cleared and, for a blit, the alpha code clamped to
[384, 894].
- bind::extended_canonical_module, a compute kernel that rewrites a texel range's words in place
  (bind/extended_canonical.rs, with extended_range_canonical as its reference and interpreter
  tests); the runtime owns it as OwnedModule::ExtendedCanonical.
- The runtime (extended_canonical.rs): after a blit into such a texture, or out of one into another
  texture of the format, the written regions go out to a scratch buffer, one dispatch per region
  rewrites them, and they go back; after a blit out of one into a buffer, or into a texture over a
  buffer's bytes, one dispatch rewrites the words in place at the layout's rows. A fill's texel is
  encoded before it is written (fills clear the low bits alone: Metal's fill keeps alpha codes 4
  and 1023 on the M3 Max under 27.0.1). A buffer the device cannot bind (offset or pitch off 4,
  past maxStorageBufferRange) or a texture over a buffer whose rows share bytes keeps the bytes and
  announces extended-range-bits-kept, as under Kept. Under Canonical the note is not announced for
  the blits it makes exact.
- copy_from_buffer_to_texture's body moved into buffer_into_texture, which a fill's row copies call
  with Writer::Fill (so a fill announces its own wording and is never rewritten as a blit).

Why: Metal's GPU blits through the compression rewrite these bits (measured on the M3 Max under
macOS 27.0.1, plain Metal, xr_matrix: compression iff allowGPUOptimizedContents, shorter side >= 16,
neither ShaderWrite nor PixelFormatView usage; every storage mode alike; CPU copies keep the bytes;
fills clear the low six bits only). The device's copy keeps the bytes. It is the runtime's choice,
not a native answer (no device arithmetic is involved: a copy's bytes), so per rule 1 the fast form
stays the default and the exact form is the switch.

Ledger: FAST-PATHS row (fast defaults), API.md section 1 bullet and the extended-range-bits-kept
catalogue entry, the Degradation doc, the conformance Policy doc. Known gaps: the 28 rows of
compressed-blits-bgra10xr and -srgb (7 sites x 2 formats x Apple M3 Max and llvmpipe) dropped:
under the suite's exact policy those sites now hold Metal's bytes.
RUNTIME_VERSION 1728 -> 1731 (a run under the exact policy writes other bytes).

Also fixes forward a clippy needless borrow in engine_arith's pack test (7a99b93af2).

Verified (M3 Max, macOS 27.0.1, MoltenVK 1.4.2; and lavapipe in scripts/linux-gate, arm64,
LLVM 21.1.8 128 bits):
- runtime_lane::compressed_blits on MoltenVK: both tests pass; the new
  extended_range_blits_write_metal_s_encoding_under_the_canonical_policy checks every direction,
  level 3 into padded rows, Shared CPU/blit mixes, texture to texture both ways, a fill of a
  compressed and a plain texture, and a copy into a texture over a buffer with padded rows, under
  both values (Canonical: Metal's bytes and no notice; Kept: the bytes and the notice once).
- conformance replay of the four compressed-blits cases on MoltenVK: exit 0, the ledger as
  edited (bgra10xr and -srgb `announced` only for staged-texture-copy/shadowed-texture).
- the full `conformance replay --cpu` on lavapipe at 68074019a3 and at this change: the only
  difference is the 14 llvmpipe sites of the two XR cases, which no longer diverge (divergent
  244 -> 242, exact 458 -> 460); the 265 other ledger mismatches of that arm64 venue are the same
  at both (it is not CI's amd64 lavapipe).
- 154 touched validation lanes on MoltenVK (blits, fills, extended-range, NaN, pack, padded,
  rotated, no-copy, two-plane heap): 143 passed, 10 failed, 1 ignored; the same 10 fail with the
  same messages and the same differing texels at 68074019a3 (pre-existing).

(cherry picked from commit 612ff50b86bc29515b158d9b2596b14a45431467)
This commit is contained in:
Anees Iqbal committed 2026-11-02 13:13:17 -08:00
1 parent 452c17aa2c
commit 4b194d24af
23 files changed
+1304 -258

No files matched your search

+3 -29
View File
@@ -1037,21 +1037,9 @@ read-write-tier-round-trip-float llvmpipe divergent case/MTLPixelFormatRGBA8Unor
# Blits through a texture Metal keeps losslessly compressed: Metal's compression writes three
# families' texels in their canonical encoding and the device's copy keeps the bytes it read, the same
# value. Each row names the note that records it (the runtime's `compressed_blit.rs`).
compressed-blits-bgra10xr llvmpipe divergent case/blit-in-cpu-out 8189 elements differ (U32), the largest difference 1610153938 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr llvmpipe divergent case/cpu-in-blit-out 8192 elements differ (U32), the largest difference 1610612733 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr llvmpipe divergent case/into-compressed 8190 elements differ (U32), the largest difference 1610219491 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr llvmpipe divergent case/level-3-padded 128 elements differ (U32), the largest difference 1578041311 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr llvmpipe divergent case/out-of-compressed 8189 elements differ (U32), the largest difference 1609170923 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr llvmpipe divergent case/over-a-buffer 8191 elements differ (U32), the largest difference 1609367489 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr llvmpipe divergent case/tall 8191 elements differ (U32), the largest difference 1610547199 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb llvmpipe divergent case/blit-in-cpu-out 8191 elements differ (U32), the largest difference 1609498596 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb llvmpipe divergent case/cpu-in-blit-out 8189 elements differ (U32), the largest difference 1610285007 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb llvmpipe divergent case/into-compressed 8190 elements differ (U32), the largest difference 1610285037 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb llvmpipe divergent case/level-3-padded 128 elements differ (U32), the largest difference 1543569388 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb llvmpipe divergent case/out-of-compressed 8189 elements differ (U32), the largest difference 1610153972 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb llvmpipe divergent case/over-a-buffer 8190 elements differ (U32), the largest difference 1606483915 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb llvmpipe divergent case/tall 8190 elements differ (U32), the largest difference 1609891839 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, the same value in another encoding. `extended-range-bits-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
# value. Each row names the note that records it (the runtime's `compressed_blit.rs`). `BGRA10_XR` and
# its sRGB twin have none: the suite's exact policy writes Metal's encoding
# (`ExtendedRangeBlitPolicy::Canonical`).
compressed-blits-rg11b10f llvmpipe divergent case/blit-in-cpu-out 331 elements differ (U32), the largest difference 62914560 Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field's NaN bits. `device-nan-encoding` records it (the runtime's `compressed_blit.rs`), and its bound -- a NaN stays a NaN, its bits the device's -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rg11b10f llvmpipe divergent case/cpu-in-blit-out 322 elements differ (U32), the largest difference 62914560 Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field's NaN bits. `device-nan-encoding` records it (the runtime's `compressed_blit.rs`), and its bound -- a NaN stays a NaN, its bits the device's -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rg11b10f llvmpipe divergent case/into-compressed 366 elements differ (U32), the largest difference 62914560 Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field's NaN bits. `device-nan-encoding` records it (the runtime's `compressed_blit.rs`), and its bound -- a NaN stays a NaN, its bits the device's -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
@@ -1066,20 +1054,6 @@ compressed-blits-rgb9e5f llvmpipe divergent case/level-3-padded 8 elements diffe
compressed-blits-rgb9e5f llvmpipe divergent case/out-of-compressed 509 elements differ (U32), the largest difference 400620895 Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and the device's copy keeps the bytes it read, the same value in another encoding. `shared-exponent-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the same value -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rgb9e5f llvmpipe divergent case/over-a-buffer 532 elements differ (U32), the largest difference 426639677 Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and the device's copy keeps the bytes it read, the same value in another encoding. `shared-exponent-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the same value -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rgb9e5f llvmpipe divergent case/tall 494 elements differ (U32), the largest difference 402462819 Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and the device's copy keeps the bytes it read, the same value in another encoding. `shared-exponent-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the same value -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr Apple M3 Max divergent case/blit-in-cpu-out 8189 elements differ (U32), the largest difference 1610153938 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr Apple M3 Max divergent case/cpu-in-blit-out 8192 elements differ (U32), the largest difference 1610612733 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr Apple M3 Max divergent case/into-compressed 8190 elements differ (U32), the largest difference 1610219491 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr Apple M3 Max divergent case/level-3-padded 128 elements differ (U32), the largest difference 1578041311 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr Apple M3 Max divergent case/out-of-compressed 8189 elements differ (U32), the largest difference 1609170923 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr Apple M3 Max divergent case/over-a-buffer 8191 elements differ (U32), the largest difference 1609367489 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr Apple M3 Max divergent case/tall 8191 elements differ (U32), the largest difference 1610547199 Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb Apple M3 Max divergent case/blit-in-cpu-out 8191 elements differ (U32), the largest difference 1609498596 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb Apple M3 Max divergent case/cpu-in-blit-out 8189 elements differ (U32), the largest difference 1610285007 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb Apple M3 Max divergent case/into-compressed 8190 elements differ (U32), the largest difference 1610285037 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb Apple M3 Max divergent case/level-3-padded 128 elements differ (U32), the largest difference 1543569388 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb Apple M3 Max divergent case/out-of-compressed 8189 elements differ (U32), the largest difference 1610153972 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb Apple M3 Max divergent case/over-a-buffer 8190 elements differ (U32), the largest difference 1606483915 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-bgra10xr-srgb Apple M3 Max divergent case/tall 8190 elements differ (U32), the largest difference 1609891839 Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bits cleared, the alpha code clamped to [384, 894] -- and the device's copy keeps the bytes it read, at every site: the runtime holds the format in an `R16G16B16A16_UINT` image, and Metal's blits through MoltenVK's texture of that format keep its bytes (`compressed_blit.rs`, `copies_rewrite`). The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `extended-range-bits-kept` records it, and its bound -- the value Metal reads, the low six bits unread and the alpha read clamped -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rg11b10f Apple M3 Max divergent case/blit-in-cpu-out 331 elements differ (U32), the largest difference 62914560 Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field's NaN bits. Under MoltenVK the image of a `Shared` texture Metal compresses is made of `PixelFormatView` usage, which Metal keeps uncompressed, so the sites through the shared texture keep the bytes (`compressed_blit.rs`, `copy_exact_usage`); the `Private` compressed textures' sites (`tall`, `level-3-padded`) are MoltenVK's own blit through Metal's compression and match it. The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `device-nan-encoding` records it, and its bound -- a NaN stays a NaN, its bits the device's -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rg11b10f Apple M3 Max divergent case/cpu-in-blit-out 322 elements differ (U32), the largest difference 62914560 Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field's NaN bits. Under MoltenVK the image of a `Shared` texture Metal compresses is made of `PixelFormatView` usage, which Metal keeps uncompressed, so the sites through the shared texture keep the bytes (`compressed_blit.rs`, `copy_exact_usage`); the `Private` compressed textures' sites (`tall`, `level-3-padded`) are MoltenVK's own blit through Metal's compression and match it. The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `device-nan-encoding` records it, and its bound -- a NaN stays a NaN, its bits the device's -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rg11b10f Apple M3 Max divergent case/into-compressed 366 elements differ (U32), the largest difference 62914560 Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field's NaN bits. Under MoltenVK the image of a `Shared` texture Metal compresses is made of `PixelFormatView` usage, which Metal keeps uncompressed, so the sites through the shared texture keep the bytes (`compressed_blit.rs`, `copy_exact_usage`); the `Private` compressed textures' sites (`tall`, `level-3-padded`) are MoltenVK's own blit through Metal's compression and match it. The same value in another encoding: the words that differ are the bytes the case feeds against Metal's re-encoding of them, and every texel of those bytes reads Metal's value. `device-nan-encoding` records it, and its bound -- a NaN stays a NaN, its bits the device's -- covers the difference. Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
Can't render this file because it is too large.
@@ -7,7 +7,10 @@
//! the same value in its canonical encoding. The runtime's answer is the device's copy, which keeps
//! the bytes, announced by the note of the encoding it keeps (`compressed_blit.rs`): where the
//! device's own copy of the compressed image is not Metal's blit, those sites are `known-gaps.tsv`
//! rows that name the note.
//! rows that name the note. `BGRA10_XR` and its sRGB twin have an exact form: under the suite's
//! `Policy::Exact` (`ExtendedRangeBlitPolicy::Canonical`) the runtime writes Metal's encoding, so
//! their sites hold Metal's bytes and announce nothing; their note's declaration covers a
//! `--default-policy` run, where the device's copy keeps the bytes.
//!
//! Record mode runs the whole program on this M3 Max, because every call it makes is public Metal:
//! a texture of any descriptor, a texture over a buffer, the blit copies, `replaceRegion:` and
@@ -104,7 +107,9 @@ const FORMATS: [Format; 4] = [
/// native notes the suite declares for every case (`crate::replay::NATIVE_NOTES`):
/// `extended-range-bits-kept` for `BGRA10_XR` and its sRGB twin, `shared-exponent-kept` for
/// `RGB9E5Float`. Every case whose program blits through such a texture declares it, at the
/// notices site alone: each value still compares against Metal's.
/// notices site alone: each value still compares against Metal's. Under `Policy::Exact` the
/// `BGRA10_XR` formats' note does not fire (`ExtendedRangeBlitPolicy::Canonical` writes Metal's
/// encoding), and the report counts its declaration as unfired.
pub(crate) fn kept_encoding_notice(format: u32) -> Option<Allowance> {
FORMATS
.iter()
@@ -266,8 +266,8 @@ pub enum Policy {
/// `DevicePolicy::exact_answers()`: the accurate form of each of the runtime's
/// speed-for-accuracy switches, which are all it selects — `heap_compression`
/// `Uncompressed`, `completion` `Exact`, `batch_order` `Exact`, `render_lowering` `AtCall`,
/// `host_page_textures` `Shadow`, `half_chains` `EachOperation`, `pipeline_waits` `Exact` and
/// `wide_lines` `Exact`.
/// `host_page_textures` `Shadow`, `half_chains` `EachOperation`, `pipeline_waits` `Exact`,
/// `wide_lines` `Exact` and `extended_range_blits` `Canonical`.
Exact,
/// The runtime's own defaults: the fast form of every choice, which is what a consumer runs.
Default,
+10 -11
View File
@@ -173,7 +173,7 @@ use super::blit_texture;
use super::chroma_pairs::{is_four_two_two, TEXEL_BYTES};
use super::clear_value;
use super::clear_value::has_channels;
use super::compressed_blit::degrade_compressed_blit;
use super::compressed_blit::{self, degrade_compressed_blit, Writer};
use super::copy_plan::{
block_bytes, block_extent, level_extent, BlitOption, CopyUnit, ImageRegion,
};
@@ -1309,7 +1309,11 @@ impl BlitCommandEncoder {
if texture.record().samples > 1 {
return self.sample_fill(call, texture, (level_u32, slice), option, (x, y), pattern);
}
let unit_bytes = unit_of(pattern, bytes);
let mut unit_bytes = unit_of(pattern, bytes);
// Into a texture Metal keeps compressed: Metal's encoding of the texel, written as it is.
if compressed_blit::canonical(texture) {
compressed_blit::canonical_fill_unit(&mut unit_bytes);
}
if unit == FillUnit::PackedCodes {
return self.packed_code_fill(texture, (x, y));
}
@@ -1441,16 +1445,11 @@ impl BlitCommandEncoder {
let top = row * block[1];
let height = (end * block[1]).min(size[1]) - top;
self.unlogged(|this| {
this.copy_from_buffer_to_texture(
&staging,
0,
row_bytes,
row_bytes * (end - row),
this.buffer_into_texture(
Writer::Fill,
(&staging, 0, row_bytes, row_bytes * (end - row)),
Size::new(width, height, 1),
texture,
slice,
level,
Origin::new(left, top, z),
(texture, slice, level, Origin::new(left, top, z)),
option,
)
})?;
+199 -141
View File
@@ -60,7 +60,7 @@ use super::blit_plan::{
plan_texels_rows_copy, plan_whole_copy, texel_layout, BufferCopyPlan, BufferImageRegion,
BufferLayout, BufferRange, CopyPair, ImageCopyRegion, RowsCopy,
};
use super::compressed_blit::degrade_compressed_blit;
use super::compressed_blit::{self, degrade_compressed_blit, Writer};
use super::copy_plan::{
check_region, colour_unit, copy_unit, depth_bytes, level_extent, shape, BlitOption,
CopyProblem, CopyRefusal, CopyUnit, ImageRegion, TextureRegion,
@@ -473,149 +473,187 @@ impl BlitCommandEncoder {
}))
},
|this| {
const CALL: &str = "copy_from_buffer_to_texture";
this.core().check_device(CALL, source_buffer.device())?;
this.check_texture(CALL, destination_texture)?;
destination_texture.check_plane_copied()?;
if this.fails_on_memoryless(&[destination_texture]) {
return Ok(());
}
destination_texture.check_rotated_reach()?;
let Some(size) = copy_size(source_size, &[destination_texture.texture_type()])
else {
return Ok(());
};
// Vulkan copies no multisampled image from a buffer, so the buffer-image path below
// cannot take one. The empty copy is the no-op Metal makes (above); a real one into
// a multisampled texture is emulated per sample through a wide image and a scratch
// (`sample_interleave.rs`), or refused typed where the device cannot run that.
let samples = destination_texture.record().samples;
if samples > 1 {
let layout = BufferLayout {
offset: source_offset,
bytes_per_row: source_bytes_per_row,
bytes_per_image: source_bytes_per_image,
};
let region = region(
CALL,
destination_origin,
size,
destination_level,
destination_slice,
)?;
let region = multisampled_region(CALL, destination_texture, region)?;
let (raw_buffer, base) = this.core().blit_at(source_buffer, 0)?;
let aspect = multisampled_aspect(CALL, destination_texture, options)?;
let planned = sample_interleave::InterleaveCopy::plan(
CALL,
this.core().command_buffer(),
raw_buffer,
base,
source_buffer.copy_reach(),
&layout,
destination_texture,
&region,
aspect,
samples,
true,
)?;
return match planned {
Some(copy) => {
// Every sample of the region written: a heap shadow it covers takes no
// copy in.
let covered = [multisampled_box(destination_texture, aspect, &region)?];
let boxes = (&[][..], &covered[..]);
this.command_in_reading(
copy.stages,
&copy.uses,
boxes,
|device, raw| {
// SAFETY: the encoder's command buffer is recording outside a
// render pass; the buffer (held by `blit_at`), the texture and
// the copy's images and objects (held by the copy; both
// retained below) are live until it completes.
unsafe { copy.record(device, raw) };
},
)?;
// A depth written as the single-sample path writes one announces as it
// does.
destination_texture.degrade_depth_upload(CALL, aspect, true);
destination_texture.degrade_depth_denormals(CALL, aspect, false);
copy.announce(this.core().device(), CALL, destination_texture);
let format = destination_texture.pixel_format();
copy.announce_staging(this.core().device(), format, true);
this.core().retain(copy);
this.core().retain(destination_texture.clone());
// Every sample of the region written, as the single-sample path's.
let written = multisampled_texels(&region);
this.scrub(destination_texture, vec![(aspect.into(), written)])
}
None => Err(Error::NotImplemented(RuntimeGap::MultisampledBufferCopy)),
};
}
let texture = destination_texture;
let layout = BufferLayout {
offset: source_offset,
bytes_per_row: source_bytes_per_row,
bytes_per_image: source_bytes_per_image,
};
if two_planes::holds_planes(texture.pixel_format()) && !texture.over_buffer() {
let region = region(
CALL,
destination_origin,
size,
destination_level,
destination_slice,
)?;
return this.plane_copy(CALL, source_buffer, texture, &region, &layout, true);
}
let unit = unit(CALL, texture, options)?;
let region = region(
CALL,
destination_origin,
size,
destination_level,
destination_slice,
)?;
if let Some(texels) = texture.buffer_texels() {
// Rows that share bytes (an IOSurface plane's on Metal's GPU): the row
// copies would write every shared byte from one fixed row, where Metal
// leaves it from whichever row its own command wrote last -- an order that
// follows the command, the GPU pitch and the row count, and that one shape
// does not settle from run to run (`linear_plan.rs`'s **Rows that
// overlap**). The other direction reads those rows instead of writing them
// and is served (`copy_from_texture_to_buffer`).
if texels.plane_rows_overlap() {
return Err(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows));
}
let (from, to) = plan_rows_copy(
texture.record(),
&region,
&unit,
&layout,
source_buffer.copy_reach(),
&texels.layout,
)
.map_err(|problem| invalid(CALL, Problem::Copy(problem)))?;
return this.rows_copy(
this.buffer_into_texture(
Writer::Blit,
(
source_buffer,
&texels.buffer,
&RowsCopy::new(&from, &to),
);
}
let plan = plan_copy(CALL, texture, &region, &unit, &layout, source_buffer, true)?;
let written: Vec<ImageRegion> = plan.regions.iter().map(|r| r.image).collect();
this.buffer_texture_copy(source_buffer, texture, plan, true)?;
texture.degrade_depth_upload(CALL, unit.aspect, true);
texture.degrade_depth_denormals(CALL, unit.aspect, false);
// Into a texture Metal keeps compressed: the device's copy keeps the bytes.
degrade_compressed_blit(CALL, texture)?;
// Into a texture with a decoded twin: the twin's texels of what the copy wrote.
this.decode_twin(texture, &written)
source_offset,
source_bytes_per_row,
source_bytes_per_image,
),
source_size,
(
destination_texture,
destination_slice,
destination_level,
destination_origin,
),
options,
)
},
)
}
/// [`copy_from_buffer_to_texture`](Self::copy_from_buffer_to_texture), unlogged, its texels
/// written by `writer`: a blit's copy, or a fill's rows of its texel (`blit_fill.rs`), which
/// differ in what Metal's compression writes of a `BGRA10_XR` texture's texels
/// (`compressed_blit.rs`).
pub(super) fn buffer_into_texture(
&mut self,
writer: Writer,
(source_buffer, source_offset, source_bytes_per_row, source_bytes_per_image): (
&Buffer,
u64,
u64,
u64,
),
source_size: Size,
(destination_texture, destination_slice, destination_level, destination_origin): (
&Texture,
u64,
u64,
Origin,
),
options: BlitOption,
) -> Result<(), Error> {
const CALL: &str = "copy_from_buffer_to_texture";
self.core().check_device(CALL, source_buffer.device())?;
self.check_texture(CALL, destination_texture)?;
destination_texture.check_plane_copied()?;
if self.fails_on_memoryless(&[destination_texture]) {
return Ok(());
}
destination_texture.check_rotated_reach()?;
let Some(size) = copy_size(source_size, &[destination_texture.texture_type()]) else {
return Ok(());
};
// Vulkan copies no multisampled image from a buffer, so the buffer-image path below
// cannot take one. The empty copy is the no-op Metal makes (above); a real one into
// a multisampled texture is emulated per sample through a wide image and a scratch
// (`sample_interleave.rs`), or refused typed where the device cannot run that.
let samples = destination_texture.record().samples;
if samples > 1 {
let layout = BufferLayout {
offset: source_offset,
bytes_per_row: source_bytes_per_row,
bytes_per_image: source_bytes_per_image,
};
let region = region(
CALL,
destination_origin,
size,
destination_level,
destination_slice,
)?;
let region = multisampled_region(CALL, destination_texture, region)?;
let (raw_buffer, base) = self.core().blit_at(source_buffer, 0)?;
let aspect = multisampled_aspect(CALL, destination_texture, options)?;
let planned = sample_interleave::InterleaveCopy::plan(
CALL,
self.core().command_buffer(),
raw_buffer,
base,
source_buffer.copy_reach(),
&layout,
destination_texture,
&region,
aspect,
samples,
true,
)?;
return match planned {
Some(copy) => {
// Every sample of the region written: a heap shadow it covers takes no
// copy in.
let covered = [multisampled_box(destination_texture, aspect, &region)?];
let boxes = (&[][..], &covered[..]);
self.command_in_reading(copy.stages, &copy.uses, boxes, |device, raw| {
// SAFETY: the encoder's command buffer is recording outside a
// render pass; the buffer (held by `blit_at`), the texture and
// the copy's images and objects (held by the copy; both
// retained below) are live until it completes.
unsafe { copy.record(device, raw) };
})?;
// A depth written as the single-sample path writes one announces as it
// does.
destination_texture.degrade_depth_upload(CALL, aspect, true);
destination_texture.degrade_depth_denormals(CALL, aspect, false);
copy.announce(self.core().device(), CALL, destination_texture);
let format = destination_texture.pixel_format();
copy.announce_staging(self.core().device(), format, true);
self.core().retain(copy);
self.core().retain(destination_texture.clone());
// Every sample of the region written, as the single-sample path's.
let written = multisampled_texels(&region);
self.scrub(destination_texture, vec![(aspect.into(), written)])
}
None => Err(Error::NotImplemented(RuntimeGap::MultisampledBufferCopy)),
};
}
let texture = destination_texture;
let layout = BufferLayout {
offset: source_offset,
bytes_per_row: source_bytes_per_row,
bytes_per_image: source_bytes_per_image,
};
if two_planes::holds_planes(texture.pixel_format()) && !texture.over_buffer() {
let region = region(
CALL,
destination_origin,
size,
destination_level,
destination_slice,
)?;
return self.plane_copy(CALL, source_buffer, texture, &region, &layout, true);
}
let unit = unit(CALL, texture, options)?;
let region = region(
CALL,
destination_origin,
size,
destination_level,
destination_slice,
)?;
if let Some(texels) = texture.buffer_texels() {
// Rows that share bytes (an IOSurface plane's on Metal's GPU): the row
// copies would write every shared byte from one fixed row, where Metal
// leaves it from whichever row its own command wrote last -- an order that
// follows the command, the GPU pitch and the row count, and that one shape
// does not settle from run to run (`linear_plan.rs`'s **Rows that
// overlap**). The other direction reads those rows instead of writing them
// and is served (`copy_from_texture_to_buffer`).
if texels.plane_rows_overlap() {
return Err(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows));
}
let (from, to) = plan_rows_copy(
texture.record(),
&region,
&unit,
&layout,
source_buffer.copy_reach(),
&texels.layout,
)
.map_err(|problem| invalid(CALL, Problem::Copy(problem)))?;
return self.rows_copy(source_buffer, &texels.buffer, &RowsCopy::new(&from, &to));
}
let plan = plan_copy(CALL, texture, &region, &unit, &layout, source_buffer, true)?;
let written: Vec<ImageRegion> = plan.regions.iter().map(|r| r.image).collect();
self.buffer_texture_copy(source_buffer, texture, plan, true)?;
texture.degrade_depth_upload(CALL, unit.aspect, true);
texture.degrade_depth_denormals(CALL, unit.aspect, false);
// Into a texture Metal keeps compressed: Metal's encoding of what the copy wrote, else
// the device's copy keeps the bytes (a fill's texel was encoded before it, `blit_fill.rs`).
match writer {
Writer::Blit
if compressed_blit::canonical(texture)
&& self.canonical_texels(texture, &written)? => {}
Writer::Blit => degrade_compressed_blit(CALL, texture)?,
Writer::Fill => compressed_blit::degrade_compressed_fill(texture),
}
// Into a texture with a decoded twin: the twin's texels of what the copy wrote.
self.decode_twin(texture, &written)
}
/// `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:
/// destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:`: the
/// texture's region into the buffer, laid out as
@@ -779,7 +817,14 @@ impl BlitCommandEncoder {
false,
)?;
this.buffer_texture_copy(destination_buffer, source_texture, plan, false)?;
// Out of a texture Metal keeps compressed: the device's copy keeps the bytes.
// Out of a texture Metal keeps compressed: Metal's encoding of what the copy
// wrote, where the device binds the buffer's words, else the device's copy keeps
// the bytes.
if compressed_blit::canonical(source_texture)
&& this.canonical_words(destination_buffer, &layout, region.size)?
{
return Ok(());
}
degrade_compressed_blit(CALL, source_texture)
},
)
@@ -1306,7 +1351,20 @@ impl BlitCommandEncoder {
// Into a texture with a decoded twin: the twin's texels of what the copies wrote.
let written: Vec<ImageRegion> = copies.iter().map(|copy| copy.dst).collect();
self.decode_twin(destination, &written)?;
// Out of or into a texture Metal keeps compressed: the device's copy keeps the bytes.
// Out of or into a texture Metal keeps compressed: Metal's encoding of what the copies
// wrote, where the destination holds its texels in an image of the format or at their
// rows in a buffer's bytes; else the device's copy keeps the bytes.
let canonical =
compressed_blit::canonical(source) || compressed_blit::canonical(destination);
if canonical {
let rewritten = match compressed_blit::holds_canonical(destination) {
true => self.canonical_texels(destination, &written)?,
false => self.canonical_texel_words(destination, copies)?,
};
if rewritten {
return Ok(());
}
}
degrade_compressed_blit(call, source)?;
degrade_compressed_blit(call, destination)
}
@@ -14,6 +14,11 @@
//! census tried keep their bytes, and so do a texture over a buffer or of an IOSurface and CPU
//! copies (`replace_region`, `get_bytes`) of any texture.
//!
//! Metal's fill (`fillTexture:...`, Apple SPI) of such a `BGRA10_XR` texture clears each field's
//! low six bits and leaves the alpha code as the texel gives it (the M3 Max under 27.0.1: the
//! patterns `0x0123456789abcdef` and all ones keep alpha codes 4 and 1023); a colour fill's texel
//! is the same either way.
//!
//! **The runtime's answer** is the device's copy, which keeps the bytes it read: the canonical
//! encoding is Metal's compressor's, not the format's (Metal's own uncompressed texture of the
//! format keeps the bytes through the same blit), and a texel whose bytes no Metal write left
@@ -23,6 +28,16 @@
//! `device-nan-encoding`, `shared-exponent-kept`), once per device, except where the device's own
//! copy is Metal's blit of a compressed image ([`copy_rewrites`]).
//!
//! **Under `ExtendedRangeBlitPolicy::Canonical`** (`DevicePolicy::extended_range_blits`, which
//! `exact_answers()` selects) a `BGRA10_XR` texture's blits and fills write Metal's encoding
//! ([`canonical`], `extended_canonical.rs`): a fill's texel is encoded before the fill writes it
//! ([`canonical_fill_unit`]); after a blit into such a texture, or out of one into another texture
//! of the format whose texels are an image, a dispatch rewrites the region the blit wrote in a
//! scratch copy of it; after a blit out of one into a buffer, or into a texture over a buffer's
//! bytes, a dispatch rewrites the words the blit wrote in place. A blit out of one into a buffer
//! whose words the device cannot bind there, or into a texture over a buffer whose rows share
//! bytes (an IOSurface plane's), keeps the bytes and announces the note as before.
//!
//! **MoltenVK** (`RuntimeDriverDefect::CompressedImageCopiesRewriteTexels`): its copies of an
//! image are Metal's blits, so a copy of a compressed `RG11B10Float` or `RGB9E5Float` image writes
//! the canonical encoding. A CPU copy, which the runtime makes a Vulkan copy, would make it too, so
@@ -38,6 +53,7 @@ use super::texture::Texture;
use super::texture_descriptor::{TextureDescriptor, TextureLayout};
use super::values::StorageMode;
use super::{Degradation, Device};
use metal2vulkan::device::ExtendedRangeBlitPolicy;
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::format::is_depth_stencil;
use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage};
@@ -76,6 +92,92 @@ fn rewritten(
&& metal_compresses(colour, usage, allow_gpu_optimized_contents, level0)
}
/// What wrote a texture's texels through a buffer: a blit's copy, or a fill's rows of its texel
/// (`blit_fill.rs`), whose encodings Metal's compression writes otherwise (the module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Writer {
/// A blit's copy.
Blit,
/// A fill's rows of its texel.
Fill,
}
/// Whether Metal keeps `texture` losslessly compressed and its blits rewrite its texels (the
/// module docs): not a texture over a buffer, its root's type, level 0, usage and
/// `allowGPUOptimizedContents` and its own samples ([`rewritten`]).
fn compressed(texture: &Texture) -> bool {
if texture.over_buffer() {
return false;
}
let mut root = texture;
while let Some(parent) = root.parent_texture() {
root = parent;
}
rewritten(
texture.pixel_format(),
root.texture_type(),
[root.width(), root.height()],
texture.sample_count(),
(root.usage(), root.allow_gpu_optimized_contents()),
)
}
/// Whether `texture`'s format is `BGRA10_XR` or its sRGB twin, whose canonical encoding the
/// runtime writes ([`canonical`]).
pub(super) fn extended(pixel_format: PixelFormat) -> bool {
matches!(
pixel_format,
PixelFormat::BGRA10XR | PixelFormat::BGRA10XRSRGB
)
}
/// Whether a blit or fill through `texture` writes Metal's canonical encoding of its texels: the
/// device's policy asks for it (`ExtendedRangeBlitPolicy::Canonical`), and `texture` is a
/// `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed (the module docs).
pub(super) fn canonical(texture: &Texture) -> bool {
let policy = texture.device().compile_device().policy();
policy.extended_range_blits == ExtendedRangeBlitPolicy::Canonical
&& extended(texture.pixel_format())
&& compressed(texture)
}
/// Whether `texture` holds its texels in an image of a `BGRA10_XR` format of one sample, which
/// the canonical encoding's dispatch rewrites through a scratch copy (`extended_canonical.rs`).
pub(super) fn holds_canonical(texture: &Texture) -> bool {
!texture.over_buffer() && extended(texture.pixel_format()) && texture.sample_count() == 1
}
/// `unit`, a fill's texel of a `BGRA10_XR` texture, as Metal's fill through its compression
/// writes it: each 16-bit field's low six bits cleared, the alpha code as it is (the module
/// docs).
pub(super) fn canonical_fill_unit(unit: &mut [u8]) {
for field in unit.as_chunks_mut::<2>().0 {
let code = u16::from_le_bytes(*field) & 0xFFC0;
*field = code.to_le_bytes();
}
}
/// Announce, for a fill through `texture` whose texel the device writes as it is, the note of a
/// `BGRA10_XR` texture Metal keeps losslessly compressed, whose fill clears each field's low six
/// bits (the module docs); nothing where the fill wrote Metal's encoding ([`canonical`]).
pub(super) fn degrade_compressed_fill(texture: &Texture) {
if !extended(texture.pixel_format()) || !compressed(texture) || canonical(texture) {
return;
}
let pf = texture.pixel_format();
texture
.device()
.degrade(Degradation::ExtendedRangeBitsKept, || {
(
format!("a fill of a {pf:?} texture Metal keeps losslessly compressed"),
"the device's fill keeps the texel's bytes, where Metal's fill through its \
compression clears each field's low six bits: the same value in another \
encoding"
.to_owned(),
)
});
}
/// Whether a driver of `RuntimeDriverDefect::CompressedImageCopiesRewriteTexels` rewrites texels
/// in its copies of a compressed image of `format`: the Vulkan formats MoltenVK makes Metal's
/// `RG11B10Float` and `RGB9E5Float` textures of. `BGRA10_XR`'s images are of a format whose
@@ -105,22 +207,8 @@ fn copy_rewrites(texture: &Texture) -> Result<bool, Error> {
/// canonical encoding where Metal keeps the texture losslessly compressed and the device's copy
/// keeps the bytes (the module docs).
pub(super) fn degrade_compressed_blit(call: &'static str, texture: &Texture) -> Result<(), Error> {
if texture.over_buffer() {
return Ok(());
}
let mut root = texture;
while let Some(parent) = root.parent_texture() {
root = parent;
}
let pf = texture.pixel_format();
let compressed = rewritten(
pf,
root.texture_type(),
[root.width(), root.height()],
texture.sample_count(),
(root.usage(), root.allow_gpu_optimized_contents()),
);
let Some(kind) = kept_encoding(pf).filter(|_| compressed) else {
let Some(kind) = kept_encoding(pf).filter(|_| compressed(texture)) else {
return Ok(());
};
if copy_rewrites(texture)? {
@@ -1250,10 +1250,13 @@ degradations! {
/// the device's pass keeps the bytes its draws do not write, on every device. Announced at
/// every draw, an indirect command buffer's executed commands' too, naming every such
/// attachment of the pass. Also a GPU blit into, out of or between textures of which one
/// is a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed
/// (`compressed_blit.rs`): Metal's blit moves the texels through the compression, which
/// clears the same bits and clamps the same alpha, where the device's copy keeps the
/// bytes; once per device.
/// is a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed, and a
/// fill of one (`compressed_blit.rs`): Metal's blit moves the texels through the
/// compression, which clears the same bits and clamps the same alpha (its fill clears the
/// bits alone), where the device's copy keeps the bytes; once per device, under
/// `ExtendedRangeBlitPolicy::Kept` (the default). Under `Canonical` the runtime writes
/// Metal's encoding, and announces only a blit out of one into a buffer whose words the
/// device cannot bind or into a texture over a buffer whose rows share bytes.
ExtendedRangeBitsKept = "extended-range-bits-kept", Precision,
"the texels the pass's draws do not write keep their bytes; Metal's pass rewrites, in \
each tile a draw reaches, the bits their codes leave unused (BGR10_XR's bits 30 and \
@@ -0,0 +1,311 @@
//! Metal's canonical encoding of `BGRA10_XR` and `BGRA10_XR_sRGB` texels, written after a blit
//! through a texture Metal keeps losslessly compressed, under `ExtendedRangeBlitPolicy::Canonical`
//! (`compressed_blit.rs` says when Metal writes it and what it is).
//!
//! - **Into an image** ([`BlitCommandEncoder::canonical_texels`]): the regions the blit wrote are
//! copied out of the image into a scratch buffer, tightly packed, each at an offset the device
//! binds a storage buffer at; one dispatch of `bind::extended_canonical_module` a region
//! rewrites its texels' words in place; and the regions are copied back. Three commands the
//! encoder's tracker orders as any others: the copies' transfer reads and writes, the dispatch's
//! storage reads and writes of the scratch.
//! - **Into a buffer** ([`BlitCommandEncoder::canonical_words`]): one dispatch rewrites the words
//! of the texels the blit wrote, at the layout's rows and images, in place, where the device
//! binds them: the region's first byte, its pitches and its images' 4-byte aligned, and its
//! bytes within `maxStorageBufferRange` of the binding's offset.
//!
//! - **Into a texture over a buffer** ([`BlitCommandEncoder::canonical_texel_words`]): as into a
//! buffer, at the texels' own rows in the buffer's bytes.
//!
//! Each dispatch writes no word but the texels' (the module's contract), so the bytes between a
//! layout's rows and images, and past them, keep what the blit left. A region the device cannot
//! bind is not rewritten: the caller announces the note instead, as under `Kept`.
use super::blit::{reads, writes, writes_by, BlitCommandEncoder, TRANSFER};
use super::blit_plan::{texel_layout, BufferLayout, ImageCopyRegion};
use super::compressed_blit;
use super::copy_plan::ImageRegion;
use super::error::{internal, Error};
use super::owned_kernel::{OwnedBinds, OwnedModule, OwnedSet};
use super::texture::{buffer_image_copy, Texture};
use super::tracker::Access;
use super::values::ResourceOptions;
use super::Buffer;
use ash::vk;
use metal2vulkan::bind::ExtendedCanonicalModule;
/// The canonical encoding's storage access of the words it rewrites: a read and a write in the
/// compute shader stage.
fn storage_access() -> (Access, Access) {
let stage = vk::PipelineStageFlags2::COMPUTE_SHADER;
(
Access::new(stage, vk::AccessFlags2::SHADER_STORAGE_READ),
Access::new(stage, vk::AccessFlags2::SHADER_STORAGE_WRITE),
)
}
/// One dispatch of the kernel: its binding's buffer, offset and range, its shape and workgroups.
struct Dispatch {
binding: (vk::Buffer, u64, u64),
shape: [u8; 16],
groups: [u32; 3],
}
impl BlitCommandEncoder {
/// Rewrite the texels of `regions` of `texture`'s image, which a blit just wrote, in Metal's
/// canonical encoding (the module docs). `false`, with nothing recorded, where a region's
/// texels exceed the device's storage buffer range.
pub(super) fn canonical_texels(
&mut self,
texture: &Texture,
regions: &[ImageRegion],
) -> Result<bool, Error> {
let limits = &self.core().device().properties().description.limits;
let align = limits.min_storage_buffer_offset_alignment.max(8);
let most = u64::from(limits.max_storage_buffer_range);
let (most_groups_y, most_groups_z) = (
limits.max_compute_work_group_count[1],
limits.max_compute_work_group_count[2],
);
// Each region's place in the scratch buffer and its dispatch's shape.
let mut placed = Vec::with_capacity(regions.len());
let mut length = 0u64;
for region in regions {
let [width, height, depth] = region.size;
let images = depth
.checked_mul(region.layers)
.ok_or_else(|| internal("a canonical region's images"))?;
let bytes = u64::from(width) * u64::from(height) * u64::from(images) * 8;
if bytes == 0 {
continue;
}
if bytes > most || height > most_groups_y || images > most_groups_z {
return Ok(false);
}
let at = length.next_multiple_of(align);
let row_words = width
.checked_mul(2)
.ok_or_else(|| internal("a canonical region's rows"))?;
let image_words = row_words
.checked_mul(height)
.ok_or_else(|| internal("a canonical region's images"))?;
placed.push((
*region,
at,
bytes,
ExtendedCanonicalModule::shape(0, width, row_words, image_words),
ExtendedCanonicalModule::groups(width, height, images),
));
length = at + bytes;
}
if placed.is_empty() {
return Ok(true);
}
// The levels and layers the regions span, of the image's own.
let span = |of: fn(&ImageRegion) -> (u32, u32)| {
let starts = placed.iter().map(|p| of(&p.0).0).min().unwrap_or(0);
let ends = placed.iter().map(|p| of(&p.0).1).max().unwrap_or(0);
starts..ends
};
let levels = span(|r| (r.level, r.level + 1));
let layers = span(|r| (r.layer, r.layer + r.layers));
let device = self.core().device().clone();
let scratch = device.own_buffer(length, ResourceOptions::private())?;
let (through, base) = scratch.at(0);
let copies: Vec<vk::BufferImageCopy> = placed
.iter()
.map(|(region, at, ..)| vk::BufferImageCopy {
buffer_offset: base + at,
buffer_row_length: 0,
buffer_image_height: 0,
..buffer_image_copy(region)
})
.collect();
let dispatches: Vec<Dispatch> = placed
.iter()
.map(|&(_, at, bytes, shape, groups)| Dispatch {
binding: (through, base + at, bytes),
shape,
groups,
})
.collect();
let image = texture.raw_image()?;
let whole = 0..length;
let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ);
let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE);
let uses = [
texture.image_use(levels.clone(), layers.clone(), read, false)?,
writes(&scratch, whole.clone()),
];
self.command(&uses, |device, raw| {
// SAFETY: the encoder's command buffer is recording outside a render pass; the image
// and the scratch buffer are live and retained until it completes, the image is in
// the `GENERAL` layout, and each region lies in both.
unsafe {
device.cmd_copy_image_to_buffer(
raw,
image,
vk::ImageLayout::GENERAL,
through,
&copies,
);
}
})?;
self.rewrite(&scratch, whole.clone(), &dispatches)?;
let uses = [
reads(&scratch, whole),
texture.image_use(levels, layers, write, true)?,
];
self.command(&uses, |device, raw| {
// SAFETY: as the copy out above.
unsafe {
device.cmd_copy_buffer_to_image(
raw,
through,
image,
vk::ImageLayout::GENERAL,
&copies,
);
}
})?;
self.core().retain(scratch);
self.core().retain(texture.clone());
Ok(true)
}
/// Rewrite the words of the texels of `size` (width, height and images) that a blit just wrote
/// into `buffer` at `layout`, in Metal's canonical encoding (the module docs). `false`, with
/// nothing recorded, where the device cannot bind them.
pub(super) fn canonical_words(
&mut self,
buffer: &Buffer,
layout: &BufferLayout,
[width, height, images]: [u32; 3],
) -> Result<bool, Error> {
if width == 0 || height == 0 || images == 0 {
return Ok(true);
}
let limits = &self.core().device().properties().description.limits;
let align = limits.min_storage_buffer_offset_alignment.max(4);
let most = u64::from(limits.max_storage_buffer_range);
let most_groups = limits.max_compute_work_group_count;
let (raw, base) = self.core().blit_at(buffer, 0)?;
let start = base + layout.offset;
let row = if height > 1 { layout.bytes_per_row } else { 0 };
let image = if images > 1 {
layout.bytes_per_image
} else {
0
};
let aligned = |v: u64| v.is_multiple_of(4);
if !aligned(start) || !aligned(row) || !aligned(image) {
return Ok(false);
}
let reach = u64::from(images - 1)
.checked_mul(image)
.and_then(|i| i.checked_add(u64::from(height - 1).checked_mul(row)?))
.and_then(|r| r.checked_add(u64::from(width) * 8));
let Some(reach) = reach else {
return Ok(false);
};
let offset = start - start % align;
let range = start - offset + reach;
let groups = ExtendedCanonicalModule::groups(width, height, images);
let words = |v: u64| u32::try_from(v / 4).ok();
let (Some(first), Some(row_words), Some(image_words)) =
(words(start - offset), words(row), words(image))
else {
return Ok(false);
};
if range > most || groups.iter().zip(most_groups).any(|(g, m)| *g > m) {
return Ok(false);
}
let dispatch = Dispatch {
binding: (raw, offset, range),
shape: ExtendedCanonicalModule::shape(first, width, row_words, image_words),
groups,
};
let written = layout.offset..layout.offset + reach;
self.rewrite(buffer, written, &[dispatch])?;
Ok(true)
}
/// Rewrite the texels `copies` wrote into `texture`, a texture over a buffer's bytes, in
/// Metal's canonical encoding, in place at the texels' rows ([`Self::canonical_words`]).
/// `false` where its texels are no `BGRA10_XR` texels at their own rows in a buffer (rows
/// that share bytes, or another format), or where the device cannot bind a region's words:
/// the regions before that one are rewritten.
pub(super) fn canonical_texel_words(
&mut self,
texture: &Texture,
copies: &[ImageCopyRegion],
) -> Result<bool, Error> {
let Some(texels) = texture.buffer_texels() else {
return Ok(false);
};
if !compressed_blit::extended(texture.pixel_format()) || texels.plane_rows_overlap() {
return Ok(false);
}
let unit = texels.unit();
for copy in copies {
let region = &copy.dst;
let [width, height, depth] = region.size;
for layer in 0..region.layers {
let layout = texel_layout(&texels.layout, &unit, region, region.layer + layer);
if !self.canonical_words(&texels.buffer, &layout, [width, height, depth])? {
return Ok(false);
}
}
}
Ok(true)
}
/// Record `dispatches` of the canonical encoding's kernel, which read and write the bytes
/// `range` of `buffer`, as one command.
fn rewrite(
&mut self,
buffer: &Buffer,
range: std::ops::Range<u64>,
dispatches: &[Dispatch],
) -> Result<(), Error> {
let device = self.core().device().clone();
let kernel = device.owned_kernel(OwnedModule::ExtendedCanonical)?;
let sets: Vec<OwnedSet> = dispatches
.iter()
.map(|dispatch| OwnedSet {
images: Vec::new(),
storage_images: Vec::new(),
buffers: vec![dispatch.binding],
})
.collect();
let binds = OwnedBinds::new(&device, &kernel, &sets)?;
let (read, write) = storage_access();
let mut words = writes_by(buffer, range, write);
words.read = read;
let stages = vk::PipelineStageFlags2::COMPUTE_SHADER;
self.command_in(stages, &[words], |functions, raw| {
let point = vk::PipelineBindPoint::COMPUTE;
// SAFETY: the encoder's command buffer is recording outside a render pass; the
// kernel is the device's, the bound words are live and retained until it completes,
// and each shape and its workgroups stay inside its binding (the callers').
unsafe {
functions.cmd_bind_pipeline(raw, point, kernel.pipeline);
for (index, dispatch) in dispatches.iter().enumerate() {
binds.bind(functions, raw, &kernel, index);
functions.cmd_push_constants(
raw,
kernel.layout,
vk::ShaderStageFlags::COMPUTE,
0,
&dispatch.shape,
);
let [x, y, z] = dispatch.groups;
functions.cmd_dispatch(raw, x, y, z);
}
}
})?;
if let OwnedBinds::Sets(sets) = binds {
self.core().retain(sets);
}
Ok(())
}
}
+1
View File
@@ -90,6 +90,7 @@ mod event;
mod event_timeline;
mod exactness;
mod execution;
mod extended_canonical;
mod families;
#[doc(hidden)]
pub use execution::{ExecutedPipeline, Execution};
@@ -93,6 +93,10 @@ pub(super) enum OwnedModule {
/// `bind::rows_copy_module`: many equal rows of words copied from one buffer into another by
/// a dispatch, in place of a copy's region per row (`row_copies.rs`).
RowsCopy,
/// `bind::extended_canonical_module`: Metal's canonical encoding of `BGRA10_XR` texels
/// written in place over a buffer's words, after a blit through a texture Metal keeps
/// losslessly compressed (`extended_canonical.rs`).
ExtendedCanonical,
/// `bind::shadow_merge_image_module` of one read of a texel (`ShadowMergeRead`): a shadowed
/// texture's writes merged into its buffer's bytes, reading its shadow's texels through its
/// unsigned-integer view or its own 8-bit unsigned normalized view, its sampled image
@@ -331,6 +335,12 @@ impl OwnedModule {
let push_bytes = metal2vulkan::bind::RowsCopyModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 2, push_bytes))
}
OwnedModule::ExtendedCanonical => {
let module = metal2vulkan::bind::extended_canonical_module(device.compile_device())
.map_err(Error::Compile)?;
let push_bytes = metal2vulkan::bind::ExtendedCanonicalModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 1, push_bytes))
}
OwnedModule::ShadowMergeImage(read, stores) => {
let module = metal2vulkan::bind::shadow_merge_image_module(
device.compile_device(),
@@ -558,6 +568,7 @@ pub(super) struct OwnedKernels {
index_rewrite_runs: HashMap<RewriteProgram, OwnedKernel>,
rotate_texels: Option<OwnedKernel>,
rows_copy: Option<OwnedKernel>,
extended_canonical: Option<OwnedKernel>,
ycbcr_refresh: Option<OwnedKernel>,
ycbcr_converts: HashMap<(YCbCrConversion, bool), OwnedKernel>,
ycbcr_samples: HashMap<(YCbCrSampler, YCbCrCodes), OwnedKernel>,
@@ -604,6 +615,7 @@ impl OwnedKernels {
self.plane_copy,
self.rotate_texels,
self.rows_copy,
self.extended_canonical,
self.ycbcr_refresh,
self.two_plane_texels,
self.plane_bytes_copy,
@@ -786,6 +798,7 @@ impl OwnedKernels {
OwnedModule::PlaneCopy => &mut self.plane_copy,
OwnedModule::RotateTexels => &mut self.rotate_texels,
OwnedModule::RowsCopy => &mut self.rows_copy,
OwnedModule::ExtendedCanonical => &mut self.extended_canonical,
OwnedModule::YCbCrRefresh => &mut self.ycbcr_refresh,
OwnedModule::TwoPlaneTexels => &mut self.two_plane_texels,
@@ -15,6 +15,14 @@
//! - A copy out into a buffer writes only the texels' bytes at the buffer's rows.
//! - Each format's blits announce the note of the encoding they keep: `extended-range-bits-kept`,
//! `device-nan-encoding`, `shared-exponent-kept`.
//! - Under `ExtendedRangeBlitPolicy::Canonical` a `BGRA10_XR` texture's blits write Metal's
//! encoding (each field's low six bits cleared, the alpha code clamped to `[384, 894]`): a buffer
//! into a compressed texture, it into a buffer (the bytes between the rows kept), and a texture
//! into or out of it, with no `extended-range-bits-kept`; a fill writes its texel with each
//! field's low six bits cleared and the alpha code as given (Metal's fill on the M3 Max under
//! macOS 27.0.1); a copy out into a texture over a buffer writes it at the texels' rows, the
//! bytes between them kept. Under `Kept` each keeps the bytes. An uncompressed texture's keep
//! them under either.
//! - A heap answers a `Shared` compressed texture's size and alignment as a `Private` one's, and
//! two `Shared` textures placed back to back in a heap at that size keep their CPU bytes (on
//! MoltenVK, whose copies of a compressed `RG11B10Float` or `RGB9E5Float` image rewrite texels,
@@ -24,6 +32,7 @@
use super::degrade_notices::counts;
use super::{layer_reported_nothing_at_all, validated_device_with, Messages, ScratchCache};
use crate::gpu::TEST_DEVICE;
use metal2vulkan::device::ExtendedRangeBlitPolicy;
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::{PixelFormat, TextureUsage};
use metal2vulkan_runtime::{
@@ -243,7 +252,11 @@ fn get(texture: &Texture, height: u64, per: u64) -> Vec<u8> {
fn blits_through_a_compressed_texture_keep_their_bytes_and_announce_it() {
let messages = Messages::default();
let cache = ScratchCache::new().unwrap();
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |_| {}).unwrap();
// The lane's devices take `exact_answers()`; the bytes kept are `Kept`'s.
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| {
options.policy.extended_range_blits = ExtendedRangeBlitPolicy::Kept;
})
.unwrap();
let name = device.name().to_owned();
let lane = Lane {
queue: device.new_command_queue().unwrap(),
@@ -401,3 +414,187 @@ fn blits_through_a_compressed_texture_keep_their_bytes_and_announce_it() {
}
layer_reported_nothing_at_all(&messages);
}
/// `bytes`, `BGRA10_XR` texels, as Metal's blit through its compression writes them: each 16-bit
/// field's low six bits cleared, the alpha code (the fourth field) clamped to `[384, 894]`; a
/// fill's (`fill`) the low six bits alone.
fn canonical(bytes: &[u8], fill: bool) -> Vec<u8> {
let mut out = bytes.to_vec();
for texel in out.as_chunks_mut::<8>().0 {
for (k, field) in texel.as_chunks_mut::<2>().0.iter_mut().enumerate() {
let code = u16::from_le_bytes(*field) >> 6;
let code = match (k, fill) {
(3, false) => code.clamp(384, 894),
_ => code,
};
*field = (code << 6).to_le_bytes();
}
}
out
}
/// Under each value of `extended_range_blits`, a `BGRA10_XR` texture Metal keeps compressed takes
/// Metal's encoding through every blit and fill under `Canonical`, and keeps the bytes under `Kept`
/// (the module docs): a buffer into a `Private` texture and back; level 3 of a mipmapped one out
/// into a buffer's padded rows at an offset, the padding kept; a `Shared` texture's CPU bytes
/// (kept under both), blitted out, and a blit's into it read back by the CPU; a copy out of it
/// into a plain texture and from a plain one into it; a fill. An uncompressed texture keeps the
/// bytes under both. A copy out of it into a texture over a buffer whose rows run 256 bytes past
/// its texels' takes Metal's encoding at the texels' rows under `Canonical`, the bytes between
/// them kept. Only `Kept` announces `extended-range-bits-kept`.
#[test]
fn extended_range_blits_write_metal_s_encoding_under_the_canonical_policy() {
let pattern = 0x0123_4567_89ab_cdefu64.to_le_bytes();
for policy in [
ExtendedRangeBlitPolicy::Kept,
ExtendedRangeBlitPolicy::Canonical,
] {
let messages = Messages::default();
let cache = ScratchCache::new().unwrap();
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| {
options.policy.extended_range_blits = policy;
})
.unwrap();
let name = format!("{} under {policy:?}", device.name());
let lane = Lane {
queue: device.new_command_queue().unwrap(),
device,
};
let canon = policy == ExtendedRangeBlitPolicy::Canonical;
let metal = |bytes: &[u8], fill: bool| match canon {
true => canonical(bytes, fill),
false => bytes.to_vec(),
};
let mut rng = Rng(0x10_c0de);
for pf in [PixelFormat::BGRA10XR, PixelFormat::BGRA10XRSRGB] {
let per = 8;
let whole = [SIDE, SIDE];
let n = (SIDE * SIDE * per) as usize;
for (optimized, height, compressed) in
[(true, SIDE, true), (false, SIDE, false), (true, 8, false)]
{
let bytes = rng.bytes((SIDE * height * per) as usize);
let texture = lane.texture(pf, optimized, StorageMode::Private, height, 1);
lane.blit_in(&texture, 0, [SIDE, height], per, &bytes);
let out = lane.blit_out(&texture, 0, [SIDE, height], (0, SIDE * per));
let want = match compressed {
true => metal(&bytes, false),
false => bytes,
};
assert!(
out == want,
"{pf:?} optimized {optimized}, {height} high on {name}"
);
}
// Level 3, out at an offset of 4 into rows 12 bytes longer than the texels'.
let texture = lane.texture(pf, true, StorageMode::Private, SIDE, 4);
let small = [SIDE >> 3, SIDE >> 3];
let bytes = rng.bytes((small[0] * small[1] * per) as usize);
lane.blit_in(&texture, 3, small, per, &bytes);
let row = small[0] * per + 12;
let out = lane.blit_out(&texture, 3, small, (4, row));
let want = metal(&bytes, false);
let texels = (small[0] * per) as usize;
for y in 0..small[1] as usize {
let at = 4 + y * row as usize;
assert!(
out[at..at + texels] == want[y * texels..(y + 1) * texels],
"{pf:?} level 3 row {y} on {name}"
);
assert!(out[at + texels..at + row as usize]
.iter()
.all(|&b| b == 0xee));
}
assert!(out[..4].iter().all(|&b| b == 0xee));
// A Shared texture's CPU bytes, kept; blitted out; a blit's read back by the CPU.
let shared = lane.texture(pf, true, StorageMode::Shared, SIDE, 1);
let bytes = rng.bytes(n);
put(&shared, SIDE, per, &bytes);
assert!(get(&shared, SIDE, per) == bytes, "{pf:?} CPU on {name}");
let out = lane.blit_out(&shared, 0, whole, (0, SIDE * per));
assert!(
out == metal(&bytes, false),
"{pf:?} CPU in, blit out on {name}"
);
let bytes = rng.bytes(n);
lane.blit_in(&shared, 0, whole, per, &bytes);
assert!(
get(&shared, SIDE, per) == metal(&bytes, false),
"{pf:?} blit in, CPU out on {name}"
);
// Out of it into a plain texture, and from a plain one into it.
let plain = lane.texture(pf, false, StorageMode::Shared, SIDE, 1);
let bytes = rng.bytes(n);
put(&shared, SIDE, per, &bytes);
lane.copy(&shared, &plain, SIDE);
assert!(
get(&plain, SIDE, per) == metal(&bytes, false),
"{pf:?} out of compressed on {name}"
);
let bytes = rng.bytes(n);
put(&plain, SIDE, per, &bytes);
lane.copy(&plain, &shared, SIDE);
assert!(
get(&shared, SIDE, per) == metal(&bytes, false),
"{pf:?} into compressed on {name}"
);
// A fill of it, and of the plain one.
let region = Region::new_2d(0, 0, SIDE, SIDE);
for (texture, compressed) in [(&shared, true), (&plain, false)] {
lane.run(|blit| blit.fill_texture(texture, 0, 0, region, &pattern).unwrap());
let texel = match compressed {
true => metal(&pattern, true),
false => pattern.to_vec(),
};
assert!(
get(texture, SIDE, per) == texel.repeat((SIDE * SIDE) as usize),
"{pf:?} fill, compressed {compressed}, on {name}"
);
}
let notices = counts(&messages.take_notices());
eprintln!("EXTENDED-BLITS {pf:?} on {name}: announced {notices:?}");
assert_eq!(
notices.contains_key(&Degradation::ExtendedRangeBitsKept),
!canon && pf == PixelFormat::BGRA10XR,
"{pf:?} on {name}: {notices:?}"
);
}
// Out of a compressed texture into one over a buffer, its rows 256 bytes past the
// texels': Metal's encoding at the texels' rows, the bytes between them kept. `Kept`
// announced the note once above, so neither value announces it again here.
let pf = PixelFormat::BGRA10XR;
let per = 8;
let shared = lane.texture(pf, true, StorageMode::Shared, SIDE, 1);
let row = SIDE * per + 256;
let backing = lane.buffer(&vec![0xee; (row * SIDE) as usize]);
let mut d = TextureDescriptor::texture_2d(pf, SIDE, SIDE, false);
d.usage = TextureUsage::SHADER_READ;
d.resource_options = ResourceOptions::shared();
let over = backing.new_texture(&d, 0, row).unwrap();
let bytes = rng.bytes((SIDE * SIDE * per) as usize);
put(&shared, SIDE, per, &bytes);
lane.copy(&shared, &over, SIDE);
// SAFETY: every command buffer completed; the buffer holds `row * SIDE` bytes.
let held = unsafe {
std::slice::from_raw_parts(backing.contents().unwrap().as_ptr(), (row * SIDE) as usize)
};
let want = metal(&bytes, false);
let texels = (SIDE * per) as usize;
for y in 0..SIDE as usize {
let at = y * row as usize;
assert!(
held[at..at + texels] == want[y * texels..(y + 1) * texels],
"over a buffer row {y} on {name}"
);
assert!(held[at + texels..at + row as usize]
.iter()
.all(|&b| b == 0xee));
}
let notices = counts(&messages.take_notices());
assert!(
!notices.contains_key(&Degradation::ExtendedRangeBitsKept),
"over a buffer on {name}: {notices:?}"
);
layer_reported_nothing_at_all(&messages);
}
}
@@ -0,0 +1,303 @@
//! The canonical encoding that Metal's lossless compression writes of `BGRA10_XR` and
//! `BGRA10_XR_sRGB` texels, written in place over a buffer's texels by a compute dispatch (the
//! runtime's `compressed_blit.rs`, under the policy's `extended_range_blits` `Canonical`).
//!
//! **The encoding.** A texel is four 16-bit fields, blue, green, red and alpha in that order (two
//! little-endian words, blue and green, then red and alpha), each a 10-bit code in its top bits.
//! A blit that reads or writes a texture Metal keeps losslessly compressed writes each field with
//! its low six bits cleared and the alpha code clamped to `[384, 894]`
//! ([`extended_range_canonical`]); the texel reads the same value either way.
//!
//! **The module.** One `GLCompute` entry `main` with local size
//! ([`ExtendedCanonicalModule::LOCAL_SIZE`], 1, 1), [`ExtendedCanonicalModule::PUSH_BYTES`] of
//! `COMPUTE` push constants at offset 0 (the texels' shape, [`ExtendedCanonicalModule::shape`]),
//! and in set 0 one storage buffer ([`ExtendedCanonicalModule::TEXELS_BINDING`]) over the texels'
//! bytes, a whole number of 4-byte words.
//!
//! The shape's words, in order: `first`, the binding's word of the first texel; `width`, the
//! texels a row; `row_words` and `image_words`, the rows and the images apart in words.
//! Invocation `(x, y, z)` with `x` below `width` writes the canonical encoding of the two words at
//! `first + z · image_words + y · row_words + 2x` over them; one past `width` does nothing. A
//! dispatch takes `ceil(width / LOCAL_SIZE)` by the rows by the images workgroups
//! ([`ExtendedCanonicalModule::groups`]). No word between the rows, the images or past them is
//! written.
//!
//! **Synchronization** (consumer): the texels' earlier writes → `SHADER_STORAGE_READ` and
//! `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER` before the dispatch; its writes → the texels' next
//! use.
use std::sync::Arc;
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::Error;
use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, Symbol};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, TypeId, Value};
use crate::spirv::ir::{
natural_layout, BinOp, ExecMode, ExecModel, GlslOp, IoDir, LayoutRule, MemAccess, StorageClass,
Type, TypedModule,
};
/// The canonical encoding of one `BGRA10_XR` texel's words `[blue | green << 16, red | alpha <<
/// 16]`: each field's low six bits cleared, the alpha code clamped to `[384, 894]` (the module
/// docs).
pub fn extended_range_canonical([low, high]: [u32; 2]) -> [u32; 2] {
let alpha = (high >> 22).clamp(384, 894);
[low & 0xFFC0_FFC0, (high & 0xFFC0) | (alpha << 22)]
}
/// The crate-owned canonical-encoding module on one device, validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExtendedCanonicalModule {
/// SPIR-V 1.5 words, entry point `main`, its binding numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device (within every Vulkan 1.2 device).
pub requirements: Requirements,
}
impl ExtendedCanonicalModule {
/// Descriptor set of the binding.
pub const SET: u32 = 0;
/// The texels' bytes, a storage buffer the dispatch reads and writes in place.
pub const TEXELS_BINDING: u32 = 0;
/// Invocations of one workgroup, along x: one texel each, of one row.
pub const LOCAL_SIZE: u32 = 64;
/// Bytes of the `COMPUTE` push-constant range at offset 0: the texels' shape.
pub const PUSH_BYTES: u32 = 16;
/// The push bytes of rows of `width` texels, the first texel at word `first` of the binding,
/// the rows `row_words` and the images `image_words` apart (the module docs).
pub fn shape(first: u32, width: u32, row_words: u32, image_words: u32) -> [u8; 16] {
let words = [first, width, row_words, image_words];
let mut bytes = [0; 16];
for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) {
chunk.copy_from_slice(&word.to_le_bytes());
}
bytes
}
/// The workgroups of a dispatch over `images` images of `rows` rows of `width` texels.
pub fn groups(width: u32, rows: u32, images: u32) -> [u32; 3] {
[width.div_ceil(Self::LOCAL_SIZE), rows, images]
}
}
/// The binding symbol of the texels' bytes in the typed module.
const TEXELS: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 0,
};
/// The push field the shape is declared under: a crate-owned module's own words, which no
/// selection places.
const SHAPE: PushField = PushField::DispatchRegion;
/// A `Block { u32 words[]; }` storage buffer bound at `sym`.
fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResult<GlobalId> {
let rta = b.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})?;
let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?;
let block = b.ty(Type::Struct {
members: [rta].into(),
layout: Some(layout),
})?;
b.resource(sym, StorageClass::StorageBuffer, block)
}
fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
let c = f.u32_const(v)?;
f.module().const_value(c)
}
/// The canonical-encoding module as a typed module, before serialization: the module
/// [`extended_canonical_module`] serializes, which the CPU interpreter runs. Its binding is the
/// symbol `TEXELS`, and its push field the shape, a `uvec4` (the module docs).
fn typed_module() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?;
let m_shape = b.push_member(SHAPE, uvec4, 0)?;
let push = b.push_global()?;
let texels = words_buffer(&mut b, TEXELS, u32_)?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let zero = u32_value(&mut f, 0)?;
let invocation = f.module().global_value(invocation)?;
let invocation = f.load(invocation, MemAccess::default())?;
let x = f.composite_extract(invocation, &[0])?;
let y = f.composite_extract(invocation, &[1])?;
let z = f.composite_extract(invocation, &[2])?;
let texels = f.module().global_value(texels)?;
let push = f.module().global_value(push)?;
let member = u32_value(&mut f, m_shape.index)?;
let shape = f.access_chain(push, &[member])?;
let shape = f.load(shape, MemAccess::default())?;
let first = f.composite_extract(shape, &[0])?;
let width = f.composite_extract(shape, &[1])?;
let row_words = f.composite_extract(shape, &[2])?;
let image_words = f.composite_extract(shape, &[3])?;
let inside = f.binary(BinOp::ULessThan, x, width)?;
let encode: ArmFn<'_, ()> = Box::new(move |f, _| {
let one = u32_value(f, 1)?;
let at = f.binary(BinOp::IMul, z, image_words)?;
let at = f.binary(BinOp::IAdd, first, at)?;
let row = f.binary(BinOp::IMul, y, row_words)?;
let at = f.binary(BinOp::IAdd, at, row)?;
let texel = f.binary(BinOp::ShiftLeftLogical, x, one)?;
let low_at = f.binary(BinOp::IAdd, at, texel)?;
let high_at = f.binary(BinOp::IAdd, low_at, one)?;
let low_ptr = f.access_chain(texels, &[zero, low_at])?;
let high_ptr = f.access_chain(texels, &[zero, high_at])?;
let low = f.load(low_ptr, MemAccess::default())?;
let high = f.load(high_ptr, MemAccess::default())?;
// Each field's low six bits cleared; the alpha code clamped to [384, 894].
let fields = u32_value(f, 0xFFC0_FFC0)?;
let low = f.binary(BinOp::BitwiseAnd, low, fields)?;
let red_field = u32_value(f, 0xFFC0)?;
let red = f.binary(BinOp::BitwiseAnd, high, red_field)?;
let shift = u32_value(f, 22)?;
let alpha = f.binary(BinOp::ShiftRightLogical, high, shift)?;
let least = u32_value(f, 384)?;
let most = u32_value(f, 894)?;
let alpha = f.glsl(GlslOp::UClamp, &[alpha, least, most])?;
let alpha = f.binary(BinOp::ShiftLeftLogical, alpha, shift)?;
let high = f.binary(BinOp::BitwiseOr, red, alpha)?;
f.store(low_ptr, low, MemAccess::default())?;
f.store(high_ptr, high, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, encode, None)?;
f.ret(None)?;
let id = f.finish()?;
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize {
x: ExtendedCanonicalModule::LOCAL_SIZE,
y: 1,
z: 1,
}],
)?;
b.finalize()
}
/// The fixed binding numbers of the module's symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(ExtendedCanonicalModule::SET),
Symbol::Binding(s) if *s == TEXELS => Some(ExtendedCanonicalModule::TEXELS_BINDING),
_ => None,
}
}
/// The canonical-encoding module of `device`: built with the typed builder, checked by the owned
/// verifier against the device's profile (requirements included), serialized, and numbered with
/// the fixed binding of [`ExtendedCanonicalModule`].
pub fn extended_canonical_module(device: &Device) -> Result<ExtendedCanonicalModule, Error> {
let profile = device.profile();
let m = typed_module()?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
profile.check(&r.requirements).map_err(|c| {
Error::Internal(crate::error::InternalError::new(
crate::error::InternalKind::RequirementsExceedProfile,
format!("the extended-range canonical encoding needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &binding_of)?;
Ok(ExtendedCanonicalModule {
spirv: words.into(),
requirements: r.requirements,
})
}
#[cfg(test)]
mod tests {
use super::{extended_range_canonical, typed_module, ExtendedCanonicalModule, TEXELS};
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::testing::{assert_valid, committed_profiles};
#[test]
fn the_canonical_kernel_is_valid_on_every_committed_profile() {
for (_, p) in committed_profiles().expect("profiles") {
assert_valid(typed_module().expect("module"), &p);
}
}
/// Every word of a buffer after one dispatch over two images of three rows of five texels,
/// the first texel at word 2, rows 14 words apart and images 50: each texel inside the shape
/// its canonical encoding, every other word as it was, in both invocation orders.
#[test]
fn the_kernel_writes_each_texel_s_canonical_encoding_and_nothing_else() {
let mut state = 0x2545_f491u32;
let mut next = || {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
state
};
let words: Vec<u32> = (0..110).map(|_| next()).collect();
let (first, width, row_words, image_words) = (2u32, 5u32, 14u32, 50u32);
let mut want = words.clone();
for z in 0..2 {
for y in 0..3 {
for x in 0..width {
let at = (first + z * image_words + y * row_words + 2 * x) as usize;
let [low, high] = extended_range_canonical([want[at], want[at + 1]]);
(want[at], want[at + 1]) = (low, high);
}
}
}
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let m = typed_module().expect("module");
for order in [Order::Forward, Order::Reverse] {
let cfg = Config {
workgroups: ExtendedCanonicalModule::groups(width, 3, 2),
order,
..Config::default()
};
let res = Resources {
buffers: vec![Buffer {
slot: Some(TEXELS),
address: None,
bytes: bytes.clone(),
}],
push: ExtendedCanonicalModule::shape(first, width, row_words, image_words).to_vec(),
spec: Default::default(),
};
let out = run(&m, &cfg, res).expect("run");
let got: Vec<u32> = (out.buffers[0].as_chunks::<4>().0.iter())
.map(|b| u32::from_le_bytes(*b))
.collect();
assert_eq!(got, want, "{order:?}");
}
}
/// The encoding clears each field's six low bits and clamps the alpha code alone.
#[test]
fn the_encoding_clears_the_low_bits_and_clamps_alpha() {
assert_eq!(
extended_range_canonical([0xFFFF_FFFF, 0xFFFF_FFFF]),
[0xFFC0_FFC0, 0xDF80_FFC0]
);
assert_eq!(extended_range_canonical([0, 0]), [0, 384 << 22]);
assert_eq!(
extended_range_canonical([0, 600 << 22 | 0x3F]),
[0, 600 << 22]
);
}
}
+7 -1
View File
@@ -86,7 +86,9 @@
//! [`shadow_copy_in_module`] copies a merged texture's texels in and keeps them with one dispatch.
//! A copy of many
//! equal rows between two buffers is one dispatch of [`rows_copy_module`] where a copy's region
//! per row costs more. A blit between a buffer
//! per row costs more. A blit through a `BGRA10_XR` texture Metal keeps losslessly compressed
//! writes Metal's canonical encoding of its texels through [`extended_canonical_module`] where
//! the policy asks for it. A blit between a buffer
//! and a two-plane extended-range texture moves its color words through [`plane_words_module`],
//! and a blit between two such textures moves both planes as Metal's blit does through
//! [`plane_copy_module`]. A rotated texture's texels move between its
@@ -135,6 +137,7 @@ pub(crate) mod depth_stencil_resolve;
pub(crate) mod dispatch;
pub(crate) mod dynamic_views;
pub(crate) mod etc_decode;
pub(crate) mod extended_canonical;
pub(crate) mod extended_shadow;
pub(crate) mod graphics;
pub(crate) mod heap;
@@ -206,6 +209,9 @@ pub use depth_stencil_resolve::{
};
pub use dispatch::{Dispatch, DispatchCommands, DispatchRegion, IndirectArgs};
pub use etc_decode::{etc_decode_module, EtcDecode, EtcTexels};
pub use extended_canonical::{
extended_canonical_module, extended_range_canonical, ExtendedCanonicalModule,
};
pub use extended_shadow::{extended_shadow_module, ExtendedShadowModule};
pub use graphics::{
DrawCall, DrawCommands, IndexOverrun, MeshDispatch, MeshGroups, MeshRecordsRegion,
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 483;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1728;
pub const RUNTIME_VERSION: u32 = 1731;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
+3 -3
View File
@@ -66,9 +66,9 @@ pub use enables::{EnableSet, Exposure};
pub(crate) use mechanism::mechanism;
pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd};
pub use policy::{
BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DevicePolicy, HalfChainPolicy,
HeapCompressionPolicy, HostPageTexturePolicy, PipelineWaitPolicy, RenderLoweringPolicy,
WideLinePolicy,
BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DevicePolicy, ExtendedRangeBlitPolicy,
HalfChainPolicy, HeapCompressionPolicy, HostPageTexturePolicy, PipelineWaitPolicy,
RenderLoweringPolicy, WideLinePolicy,
};
pub(crate) use profile::whole_point_size;
pub use profile::{DeviceProfile, SpirvValidation};
+46 -9
View File
@@ -6,12 +6,13 @@ use std::time::Duration;
/// Policy inputs of `Device::new`. Every field but `heap_compression`, `completion`,
/// `batch_order`, `render_lowering`, `host_page_textures`, `pipeline_waits`,
/// `pipeline_creation_wait`, `pipeline_commit_wait` and `wide_lines` can change emitted code, so
/// the profile carries it (containment as the encoding it selects) and its fingerprint covers it;
/// those nine are the runtime's alone (a heap's compressed texture's image, when the host sees a
/// command buffer complete, how a batch begins after the earlier ones of its queue, where a render
/// encoder's calls are lowered, what holds a sampled texture over host pages, whether and how
/// long a pipeline the driver is still making is waited for, and which lines draw a wide line),
/// `pipeline_creation_wait`, `pipeline_commit_wait`, `wide_lines` and `extended_range_blits` can
/// change emitted code, so the profile carries it (containment as the encoding it selects) and
/// its fingerprint covers it; those ten are the runtime's alone (a heap's compressed texture's
/// image, when the host sees a command buffer complete, how a batch begins after the earlier ones
/// of its queue, where a render encoder's calls are lowered, what holds a sampled texture over
/// host pages, whether and how long a pipeline the driver is still making is waited for, which
/// lines draw a wide line, and what a blit through a compressed extended-range texture writes),
/// and no profile carries them.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -81,6 +82,10 @@ pub struct DevicePolicy {
/// the pipeline's band variant, two triangles that cover Metal's parallelogram. The runtime's
/// choice alone: no emitted code of a pipeline changes, the band being a variant of its own.
pub wide_lines: WideLinePolicy,
/// Whether a blit or fill through a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps
/// losslessly compressed keeps the texels' bytes (the default) or writes Metal's canonical
/// encoding of them. The runtime's choice alone: no emitted code changes.
pub extended_range_blits: ExtendedRangeBlitPolicy,
}
impl DevicePolicy {
@@ -106,6 +111,7 @@ impl DevicePolicy {
pipeline_creation_wait: Duration::from_millis(4500),
pipeline_commit_wait: Duration::from_millis(4500),
wide_lines: WideLinePolicy::Device,
extended_range_blits: ExtendedRangeBlitPolicy::Kept,
};
/// This policy with Metal's answer wherever the choices offer it: a heap's texture whose bytes
@@ -119,9 +125,10 @@ impl DevicePolicy {
/// copies touch its texels alone ([`HostPageTexturePolicy::Shadow`]), each `half`
/// operation rounded on a device without `shaderFloat16` ([`HalfChainPolicy::EachOperation`]),
/// a render state's predicted pipeline made at its creation, each draw's pipeline waited
/// for until it is made ([`PipelineWaitPolicy::Exact`]), and every wide line Metal's
/// parallelogram where the device's own line differs ([`WideLinePolicy::Exact`]). Every other
/// field is kept.
/// for until it is made ([`PipelineWaitPolicy::Exact`]), every wide line Metal's
/// parallelogram where the device's own line differs ([`WideLinePolicy::Exact`]), and every
/// blit and fill through a compressed `BGRA10_XR` texture Metal's canonical encoding of its
/// texels ([`ExtendedRangeBlitPolicy::Canonical`]). Every other field is kept.
pub const fn exact_answers(self) -> DevicePolicy {
DevicePolicy {
heap_compression: HeapCompressionPolicy::Uncompressed,
@@ -132,6 +139,7 @@ impl DevicePolicy {
half_chains: HalfChainPolicy::EachOperation,
pipeline_waits: PipelineWaitPolicy::Exact,
wide_lines: WideLinePolicy::Exact,
extended_range_blits: ExtendedRangeBlitPolicy::Canonical,
..self
}
}
@@ -373,3 +381,32 @@ pub enum WideLinePolicy {
/// announced as under `Device`.
Exact,
}
/// What a blit or fill writes through a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps
/// losslessly compressed (`allowGPUOptimizedContents`, the shorter side of level 0 16 texels or
/// more, neither `ShaderWrite` nor `PixelFormatView` usage, one sample, not over a buffer). Metal's
/// GPU blit that reads or writes such a texture (a buffer into it, it into a buffer, a texture into
/// it or out of it) moves the texels through its compression, which writes their canonical
/// encoding: each 16-bit field's low six bits cleared and the alpha code clamped to `[384, 894]`;
/// its fill clears the low six bits alone. The texel reads the same value either way: the low six
/// bits are not read, and a read clamps the alpha. Measured on an Apple M3 Max under macOS 27.0.1:
/// random texels through each direction, both formats, every storage mode, the usages and sizes
/// that decide the compression; CPU copies (`replaceRegion`, `getBytes`) keep the bytes on Metal
/// too. The runtime's choice alone: no emitted code changes.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExtendedRangeBlitPolicy {
/// The device's copy, which keeps the bytes it moves (the default): no work past the copy.
/// Announced `extended-range-bits-kept` at the first such blit or fill.
#[default]
Kept,
/// Metal's canonical encoding: after a blit writes such a texture's region, or a blit out of
/// one writes a buffer's or another texture's, a compute dispatch rewrites the texels it
/// wrote (an image's through a scratch buffer, a copy in and out around the dispatch; a
/// buffer's or a texture over a buffer's in place); a fill's texel is encoded before it is
/// written. A blit out of one into a buffer whose bytes the device cannot bind there (an
/// offset or pitch off 4 bytes, a region past `maxStorageBufferRange`), or into a texture over
/// a buffer whose rows share bytes, keeps the bytes, announced as under `Kept`.
Canonical,
}
@@ -3914,7 +3914,7 @@ fn pack_conversions_are_metals_where_measured() {
};
b.push_str(&format!(" %v = call {vty} @{call}({iw} {w})\n"));
b.push_str(&format!(" %x = extractelement {vty} %v, i32 0\n"));
b.push_str(&match half {
b.push_str(match half {
true => " %b = bitcast half %x to i16\n %r = zext i16 %b to i32\n",
false => " %r = bitcast float %x to i32\n",
});
+40 -3
View File
@@ -6,8 +6,9 @@
//! classed, and so reaches the ledger.
use crate::device::{
BatchOrderPolicy, CompletionPolicy, DevicePolicy, HalfChainPolicy, HeapCompressionPolicy,
HostPageTexturePolicy, PipelineWaitPolicy, RenderLoweringPolicy, WideLinePolicy,
BatchOrderPolicy, CompletionPolicy, DevicePolicy, ExtendedRangeBlitPolicy, HalfChainPolicy,
HeapCompressionPolicy, HostPageTexturePolicy, PipelineWaitPolicy, RenderLoweringPolicy,
WideLinePolicy,
};
use crate::pipeline::PrecisionNote;
use std::collections::BTreeSet;
@@ -61,7 +62,8 @@ fn choices() -> Vec<Choice> {
// complete, how a batch begins after the earlier ones of its queue, where a render
// encoder's calls are lowered, what holds a sampled texture over host pages, whether and
// how long a pipeline being made is waited for (the bounds' values:
// `the_ledger_states_the_pipeline_wait_bounds`), and which lines draw a wide line.
// `the_ledger_states_the_pipeline_wait_bounds`), which lines draw a wide line, and what a
// blit through a compressed extended-range texture writes.
heap_compression: _,
completion: _,
batch_order: _,
@@ -71,6 +73,7 @@ fn choices() -> Vec<Choice> {
pipeline_creation_wait: _,
pipeline_commit_wait: _,
wide_lines: _,
extended_range_blits: _,
// The translator's: how a `half` chain rounds without `shaderFloat16`.
half_chains: _,
} = p;
@@ -83,6 +86,7 @@ fn choices() -> Vec<Choice> {
choice!(p.half_chains: HalfChainPolicy { AtExits, EachOperation }),
choice!(p.pipeline_waits: PipelineWaitPolicy { Bounded, Exact }),
choice!(p.wide_lines: WideLinePolicy { Device, Exact }),
choice!(p.extended_range_blits: ExtendedRangeBlitPolicy { Kept, Canonical }),
]
}
@@ -534,6 +538,39 @@ fn exact_answers_draw_wide_lines_as_metal_s_parallelogram() {
);
}
/// The runtime's choice of what a blit through a compressed `BGRA10_XR` texture writes
/// (`extended_range_blits`) moves no committed profile's fingerprint: no profile carries it, so no
/// translation follows it.
#[test]
fn the_runtime_s_extended_range_blits_choice_keys_no_profile() {
use crate::spirv::testing::committed_profiles_with;
let kept = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles");
let canonical = committed_profiles_with(DevicePolicy {
extended_range_blits: ExtendedRangeBlitPolicy::Canonical,
..DevicePolicy::UNTRUSTED
})
.expect("profiles");
assert_eq!(kept.len(), canonical.len());
for ((stem, k), (other, c)) in kept.iter().zip(&canonical) {
assert_eq!(stem, other);
assert_eq!(k.fingerprint(), c.fingerprint(), "{stem}");
}
}
/// `DevicePolicy::exact_answers()` writes Metal's canonical encoding through a compressed
/// `BGRA10_XR` texture's blits, and the default keeps the bytes.
#[test]
fn exact_answers_write_metal_s_canonical_extended_range_texels() {
assert_eq!(
DevicePolicy::UNTRUSTED.extended_range_blits,
ExtendedRangeBlitPolicy::Kept
);
assert_eq!(
DevicePolicy::UNTRUSTED.exact_answers().extended_range_blits,
ExtendedRangeBlitPolicy::Canonical
);
}
/// The ledger's row of the pipeline waits states each bound as the default policy sets it, as
/// `field = N s`: a changed bound changes its row.
#[test]
@@ -103,6 +103,10 @@ assoc-const metal2vulkan::bind::DynamicViewsModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::EtcDecode::ALL pub const ALL: [EtcDecode; 7]
assoc-const metal2vulkan::bind::ExecutionStatus::BYTES pub const BYTES: usize
assoc-const metal2vulkan::bind::ExecutionStatus::WORDS pub const WORDS: usize
assoc-const metal2vulkan::bind::ExtendedCanonicalModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::ExtendedCanonicalModule::PUSH_BYTES pub const PUSH_BYTES: u32
assoc-const metal2vulkan::bind::ExtendedCanonicalModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::ExtendedCanonicalModule::TEXELS_BINDING pub const TEXELS_BINDING: u32
assoc-const metal2vulkan::bind::ExtendedShadowModule::CODES_BINDING pub const CODES_BINDING: u32
assoc-const metal2vulkan::bind::ExtendedShadowModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::ExtendedShadowModule::SET pub const SET: u32
@@ -571,6 +575,10 @@ assoc-const-value metal2vulkan::bind::DynamicViewsModule::SET 0
assoc-const-value metal2vulkan::bind::EtcDecode::ALL [EtcDecode::Rgb8, EtcDecode::Rgb8A1, EtcDecode::Rgba8, EtcDecode::R11Unorm, EtcDecode::R11Snorm, EtcDecode::Rg11Unorm, EtcDecode::Rg11Snorm]
assoc-const-value metal2vulkan::bind::ExecutionStatus::BYTES 32
assoc-const-value metal2vulkan::bind::ExecutionStatus::WORDS 8
assoc-const-value metal2vulkan::bind::ExtendedCanonicalModule::LOCAL_SIZE 64
assoc-const-value metal2vulkan::bind::ExtendedCanonicalModule::PUSH_BYTES 16
assoc-const-value metal2vulkan::bind::ExtendedCanonicalModule::SET 0
assoc-const-value metal2vulkan::bind::ExtendedCanonicalModule::TEXELS_BINDING 0
assoc-const-value metal2vulkan::bind::ExtendedShadowModule::CODES_BINDING 0
assoc-const-value metal2vulkan::bind::ExtendedShadowModule::LOCAL_SIZE 8
assoc-const-value metal2vulkan::bind::ExtendedShadowModule::SET 0
@@ -1389,6 +1397,7 @@ enum metal2vulkan::device::ContainmentPolicy #[cfg_attr(feature = "serde", deriv
enum metal2vulkan::device::DriverFact #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DriverFact
enum metal2vulkan::device::DriverWorkaround #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DriverWorkaround
enum metal2vulkan::device::Exposure #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Exposure
enum metal2vulkan::device::ExtendedRangeBlitPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ExtendedRangeBlitPolicy
enum metal2vulkan::device::FloatControl #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FloatControl
enum metal2vulkan::device::FloatWidth #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FloatWidth
enum metal2vulkan::device::FormatUsage #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FormatUsage
@@ -3203,6 +3212,8 @@ field metal2vulkan::bind::DrawReplayPreprocess.push_holes pub push_holes: Vec<Pu
field metal2vulkan::bind::DrawReplayPreprocess.resident pub resident: RootTable
field metal2vulkan::bind::DynamicViewsModule.requirements pub requirements: Requirements
field metal2vulkan::bind::DynamicViewsModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::ExtendedCanonicalModule.requirements pub requirements: Requirements
field metal2vulkan::bind::ExtendedCanonicalModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::ExtendedShadowModule.requirements pub requirements: Requirements
field metal2vulkan::bind::ExtendedShadowModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::FlatDispatchModule.layout pub layout: PipelineLayout
@@ -3706,6 +3717,7 @@ field metal2vulkan::device::DeviceDescription.vendor_id pub vendor_id: u32
field metal2vulkan::device::DevicePolicy.batch_order pub batch_order: BatchOrderPolicy
field metal2vulkan::device::DevicePolicy.completion pub completion: CompletionPolicy
field metal2vulkan::device::DevicePolicy.containment pub containment: ContainmentPolicy
field metal2vulkan::device::DevicePolicy.extended_range_blits pub extended_range_blits: ExtendedRangeBlitPolicy
field metal2vulkan::device::DevicePolicy.half_chains pub half_chains: HalfChainPolicy
field metal2vulkan::device::DevicePolicy.handle_domain pub handle_domain: HandleDomain
field metal2vulkan::device::DevicePolicy.heap_compression pub heap_compression: HeapCompressionPolicy
@@ -4593,6 +4605,8 @@ fn metal2vulkan::bind::draw_replay_slots pub fn draw_replay_slots(interface: &Pi
fn metal2vulkan::bind::draw_replay_state pub fn draw_replay_state(graphics: &GraphicsState, merged: bool) -> Result<(), DrawReplayRule>
fn metal2vulkan::bind::dynamic_views_module pub fn dynamic_views_module(device: &Device) -> Result<DynamicViewsModule, Error>
fn metal2vulkan::bind::etc_decode_module pub fn etc_decode_module(device: &Device, decode: EtcDecode, texels: EtcTexels) -> Result<BlockDecodeModule, Error>
fn metal2vulkan::bind::extended_canonical_module pub fn extended_canonical_module(device: &Device) -> Result<ExtendedCanonicalModule, Error>
fn metal2vulkan::bind::extended_range_canonical pub fn extended_range_canonical([low, high]: [u32; 2]) -> [u32; 2]
fn metal2vulkan::bind::extended_shadow_module pub fn extended_shadow_module(device: &Device, form: ExtendedRange) -> Result<ExtendedShadowModule, Error>
fn metal2vulkan::bind::flat_dispatch_module pub fn flat_dispatch_module(device: &Device) -> Result<FlatDispatchModule, Error>
fn metal2vulkan::bind::fold_object_grid pub fn fold_object_grid(groups: [u32; 3], threads: [u32; 3], task: MeshGridLimits, direct: bool) -> Option<ObjectFold>
@@ -8421,6 +8435,8 @@ method metal2vulkan::bind::EtcDecode::texel_format pub fn texel_format(self, tex
method metal2vulkan::bind::EtcDecode::texel_pixel_format pub fn texel_pixel_format(self, texels: EtcTexels) -> PixelFormat
method metal2vulkan::bind::ExecutionStatus::decode pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport
method metal2vulkan::bind::ExecutionStatus::initial pub const fn initial() -> [u8; ExecutionStatus::BYTES]
method metal2vulkan::bind::ExtendedCanonicalModule::groups pub fn groups(width: u32, rows: u32, images: u32) -> [u32; 3]
method metal2vulkan::bind::ExtendedCanonicalModule::shape pub fn shape(first: u32, width: u32, row_words: u32, image_words: u32) -> [u8; 16]
method metal2vulkan::bind::FlatArguments::bytes pub fn bytes(self) -> u64
method metal2vulkan::bind::FlatDispatchModule::push_constants pub fn push_constants(scratch: u64, status: u64) -> [u8; 16]
method metal2vulkan::bind::FlatIndirect::inputs pub fn inputs(&self) -> [u8; 32]
@@ -9504,6 +9520,7 @@ struct metal2vulkan::bind::DrawReplayModule #[derive(Clone, Debug, PartialEq, Eq
struct metal2vulkan::bind::DrawReplayPreprocess #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DrawReplayPreprocess
struct metal2vulkan::bind::DynamicViewsModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DynamicViewsModule
struct metal2vulkan::bind::ExecutionStatus #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ExecutionStatus
struct metal2vulkan::bind::ExtendedCanonicalModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ExtendedCanonicalModule
struct metal2vulkan::bind::ExtendedShadowModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ExtendedShadowModule
struct metal2vulkan::bind::FlatDispatchModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FlatDispatchModule
struct metal2vulkan::bind::FlatIndirect #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct FlatIndirect
@@ -12514,6 +12531,8 @@ variant metal2vulkan::device::Exposure::Core Core(ApiVersion)
variant metal2vulkan::device::Exposure::Extension Extension(&'static [VkExtension])
variant metal2vulkan::device::Exposure::Implied Implied { version: ApiVersion, extensions: &'static [VkExtension] }
variant metal2vulkan::device::Exposure::Promoted Promoted { version: ApiVersion, extensions: &'static [VkExtension] }
variant metal2vulkan::device::ExtendedRangeBlitPolicy::Canonical Canonical
variant metal2vulkan::device::ExtendedRangeBlitPolicy::Kept Kept
variant metal2vulkan::device::FloatControl::DenormFlushToZero DenormFlushToZero
variant metal2vulkan::device::FloatControl::DenormPreserve DenormPreserve
variant metal2vulkan::device::FloatControl::RoundingModeRte RoundingModeRte
Can't render this file because it is too large.
+4
View File
@@ -232,6 +232,7 @@ surface! {
enum HalfChainPolicy N;
enum PipelineWaitPolicy N;
enum WideLinePolicy N;
enum ExtendedRangeBlitPolicy N;
struct DeviceProfile O;
struct SpirvValidation N;
struct EnabledCaps N;
@@ -641,6 +642,9 @@ surface! {
struct ShadowCopyInModule N;
fn rows_copy_module;
struct RowsCopyModule N;
fn extended_canonical_module;
fn extended_range_canonical;
struct ExtendedCanonicalModule N;
fn dynamic_views_module;
struct DynamicViewsModule N;
fn shadow_merge_module;
+24 -6
View File
@@ -100,8 +100,9 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`:
with their bounds. On MoltenVK on an Apple GPU, whose sampler and `float` functions are Metal's
own, most of them change nothing.
- `DevicePolicy::exact_answers()` selects Metal's answer for each of the runtime's choices that
offers one (the batch order, render lowering and wide lines below, the heap texture
compression, command buffer completion and textures over host pages) and the AIR's rounding of each `half` operation
offers one (the batch order, render lowering, wide lines and extended-range blits below, the
heap texture compression, command buffer completion and textures over host pages) and the AIR's
rounding of each `half` operation
on a device without `shaderFloat16` (below), each listed in [FAST-PATHS.md](FAST-PATHS.md)
with its bound and the measured cost of its exact form.
- **`half` chains held at `float` precision without `shaderFloat16`** (`HalfChainPolicy::AtExits`,
@@ -203,6 +204,19 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`:
device with `tessellationShader`. Every other width other than 1 is the band under either value,
and what neither draws the device's lines at the nearest width they draw, announced
`lines-at-nearest-width` (the runtime's README, line widths).
- **A compressed extended-range texture's blits keep the bytes** (`ExtendedRangeBlitPolicy::Kept`,
the default; the runtime's choice, no pipeline differs). Metal's GPU blit into, out of or between
`BGRA10_XR` or `BGRA10_XR_sRGB` textures it keeps losslessly compressed
(`allowGPUOptimizedContents`, 16 texels or more a side, neither `ShaderWrite` nor
`PixelFormatView` usage) writes each texel's canonical encoding, each 16-bit field's low six bits
cleared and the alpha code clamped to `[384, 894]`, and its fill clears the low six bits alone;
the device's copy keeps the bytes, the same value, announced `extended-range-bits-kept`.
`extended_range_blits = ExtendedRangeBlitPolicy::Canonical`, which `exact_answers()` selects,
writes Metal's encoding: a compute dispatch after each such blit rewrites the texels it wrote (an
image's through a scratch copy, a buffer's or a texture over a buffer's in place), and a fill's
texel is encoded before it is written. A blit out of one into a buffer whose words the device
cannot bind (an offset or pitch off 4 bytes, past `maxStorageBufferRange`), or into a texture over
a buffer whose rows share bytes, keeps the bytes under either value, announced.
Loops run as written: no execution bound is translated in.
@@ -2177,10 +2191,14 @@ bound.
(`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12` and their sRGB twins,
`RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat` and `RGBA16Bfloat`) and does not discard it at the
store, on every device: the device's pass keeps the bytes its draws do not write, where Metal's
pass writes each 32 x 32 tile a draw reaches back through its tile store. Also, once per device, a
GPU blit into, out of or between textures of which one is a `BGRA10_XR` or `BGRA10_XR_sRGB`
texture Metal keeps losslessly compressed: Metal's blit moves the texels through the compression,
which clears the same bits and clamps the same alpha, where the device's copy keeps the bytes.
pass writes each 32 x 32 tile a draw reaches back through its tile store. Also, once per device
under `ExtendedRangeBlitPolicy::Kept` (the default), a GPU blit into, out of or between textures
of which one is a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed, and a
fill of one: Metal's blit moves the texels through the compression, which clears the same bits
and clamps the same alpha (its fill clears the bits alone), where the device's copy keeps the
bytes. Under `extended_range_blits = ExtendedRangeBlitPolicy::Canonical` the runtime writes
Metal's encoding (section 1), and announces only a blit out of one into a buffer whose words the
device cannot bind or into a texture over a buffer whose rows share bytes.
Cost: the texels the pass's draws do not write keep their bytes; Metal's pass rewrites, in each
tile a draw reaches, the bits their codes leave unused (BGR10_XR's bits 30 and 31 to ones,
BGRA10_XR's low six bits of each field, the two-plane color word's top two bits and a padded
+1 -29
View File
@@ -44,7 +44,7 @@ Its limits, measured rather than asserted:
| committed recordings | 1122 |
| distinct SDK items the Metal leg reaches, of any status | 800 |
| of those, reached only where this cannot name the family | 2 |
| ledger rows (a case whose gap is recorded) | 1324 |
| ledger rows (a case whose gap is recorded) | 1296 |
| declared crossings of the option space (pairs put to Metal at once) | 26 |
| declared crossings that are no pair of it (a boolean or numeric field, or one type in two slots) | 30 |
@@ -3143,20 +3143,6 @@ A case whose difference from Metal is recorded rather than compared away. The le
| `astc-12x12-srgb` | A read of an ASTC sRGB form's texels through its decoded twin's `R8G8B8A8_SRGB` view, which holds Metal's own codes: the device decodes each 8-bit code by its o… |
| `read-write-tier-round-trip-float` | A read of the round-tripped 8-bit sRGB texels through the texture's sRGB view: the device decodes each 8-bit code by its own sRGB transfer function, where Metal… |
| `read-write-tier-round-trip-float` | A read of the round-tripped 8-bit sRGB texels through the texture's sRGB view: the device decodes each 8-bit code by its own sRGB transfer function, where Metal… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-rg11b10f` | Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field'… |
| `compressed-blits-rg11b10f` | Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field'… |
| `compressed-blits-rg11b10f` | Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field'… |
@@ -3171,20 +3157,6 @@ A case whose difference from Metal is recorded rather than compared away. The le
| `compressed-blits-rgb9e5f` | Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and … |
| `compressed-blits-rgb9e5f` | Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and … |
| `compressed-blits-rgb9e5f` | Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and … |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr` | Metal's blit through the lossless compression it keeps this `BGRA10_XR` texture in writes each texel in its canonical encoding -- each 16-bit field's low six bi… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-bgra10xr-srgb` | Metal's blit through the lossless compression it keeps this `BGRA10_XR_sRGB` texture in writes each texel in its canonical encoding -- each 16-bit field's low s… |
| `compressed-blits-rg11b10f` | Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field'… |
| `compressed-blits-rg11b10f` | Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field'… |
| `compressed-blits-rg11b10f` | Metal's blit through the lossless compression it keeps this `RG11B10Float` texture in makes each NaN field the quiet NaN, and the device's copy keeps the field'… |
+1
View File
@@ -40,6 +40,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X
| A texture that only samples or reads (no `RenderTarget`, `ShaderWrite` or `ShaderAtomic` usage) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device's own check shows that the image's first move, which Vulkan lets read and write every byte bound to it (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), leaves every byte alone while the CPU writes beside it: a deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's ruling (`in_place.rs`). The check runs once per driver, release and runtime, per class of pages, on a thread of its own, its verdict kept in the shader cache's directory; a texture made before its class's verdict is a shadow. A texture whose usage renders or writes, a check that failed or made no image, and a pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`). | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each; a driver whose first move changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer |
| A render or compute state's creation hands the driver's making of its predicted pipeline (`pipeline/predicted.rs`, `pipeline/dispatch_making.rs`) to the runtime's pool, kept by the state as a draw's or dispatch's making is, and waits for it `pipeline_creation_wait` at most; a committed command buffer's recordings wait until its commit plus `pipeline_commit_wait` at most, one deadline its commands share, for its draws' and dispatches' (a compute encoder's, a render pass's tile dispatches) pipelines still being made (the scheduler wakes at the bound, `StepWaits::until`), an execution's replayed draws (`render/pending.rs`) among them, whose pipelines the commit's settle hands to the pool (a device replay's, one recording for every command, waits until made under either value), then record each such command as nothing: a draw's barriers and visibility query, a dispatch's barrier (a tile dispatch's copies into its scratch and back), no draw or dispatch, the command buffer running on without error. The making goes on, and the command buffers after it draw and dispatch with the pipeline once made. Metal compiles inside `newRenderPipelineState`, so no draw of a made state waits or is dropped; a host that creates a state inside a command buffer's encoding (the consumer creates a guest's state at an execution's first lookup of it) held that execution through the driver's whole compile: 11.59 s inside one execution on an M2 Pro (MoltenVK 1.4.2, a cold Metal compiler service; a sample of such a stall finds the compile's thread waiting in `MVKMetalCompiler::compile` for Metal's compiler), past the guest's 10 s FIFO check, which ended the guest's task. Each bound is 4.5 s: a creation and a commit may fall in one step of the guest's FIFO (a task's jobs run one after another, and a draw's own variant waits under its command buffer's bound), and no runtime call waits for both, so one step waits 9 s at most for makings, under that 10 s check. A creation waits on no command buffer's deadline and a `commit` on no creation's; a `commit` waits until its own deadline at most (it records there what it can, an execution of render commands the CPU writes among them), every other recording on the scheduler's thread. Made until made under either value, in the call that makes them: a draw that records nothing, one in a pass of custom sample positions and one recorded again into another instance of its pass (each in the draw's call or an execution's replay), a device replay's draws (in its `commit`), and a failed making made again (`PipelineWaitPolicy`'s docs). The runtime's: no pipeline differs. | `pipeline_waits = PipelineWaitPolicy::Bounded`, `pipeline_creation_wait = 4.5 s`, `pipeline_commit_wait = 4.5 s` | `pipeline_waits = PipelineWaitPolicy::Exact`: the creation makes its predicted pipeline before it returns (a render state's first key on its own thread, the rest on the pool, joined; a compute state's on its own thread), an execution's settle makes its replayed draws' pipelines at the commit, and a command buffer waits for each draw's and dispatch's pipeline until it is made | A draw whose pipeline was still being made `pipeline_commit_wait` after its command buffer's commit renders nothing in that command buffer (only there: later ones draw it), where Metal's renders: content drawn once (a layer, a glyph cache) stays without it until redrawn. A creation returns after `pipeline_creation_wait` at most with its making in flight (`WorkCounts::creations_left_making`). `DrawDroppedStillMaking` (`draw-dropped-still-making`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `CommandBuffer::dropped_draw` names the first with `VK_TIMEOUT`; `WorkCounts::draws_dropped_still_making`; `deferred_calls::a_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` and `under_the_exact_wait_a_held_making_holds_its_command_buffer_until_it_lands`. A dispatch whose pipeline was still being made then writes nothing in that command buffer, where Metal's runs: `DispatchDroppedStillMaking` (`dispatch-dropped-still-making`), `WorkCounts::dispatches_dropped_still_making`, the first named by `dropped_draw`; `deferred_calls::a_dispatch_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing`, `a_compute_state_s_creation_waits_its_bound_for_its_predicted_making` and `a_replayed_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` | No GPU cost. The exact form holds the creating thread, and the command buffer, for the whole compile: up to 11.59 s on the M2 Pro's cold boot (that boot's 2,483 render state creations, translation included: 300 over 16 ms, 151 over 100 ms, 14 over 250 ms, 3 over 1 s, the longest 11.59 s, 5.82 s and 1.17 s), where the default holds a creation for 4.5 s at most and a command buffer for 4.5 s from its commit, which drops the draws of the compiles that outlast those (2 of that boot's 2,483 were over 4.5 s) for the command buffers committed before they land; bounds of 1 s Line truncated
| A line Apple's `setLineWidth:` widens (`w' = floor(16 w) / 16`, other than 1), and a triangle's edge in fill mode `Lines`, is drawn by the device's own lines at `w'` wherever it draws that width (`wideLines`, `w'` in `lineWidthRange` and above 0), where Metal draws the parallelogram Vulkan's non-strict wide lines may be (`render/line_width.rs`). They are exactly it on a non-strict device whose wide lines are parallelograms (`strictLines` unset, `nonStrictWideLinesUseParallelogram` set) at a width above 1 on its `lineWidthGranularity`, unannounced there; elsewhere they differ: a strict device's rectangle with square ends (lavapipe, NVIDIA), lines Vulkan does not state as parallelograms (ANV, and every width below 1), a width rounded to the granularity. A mesh draw's lines and edges and a tessellated patch draw's edges take the device's lines under either value, the band not drawing them (at the nearest width they draw where they do not draw `w'`, announced `lines-at-nearest-width`: a known gap below). The runtime's: no pipeline's code differs. | `wide_lines = WideLinePolicy::Device` | `wide_lines = WideLinePolicy::Exact`: a draw of lines or edges the device's lines draw otherwise than Metal is the pipeline's band variant (`VariantKey::line_band`, `pipeline::link::band`) on a device with `tessellationShader` (the device's lines where it has none, or where the translator refuses the state's band or the draw's): two triangles over each line's parallelogram, and each triangle's three edges' parallelograms facing as the triangle, through a tessellation control and evaluation stage; every other width other than 1 is the band under either value | The lines can cover pixels the parallelogram does not, and miss others, at each end and along each edge: up to half the width past each end (square ends), and a rounded width. `DeviceWideLines` (`device-wide-lines`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `WorkCounts::device_wide_line_draws`, `line_band_draws`, `nearest_width_line_draws`; `runtime_lane::line_widths` (the band matches Metal's maps of lines and of triangles' edges, their facing, culling, flat inputs, primitive IDs and depth on MoltenVK under both values, which has no `wideLines`; a band of edges under a depth bias is announced `wide-edge-depth-bias`) | Not measured. Expected from the band's form: a second pipeline variant made for each render state that draws such lines or edges (its two synthesized stages), each line tessellated as a patch of two control points into four corners and each triangle as a patch of three into 21 triangles (12 degenerate), and a strip, loop or fan drawn as the list of its primitives |
| A blit or fill through a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed (`allowGPUOptimizedContents`, 16 texels or more a side, neither `ShaderWrite` nor `PixelFormatView` usage, one sample, not over a buffer) is the device's copy, which keeps the bytes it moves, on every device: Metal's GPU blit into, out of or between such textures moves the texels through its compression, which writes each 16-bit field's low six bits cleared and the alpha code clamped to `[384, 894]`, and its fill clears the low six bits alone (an Apple M3 Max under macOS 27.0.1, every direction, storage mode, usage and size that decides the compression; CPU copies keep the bytes on Metal too). A pass's draws through such an attachment are the device-gap row below. The runtime's choice: no pipeline differs (`compressed_blit.rs`). | `extended_range_blits = ExtendedRangeBlitPolicy::Kept` | `extended_range_blits = ExtendedRangeBlitPolicy::Canonical`: after a blit writes such a texture's region, or a blit out of one writes a buffer's words, a texture over a buffer's or another texture's, a compute dispatch (`bind::extended_canonical_module`, `extended_canonical.rs`) rewrites the texels it wrote in Metal's encoding: in place in a buffer's bytes, an image's through a scratch buffer, a copy out and back around the dispatch; a fill's texel is encoded before it is written. A buffer whose words the device cannot bind (an offset or pitch off 4 bytes, a region past `maxStorageBufferRange`) and a texture over a buffer whose rows share bytes keep the bytes under either value, announced | Bytes no Metal write left (uploaded, CPU-copied or kernel-written texels: a field's low six bits, an alpha code outside `[384, 894]`) keep what Metal's blit would rewrite; a texel reads the same value either way, its low six bits unread and its alpha read clamped. `ExtendedRangeBitsKept` (`extended-range-bits-kept`), once per device; under `Canonical` not for the blits it makes exact; `runtime_lane::compressed_blits` (both values on MoltenVK), the conformance cases `compressed-blits-bgra10xr` and `compressed-blits-bgra10xr-srgb` | Not measured. Expected from the form: per region a blit writes, one dispatch of one invocation a texel (8 bytes read and written), and into an image two copies of the region (8 bytes a texel each way) through a scratch buffer of its size; nothing for a texture Metal keeps uncompressed or of another format |
All at once: `DevicePolicy::exact_answers()` sets every switch above; each row states its own cost.