From 08ca74da22041c7ea50bd7a1e1e08cb06f0869bc Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 06:02:38 -0800 Subject: [PATCH] Charge a sparse heap for a mapping update of a slice past the texture's Plain Metal takes a sparse mapping update whose slice is past the texture's own (its API validation refuses it) and charges its heap's usedSize exactly what the same region on an in-bounds slice costs: one page a tile of the region clipped to the level's tiles, idempotent per tile, given back on an unmap of that tile, never below where it stood (probes/sparse_indirect_usedsize.m and sparse_mapping_past_the_bounds.m on the M3 Max, macOS 27.0.1, both selectors). Ours counted nothing, so sparse-mapping-a-slice-past-the-textures read 65,536 where Metal read 81,920 at used-size/2, /3 and /4. UnitGrid::clipped_region now names such a region's units at the slice (past_slices tells them apart); sparse/bind.rs's apply takes and gives back their heap room into SparseState::charged and binds nothing for them, and undo reverts them with the rest. The move keeps the slice bound (clipped_size), as measured. The texels plain Metal's page reaches (read/4: a 16 by 16 block of slice 0's tile (0, 0) reads its unwritten pattern) are not mirrored, on the owner's call via the orchestrator: an accepted difference in docs/API.md section 10 (Vulkan binds nothing past an image's layers, VUID-VkSparseImageMemoryBindInfo-subresource-01723, and the address is not derivable), which the remaining ledger row now names. Removes the three used-size rows of known-gaps.tsv. tests::sparse holds the counts against Metal's readings row by row (every row now equal). (cherry picked from commit 636522137c717715521cdda950fbb7213e00089f) --- .../metal2vulkan-conformance/known-gaps.tsv | 5 +- .../src/cases/sparse_mappings.rs | 7 +- .../metal2vulkan-runtime/src/sparse/bind.rs | 74 ++++++++++++++++-- .../src/sparse/encoder.rs | 15 ++-- .../src/sparse/mapping.rs | 72 +++++++++++------ .../metal2vulkan-runtime/src/tests/sparse.rs | 78 ++++++++----------- docs/API.md | 9 +++ 7 files changed, 170 insertions(+), 90 deletions(-) diff --git a/crates/metal2vulkan-conformance/known-gaps.tsv b/crates/metal2vulkan-conformance/known-gaps.tsv index 15ca8ce3e..9e2488d54 100644 --- a/crates/metal2vulkan-conformance/known-gaps.tsv +++ b/crates/metal2vulkan-conformance/known-gaps.tsv @@ -471,10 +471,7 @@ resolve-stencil-under-depth-filters llvmpipe refused case/pieces/pass:MTLMultisa resolve-stencil-under-depth-filters llvmpipe refused case/pieces/pass:MTLMultisampleStencilResolveFilterSample0/MTLMultisampleDepthResolveFilterMin Err(Error::NotImplemented("not implemented in the runtime yet: DepthStencilResolve")) Metal resolves a multisampled depth/stencil attachment with the stencil filter `MTLMultisampleStencilResolveFilterSample0` under the depth filter `Min` or `Max`, and we refuse it `NotImplemented(DepthStencilResolve)`. Ours is not a device refusal dressed up: crates/metal2vulkan-runtime/src/resolve.rs states in its own words that a filter the device's resolve modes lack -- `supportedDepthResolveModes`, `supportedStencilResolveModes`, or the other aspect's modes where a subpass resolving one aspect must name the same mode for both, read off the compile device's description as `VkProperty::{DepthResolveMode, StencilResolveMode, IndependentResolveNone, IndependentResolve}` -- is 'not built', and names the exact path in the same sentence: a resolve DRAW, which the module already uses for other unresolvable pairs and which needs no resolve mode from the device at all. So the gap is work not done rather than a capability missing, which is what makes it ours under the owner's rule that what Metal allows we must allow. This venue is a device with no independent resolve of the two aspects, so the `Sample0` stencil filter cannot be named beside a `Min` or `Max` depth one; the case's other filter pairs run here, so it is these two cells. The fix belongs in resolve.rs: reach the resolve draw for a filter pair the device's modes cannot state, as the module does where `DepthResolvedSample` follows `Min` or `Max` on a sampled attachment. Open: runtime work, on the orchestrator's todo list. tile-simd-blur-columns llvmpipe divergent case/state-facts/max_total_threads_per_threadgroup Metal 1024 (0x400), ours 960 (0x3c0) Metal's tile render pipeline state answers `maxTotalThreadsPerThreadgroup` 1024 and ours answers 960 on this venue. The 960 is this device's own compiled limit and the runtime reports it deliberately: crates/metal2vulkan-runtime/src/pipeline/tile.rs documents the answer as 'Metal's 1024, or the descriptor's limit, where the device runs a threadgroup of 1024 threads, else the device's lower limit', and lavapipe's emulated 32-lane simdgroups take 960 threads of this pipeline. So the number is honest about the device and a dispatch past it is refused typed -- which this family's own test `a_dispatch_the_device_cannot_take_is_the_devices_gap` rules is the DEVICE's gap and verdicts `LacksFeature`. The open work is that the same ruling has not reached the FACT: the state's reported limit is compared against Metal's number as if it were an answer of ours, so a venue whose threadgroup is smaller reads as a divergence at the getter while the matching dispatch reads as the venue's honest gap. That inconsistency is the suite's, which is ours, and the fix is in crates/metal2vulkan-conformance: let a state fact that reports a device limit follow the device-gap ruling its dispatch already gets, or state Metal's number beside the device's so the comparison asks the right question. Until it does the row records it, and the row must not be read as a claim that the runtime should report 1024 on a device that cannot run it: that would be a lie a consumer sizes a dispatch from. Open: suite work, on the orchestrator's todo list. tile-simd-blur-rows llvmpipe divergent case/state-facts/max_total_threads_per_threadgroup Metal 1024 (0x400), ours 960 (0x3c0) Metal's tile render pipeline state answers `maxTotalThreadsPerThreadgroup` 1024 and ours answers 960 on this venue. The 960 is this device's own compiled limit and the runtime reports it deliberately: crates/metal2vulkan-runtime/src/pipeline/tile.rs documents the answer as 'Metal's 1024, or the descriptor's limit, where the device runs a threadgroup of 1024 threads, else the device's lower limit', and lavapipe's emulated 32-lane simdgroups take 960 threads of this pipeline. So the number is honest about the device and a dispatch past it is refused typed -- which this family's own test `a_dispatch_the_device_cannot_take_is_the_devices_gap` rules is the DEVICE's gap and verdicts `LacksFeature`. The open work is that the same ruling has not reached the FACT: the state's reported limit is compared against Metal's number as if it were an answer of ours, so a venue whose threadgroup is smaller reads as a divergence at the getter while the matching dispatch reads as the venue's honest gap. That inconsistency is the suite's, which is ours, and the fix is in crates/metal2vulkan-conformance: let a state fact that reports a device limit follow the device-gap ruling its dispatch already gets, or state Metal's number beside the device's so the comparison asks the right question. Until it does the row records it, and the row must not be read as a claim that the runtime should report 1024 on a device that cannot run it: that would be a lie a consumer sizes a dispatch from. Open: suite work, on the orchestrator's todo list. -sparse-mapping-a-slice-past-the-textures * divergent case/program/used-size/2 Metal 81920 (0x14000), ours 65536 (0x10000) Plain Metal TAKES a sparse mapping update whose slice is past the texture's own slices, and it reaches real memory; the runtime maps nothing and counts nothing for it (crates/metal2vulkan-runtime/src/sparse/mapping.rs, `UnitGrid::clipped_size`, which answers None for a slice past the texture's). Measured on this M3 Max (macOS 27.0.1, build 26A434) from this case's own committed recording, 3 runs and one outcome, over a two-slice 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles with two tiles of each slice mapped and filled with four distinct bytes: a Map of one tile of slice 2 raises the heap's usedSize by exactly one page (65,536 to 81,920), an Unmap of another tile of slice 2 does NOT give that page back (81,920 after it and after the reads), and the texels say the page reached a real tile -- a 16 by 16 texel block at texel (0, 16) of slice 0's tile (0, 0), 256 of its 4,096 words, reads 0xFFFFFFFF, which probes/sparse_unmapped_blit.m measured on this chip to be Metal's unwritten pattern, where every other word of that tile and all 4,096 words of the other three tiles still hold their own fill. So Metal binds a page at an address its own out-of-bounds slice produced and part of it lands inside an in-bounds mapped tile, which its own API validation layer refuses the call to prevent. Ours maps nothing, counts nothing and loses no texel, which is why all four sites differ. The exact form is NOT derivable from what is measured: the address the page landed at is Apple's internal page layout for this chip and nothing here says what rule produced it, and which of the two out-of-bounds steps did it is unmeasured because the case reads once after both. The next step is a probe that separates the Map from the Unmap and reads every tile of both slices, which would say whether one page lands in several tiles at once; mirroring an Apple page-binding accident in a published crate is the owner's call either way. Open: on the orchestrator's todo list as runtime work. -sparse-mapping-a-slice-past-the-textures * divergent case/program/used-size/3 Metal 81920 (0x14000), ours 65536 (0x10000) Plain Metal TAKES a sparse mapping update whose slice is past the texture's own slices, and it reaches real memory; the runtime maps nothing and counts nothing for it (crates/metal2vulkan-runtime/src/sparse/mapping.rs, `UnitGrid::clipped_size`, which answers None for a slice past the texture's). Measured on this M3 Max (macOS 27.0.1, build 26A434) from this case's own committed recording, 3 runs and one outcome, over a two-slice 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles with two tiles of each slice mapped and filled with four distinct bytes: a Map of one tile of slice 2 raises the heap's usedSize by exactly one page (65,536 to 81,920), an Unmap of another tile of slice 2 does NOT give that page back (81,920 after it and after the reads), and the texels say the page reached a real tile -- a 16 by 16 texel block at texel (0, 16) of slice 0's tile (0, 0), 256 of its 4,096 words, reads 0xFFFFFFFF, which probes/sparse_unmapped_blit.m measured on this chip to be Metal's unwritten pattern, where every other word of that tile and all 4,096 words of the other three tiles still hold their own fill. So Metal binds a page at an address its own out-of-bounds slice produced and part of it lands inside an in-bounds mapped tile, which its own API validation layer refuses the call to prevent. Ours maps nothing, counts nothing and loses no texel, which is why all four sites differ. The exact form is NOT derivable from what is measured: the address the page landed at is Apple's internal page layout for this chip and nothing here says what rule produced it, and which of the two out-of-bounds steps did it is unmeasured because the case reads once after both. The next step is a probe that separates the Map from the Unmap and reads every tile of both slices, which would say whether one page lands in several tiles at once; mirroring an Apple page-binding accident in a published crate is the owner's call either way. Open: on the orchestrator's todo list as runtime work. -sparse-mapping-a-slice-past-the-textures * divergent case/program/used-size/4 Metal 81920 (0x14000), ours 65536 (0x10000) Plain Metal TAKES a sparse mapping update whose slice is past the texture's own slices, and it reaches real memory; the runtime maps nothing and counts nothing for it (crates/metal2vulkan-runtime/src/sparse/mapping.rs, `UnitGrid::clipped_size`, which answers None for a slice past the texture's). Measured on this M3 Max (macOS 27.0.1, build 26A434) from this case's own committed recording, 3 runs and one outcome, over a two-slice 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles with two tiles of each slice mapped and filled with four distinct bytes: a Map of one tile of slice 2 raises the heap's usedSize by exactly one page (65,536 to 81,920), an Unmap of another tile of slice 2 does NOT give that page back (81,920 after it and after the reads), and the texels say the page reached a real tile -- a 16 by 16 texel block at texel (0, 16) of slice 0's tile (0, 0), 256 of its 4,096 words, reads 0xFFFFFFFF, which probes/sparse_unmapped_blit.m measured on this chip to be Metal's unwritten pattern, where every other word of that tile and all 4,096 words of the other three tiles still hold their own fill. So Metal binds a page at an address its own out-of-bounds slice produced and part of it lands inside an in-bounds mapped tile, which its own API validation layer refuses the call to prevent. Ours maps nothing, counts nothing and loses no texel, which is why all four sites differ. The exact form is NOT derivable from what is measured: the address the page landed at is Apple's internal page layout for this chip and nothing here says what rule produced it, and which of the two out-of-bounds steps did it is unmeasured because the case reads once after both. The next step is a probe that separates the Map from the Unmap and reads every tile of both slices, which would say whether one page lands in several tiles at once; mirroring an Apple page-binding accident in a published crate is the owner's call either way. Open: on the orchestrator's todo list as runtime work. -sparse-mapping-a-slice-past-the-textures * divergent case/read/4 256 elements differ (U32), the largest difference 1010580540 Plain Metal TAKES a sparse mapping update whose slice is past the texture's own slices, and it reaches real memory; the runtime maps nothing and counts nothing for it (crates/metal2vulkan-runtime/src/sparse/mapping.rs, `UnitGrid::clipped_size`, which answers None for a slice past the texture's). Measured on this M3 Max (macOS 27.0.1, build 26A434) from this case's own committed recording, 3 runs and one outcome, over a two-slice 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles with two tiles of each slice mapped and filled with four distinct bytes: a Map of one tile of slice 2 raises the heap's usedSize by exactly one page (65,536 to 81,920), an Unmap of another tile of slice 2 does NOT give that page back (81,920 after it and after the reads), and the texels say the page reached a real tile -- a 16 by 16 texel block at texel (0, 16) of slice 0's tile (0, 0), 256 of its 4,096 words, reads 0xFFFFFFFF, which probes/sparse_unmapped_blit.m measured on this chip to be Metal's unwritten pattern, where every other word of that tile and all 4,096 words of the other three tiles still hold their own fill. So Metal binds a page at an address its own out-of-bounds slice produced and part of it lands inside an in-bounds mapped tile, which its own API validation layer refuses the call to prevent. Ours maps nothing, counts nothing and loses no texel, which is why all four sites differ. The exact form is NOT derivable from what is measured: the address the page landed at is Apple's internal page layout for this chip and nothing here says what rule produced it, and which of the two out-of-bounds steps did it is unmeasured because the case reads once after both. The next step is a probe that separates the Map from the Unmap and reads every tile of both slices, which would say whether one page lands in several tiles at once; mirroring an Apple page-binding accident in a published crate is the owner's call either way. Open: on the orchestrator's todo list as runtime work. +sparse-mapping-a-slice-past-the-textures * divergent case/read/4 256 elements differ (U32), the largest difference 1010580540 Plain Metal TAKES a sparse mapping update whose slice is past the texture's own slices (its own API validation layer refuses the call) and binds the page it charges at an address its own page layout derives. Measured on this M3 Max (macOS 27.0.1, build 26A434) from this case's own committed recording, 3 runs and one outcome, over a two-slice 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles with two tiles of each slice mapped and filled with four distinct bytes: after a Map of one tile of slice 2 and an Unmap of another, a 16 by 16 texel block at texel (0, 16) of slice 0's tile (0, 0), 256 of its 4,096 words, reads 0xFFFFFFFF (Metal's unwritten pattern on this chip, probes/sparse_unmapped_blit.m), every other word of the four tiles its own fill. The runtime charges its heap's usedSize the same page (this case's used-size sites compare) and maps nothing there, so no texel moves, which is the whole of this site's difference. It is an accepted difference, not mirrored: docs/API.md section 10, Heaps and memory, 'A sparse mapping update of a slice past the texture's own maps nothing'. Vulkan binds nothing past an image's layers (VUID-VkSparseImageMemoryBindInfo-subresource-01723), and the address Metal's page lands at is not derivable from what is measured. Scoped to every venue: the runtime maps nothing for the slice before any device is consulted. Open: nothing in the product. sparse-mapping-move-inside-the-level * divergent case/read/4 3968 elements differ (U32), the largest difference 1077952576 Plain Metal reads back only a FRACTION of a sparse tile a move rebound, and we read the whole of it. Measured on this M3 Max (macOS 27.0.1, build 26A434) from these cases' own committed recordings, 3 runs and one outcome each, over a 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles: a destination tile the move landed a source tile on reads ZERO except for 128 of its 4,096 words, which hold the source tile's own marker and sit in 4-by-2 texel groups at a 16-by-16 stride -- sixteen groups of 32 bytes, 512 bytes of the 16-KiB page. Ours reads the source tile's marker in all 4,096 words, which is why 3,968 of them differ at each site. WHAT IS NOT THE GAP: the move's own rule. The destination run, the source clipping and the no-wrap behaviour all match exactly -- sparse-mapping-move-of-a-source-past-the-level compares every texel of six tiles and is compliant, and in these cases the source's marker appears at exactly the destination tile Metal's run names and at no other, so what differs is how much of the moved tile a later blit can read and not where the tile went. It is NOT an out-of-bounds artefact: sparse-mapping-move-inside-the-level has both sides wholly inside the level and its validated leg reads `ran`, and all four of its destination tiles read this way. It is not a property of the tile's position either: B(1,1) reads whole in sparse-mapping-move-of-a-clipped-source and partial in sparse-mapping-move-inside-the-level. Which tiles read partially is fixed for a given program, which points at Apple's own page layout for that program -- the same class of thing as sparse-mapping-a-slice-past-the-textures. The 4-by-2-at-16-by-16 shape is the shape of a lossless-compression block's head, so the likely mechanism is that Metal's moved page carries compressed payload whose metadata the destination texture does not have, and a blit resolves only each block's uncompressed head; the runtime's emulated sparse path moves real memory, so the whole tile reads back (crates/metal2vulkan-runtime/src/sparse/, where a fix would belong). The exact form is NOT derivable from what is measured: nothing here says what rule picks the 128 words, and reproducing an Apple compression-metadata mismatch in a published crate is the owner's call. The next step is a probe that reads a moved tile under several formats and page sizes and says whether the surviving words are a compression block's head. Open: on the orchestrator's todo list as runtime work. sparse-mapping-move-inside-the-level * divergent case/read/5 3968 elements differ (U32), the largest difference 1094795585 Plain Metal reads back only a FRACTION of a sparse tile a move rebound, and we read the whole of it. Measured on this M3 Max (macOS 27.0.1, build 26A434) from these cases' own committed recordings, 3 runs and one outcome each, over a 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles: a destination tile the move landed a source tile on reads ZERO except for 128 of its 4,096 words, which hold the source tile's own marker and sit in 4-by-2 texel groups at a 16-by-16 stride -- sixteen groups of 32 bytes, 512 bytes of the 16-KiB page. Ours reads the source tile's marker in all 4,096 words, which is why 3,968 of them differ at each site. WHAT IS NOT THE GAP: the move's own rule. The destination run, the source clipping and the no-wrap behaviour all match exactly -- sparse-mapping-move-of-a-source-past-the-level compares every texel of six tiles and is compliant, and in these cases the source's marker appears at exactly the destination tile Metal's run names and at no other, so what differs is how much of the moved tile a later blit can read and not where the tile went. It is NOT an out-of-bounds artefact: sparse-mapping-move-inside-the-level has both sides wholly inside the level and its validated leg reads `ran`, and all four of its destination tiles read this way. It is not a property of the tile's position either: B(1,1) reads whole in sparse-mapping-move-of-a-clipped-source and partial in sparse-mapping-move-inside-the-level. Which tiles read partially is fixed for a given program, which points at Apple's own page layout for that program -- the same class of thing as sparse-mapping-a-slice-past-the-textures. The 4-by-2-at-16-by-16 shape is the shape of a lossless-compression block's head, so the likely mechanism is that Metal's moved page carries compressed payload whose metadata the destination texture does not have, and a blit resolves only each block's uncompressed head; the runtime's emulated sparse path moves real memory, so the whole tile reads back (crates/metal2vulkan-runtime/src/sparse/, where a fix would belong). The exact form is NOT derivable from what is measured: nothing here says what rule picks the 128 words, and reproducing an Apple compression-metadata mismatch in a published crate is the owner's call. The next step is a probe that reads a moved tile under several formats and page sizes and says whether the surviving words are a compression block's head. Open: on the orchestrator's todo list as runtime work. sparse-mapping-move-inside-the-level * divergent case/read/6 3968 elements differ (U32), the largest difference 1145324612 Plain Metal reads back only a FRACTION of a sparse tile a move rebound, and we read the whole of it. Measured on this M3 Max (macOS 27.0.1, build 26A434) from these cases' own committed recordings, 3 runs and one outcome each, over a 256x256 nine-level R32Float sparse texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles: a destination tile the move landed a source tile on reads ZERO except for 128 of its 4,096 words, which hold the source tile's own marker and sit in 4-by-2 texel groups at a 16-by-16 stride -- sixteen groups of 32 bytes, 512 bytes of the 16-KiB page. Ours reads the source tile's marker in all 4,096 words, which is why 3,968 of them differ at each site. WHAT IS NOT THE GAP: the move's own rule. The destination run, the source clipping and the no-wrap behaviour all match exactly -- sparse-mapping-move-of-a-source-past-the-level compares every texel of six tiles and is compliant, and in these cases the source's marker appears at exactly the destination tile Metal's run names and at no other, so what differs is how much of the moved tile a later blit can read and not where the tile went. It is NOT an out-of-bounds artefact: sparse-mapping-move-inside-the-level has both sides wholly inside the level and its validated leg reads `ran`, and all four of its destination tiles read this way. It is not a property of the tile's position either: B(1,1) reads whole in sparse-mapping-move-of-a-clipped-source and partial in sparse-mapping-move-inside-the-level. Which tiles read partially is fixed for a given program, which points at Apple's own page layout for that program -- the same class of thing as sparse-mapping-a-slice-past-the-textures. The 4-by-2-at-16-by-16 shape is the shape of a lossless-compression block's head, so the likely mechanism is that Metal's moved page carries compressed payload whose metadata the destination texture does not have, and a blit resolves only each block's uncompressed head; the runtime's emulated sparse path moves real memory, so the whole tile reads back (crates/metal2vulkan-runtime/src/sparse/, where a fix would belong). The exact form is NOT derivable from what is measured: nothing here says what rule picks the 128 words, and reproducing an Apple compression-metadata mismatch in a published crate is the owner's call. The next step is a probe that reads a moved tile under several formats and page sizes and says whether the surviving words are a compression block's head. Open: on the orchestrator's todo list as runtime work. diff --git a/crates/metal2vulkan-conformance/src/cases/sparse_mappings.rs b/crates/metal2vulkan-conformance/src/cases/sparse_mappings.rs index 0010e5421..56139f26a 100644 --- a/crates/metal2vulkan-conformance/src/cases/sparse_mappings.rs +++ b/crates/metal2vulkan-conformance/src/cases/sparse_mappings.rs @@ -40,7 +40,7 @@ //! - **the level** moves it: level 0 of this texture is 16 tiles, level 1 is 4, level 2 is 1, and //! the tail is one page however small a region names it; //! - **the slice** moves it: a second slice's tiles are tiles of their own, and a slice **past** -//! the texture's own moves it where plain Metal takes a page for one and we take none +//! the texture's own moves it, plain Metal's and ours alike, by a page for one //! ([`a_slice_past_the_textures`], which also reads the texels four mapped tiles hold either //! side of such an update, because `usedSize` cannot say which tiles one reached); //! - **the move** does not move it, which is the point of its row: the runtime's own @@ -1154,8 +1154,9 @@ pub fn slices_of_an_array() -> SparseMappings { } } -/// The case of a slice past the texture's own, which our side maps nothing for and plain Metal -/// takes a page for, with the texels four mapped tiles hold either side of it. +/// The case of a slice past the texture's own, which plain Metal and our side both take a page +/// for, with the texels four mapped tiles hold either side of it (plain Metal's page lands in one +/// of them, ours nowhere: an accepted difference, `docs/API.md`). pub fn a_slice_past_the_textures() -> SparseMappings { SparseMappings { row: &A_SLICE_PAST_THE_TEXTURES, diff --git a/crates/metal2vulkan-runtime/src/sparse/bind.rs b/crates/metal2vulkan-runtime/src/sparse/bind.rs index c464e573d..eaaa92c42 100644 --- a/crates/metal2vulkan-runtime/src/sparse/bind.rs +++ b/crates/metal2vulkan-runtime/src/sparse/bind.rs @@ -215,12 +215,16 @@ pub(crate) fn bind_batch( }); } let Images { textures, images } = known; - let (changed, moved) = apply(&ops, &images); + let Applied { + changed, + moved, + charged, + } = apply(&ops, &images); let kept = kept_units(&images, &moved); let mut changes = match plan(device, &images, &changed, &kept) { Ok(changes) => changes, Err(failure) => { - undo(&images, &changed); + undo(&images, &changed, &charged); return Err(failure); } }; @@ -345,7 +349,7 @@ pub(crate) fn bind_batch( exit_guard::called(Call::QueueBindSparse); if let Err(error) = bound { free_fresh(device, &changes); - undo(&images, &changed); + undo(&images, &changed, &charged); return Err(BindFailure::Vulkan(error)); } let mut unbound = Vec::new(); @@ -382,14 +386,24 @@ fn free_fresh(device: &Device, changes: &[UnitChange]) { } } +/// What [`apply`] changed: the units mapped and unmapped, what moved in order, and the units of +/// slices past their textures' own their heaps took or gave back. +struct Applied { + changed: Vec, + moved: Vec, + charged: Vec, +} + /// Apply each update to its textures' Metal state in order: a map takes its heap's room (a heap /// that fills leaves the rest of that update unmapped), an unmap gives it back, and a move takes /// each source unit's mapping to its destination unit where that one is unmapped as it moves, /// one unit at a time in the move's order, leaving the heaps' counts as they are (as Metal's). -/// What changed, and what moved in order. -fn apply(ops: &[Op<'_>], images: &[&SparseImage]) -> (Vec, Vec) { +/// A unit of a slice past its texture's own takes and gives back its heap's room alike, and +/// nothing holds it (`UnitGrid::clipped_region`). +fn apply(ops: &[Op<'_>], images: &[&SparseImage]) -> Applied { let mut changed = Vec::new(); let mut moved = Vec::new(); + let mut charged = Vec::new(); for op in ops { match *op { Op::Units { image, update } => { @@ -402,6 +416,30 @@ fn apply(ops: &[Op<'_>], images: &[&SparseImage]) -> (Vec, Vec) }; let mut state = lock(&sparse.state); for &unit in &update.units { + if sparse.grid.past_slices(unit) { + let map = update.mode == TileMapping::Map; + if map { + if state.charged.contains(&unit) { + continue; + } + if !heap.take(sparse.heap_tiles(unit)) { + break; + } + state.charged.insert(unit); + } else { + if !state.charged.remove(&unit) { + continue; + } + heap.give(sparse.heap_tiles(unit)); + } + charged.push(Changed { + image, + unit, + mapped: map, + counted: true, + }); + continue; + } match update.mode { TileMapping::Map => { if state.mapped.contains(&unit) { @@ -458,7 +496,11 @@ fn apply(ops: &[Op<'_>], images: &[&SparseImage]) -> (Vec, Vec) } } } - (changed, moved) + Applied { + changed, + moved, + charged, + } } /// The device units of `image`, the batch's image `index`, that `changed` touched. @@ -493,8 +535,24 @@ fn kept_units(images: &[&SparseImage], moved: &[Moved]) -> BTreeSet<(usize, VkUn kept } -/// Undo `changed`, last first: the Metal state and the heaps' counts as they were. -fn undo(images: &[&SparseImage], changed: &[Changed]) { +/// Undo `changed` and `charged`, last first: the Metal state and the heaps' counts as they were. +fn undo(images: &[&SparseImage], changed: &[Changed], charged: &[Changed]) { + for change in charged.iter().rev() { + let image = images[change.image]; + let mut state = lock(&image.state); + let held = image.heap.upgrade(); + let Some(heap) = held.as_ref().and_then(Heap::sparse) else { + continue; + }; + if change.mapped { + state.charged.remove(&change.unit); + heap.give(image.heap_tiles(change.unit)); + } else { + state.charged.insert(change.unit); + // The room was the image's a moment ago: taking it back cannot fail. + heap.take(image.heap_tiles(change.unit)); + } + } for change in changed.iter().rev() { let image = images[change.image]; let mut state = lock(&image.state); diff --git a/crates/metal2vulkan-runtime/src/sparse/encoder.rs b/crates/metal2vulkan-runtime/src/sparse/encoder.rs index 3b668e296..3172e0e87 100644 --- a/crates/metal2vulkan-runtime/src/sparse/encoder.rs +++ b/crates/metal2vulkan-runtime/src/sparse/encoder.rs @@ -134,7 +134,8 @@ impl ResourceStateCommandEncoder { /// arguments its own validation layer stops (`UnitGrid::clipped_region`, where the /// measurement is): level 9 of a nine-level texture and an origin past the level's tiles map /// nothing, and a region running past them maps the level's own tiles. A slice past the - /// texture's maps none, where plain Metal's `usedSize` took one page for it. + /// texture's maps none, and its heap's `usedSize` counts the region's tiles there as plain + /// Metal's does, one page each, given back on an unmap of each. /// /// Refused, recording nothing: a texture of another device (`Invalid`); a view of a pixel /// format whose tile is not its texture's (`NotImplemented(SparseHeaps)`: not measured). @@ -199,12 +200,12 @@ impl ResourceStateCommandEncoder { /// of no size on an axis, or of a level or slice past the texture's, maps nothing; and the /// regions the count names past the buffer map nothing. /// - /// Differs, in the heap's count alone: plain Metal **bounds the level and the origin and does - /// not bound the slice**, charging a region of a slice past the texture's exactly what the - /// same region on an in-bounds slice costs — the region clipped to the level's tiles, one - /// page each — where the runtime maps and counts none, so its `usedSize` is lower by those - /// tiles. Metal's charge is an ordinary one in every other way: idempotent per region, given - /// back on an unmap of it, and never taking the count below where it stood + /// Plain Metal **bounds the level and the origin and does not bound the slice**, charging a + /// region of a slice past the texture's exactly what the same region on an in-bounds slice + /// costs — the region clipped to the level's tiles, one page each — and so does the runtime's + /// heap, mapping none of them. Metal's charge is an ordinary one in every other way: + /// idempotent per tile, given back on an unmap of it, and never taking the count below where + /// it stood /// (`metal2vulkan-conformance/probes/sparse_indirect_usedsize.m`, the M3 Max under macOS /// 27.0.1, plain Metal, one shape per process, each reading twice, with the in-bounds region /// through the same selector as its control). A level past the texture's levels and an origin diff --git a/crates/metal2vulkan-runtime/src/sparse/mapping.rs b/crates/metal2vulkan-runtime/src/sparse/mapping.rs index e4e7da7ed..3da7e5a47 100644 --- a/crates/metal2vulkan-runtime/src/sparse/mapping.rs +++ b/crates/metal2vulkan-runtime/src/sparse/mapping.rs @@ -111,12 +111,16 @@ impl TexelBox { } } -/// What a texture has mapped and bound: Metal's mapped units, and the memory of each bound -/// device unit. +/// What a texture has mapped and bound: Metal's mapped units, the memory of each bound device +/// unit, and the units of slices past its own that its heap counts +/// ([`UnitGrid::clipped_region`]). #[derive(Default)] pub(crate) struct SparseState { pub(crate) mapped: HashSet, pub(crate) bound: HashMap, + /// Units of a slice past the texture's own that a map took: its heap counts each, as Metal's + /// `usedSize` does, and nothing holds texels of them. + pub(crate) charged: HashSet, } /// The units of a sparse texture, as data: Metal's (its tile, and a slice's tail from @@ -461,13 +465,16 @@ impl UnitGrid { } /// Metal's units an update's `region` (in tiles) of `level` and `slice` touches, as plain Metal - /// maps arguments its validation stops (the M3 Max under macOS 27.0.1): none at a level or - /// slice past the texture's, nor for a tiled level's region whose origin is past its tiles or - /// whose size is 0 on an axis; else the region's tiles inside the level, the rest of it - /// dropped. A level past `firstMipmapInTail` touches its slice's tail. + /// maps arguments its validation stops (the M3 Max under macOS 27.0.1): none at a level past + /// the texture's, nor for a tiled level's region whose origin is past its tiles or whose size + /// is 0 on an axis; else the region's tiles inside the level, the rest of it dropped. A level + /// past `firstMipmapInTail` touches its slice's tail. A slice past the texture's own names the + /// units the same region names on an in-bounds slice, at that slice + /// ([`past_slices`](Self::past_slices)): units Metal's heap counts and nothing holds. /// /// One rule for all three mapping selectors — the direct update, the plural one and the - /// indirect one — and for the move. Plain Metal **takes** each of these arguments where its own + /// indirect one — and, with the slice bounded ([`clipped_size`](Self::clipped_size)), for the + /// move. Plain Metal **takes** each of these arguments where its own /// API validation layer stops them, so a typed refusal of ours would be a refusal where Metal /// allows. Measured through the direct /// `updateTextureMapping:mode:region:mipLevel:slice:` on this M3 Max, macOS 27.0.1 @@ -479,44 +486,63 @@ impl UnitGrid { /// is the control that says the measurement works at all. The three move shapes complete with /// no error too, leaving `usedSize` where it was. /// - /// Differs, in the heap's count alone: Metal **does not bound the slice**, where it bounds the - /// level and the origin. A region of a slice past the texture's costs Metal exactly what the - /// same region on an in-bounds slice costs — the region clipped to this level's tiles, one - /// page each — and that charge is then an ordinary one: idempotent per region, given back on - /// an unmap of it, and never taking the count below where it stood. The runtime maps and - /// counts none, so its `usedSize` is lower by those tiles. Measured through **both** mapping - /// selectors on this M3 Max (the direct one above, and the indirect one over nineteen - /// configurations in `metal2vulkan-conformance/probes/sparse_indirect_usedsize.m`), which + /// Metal **does not bound the slice**, where it bounds the level and the origin. A region of + /// a slice past the texture's costs Metal's heap exactly what the same region on an in-bounds + /// slice costs — the region clipped to this level's tiles, one page each — and that charge + /// is then an ordinary one: idempotent per tile, given back on an unmap of it, and never + /// taking the count below where it stood. So the runtime counts those units in its heap and + /// maps them nowhere (`SparseState::charged`). Measured through **both** mapping selectors on + /// this M3 Max (the direct one above, and the indirect one over nineteen configurations in + /// `metal2vulkan-conformance/probes/sparse_indirect_usedsize.m`), over level 0's tiles, which /// read alike: one page for one such tile, sixteen for a region of 8 by 8 on a level holding /// 4 by 4, one per out-of-bounds slice named, and nothing at all for a level or an origin - /// past the bounds. `tests::sparse` holds the readings row by row. + /// past the bounds; another level's region, a tail among them, takes the same rule + /// unmeasured. `tests::sparse` holds the readings row by row. /// - /// The count is not the whole of that difference, and cannot be: it cannot say which tiles an - /// update reached. The conformance suite's `sparse-mapping-a-slice-past-the-textures` reads - /// the texels four mapped tiles hold either side of such an update as well as the count. + /// Plain Metal's page for such a tile also lands at an address its own page layout derives, + /// in a block of another slice's mapped tile (`sparse-mapping-a-slice-past-the-textures` + /// reads it): not mirrored, an accepted difference (`docs/API.md`), since Vulkan binds + /// nothing past an image's layers (`VUID-VkSparseImageMemoryBindInfo-subresource-01723`) and + /// the address is not derivable from what is measured. pub(crate) fn clipped_region(&self, level: u64, slice: u64, region: &Region) -> Vec { - let Some(clipped) = self.clipped_size(level, slice, region) else { + let Some(clipped) = self.clipped_level(level, region) else { return Vec::new(); }; self.update_units( level as u32, - slice as u32, + u32::try_from(slice).unwrap_or(u32::MAX), axes_of(region.origin), clipped.map(|axis| axis as u32), ) } + /// Whether `unit` is of a slice past the texture's own: one Metal's heap counts and nothing + /// holds ([`clipped_region`](Self::clipped_region)). + pub(crate) fn past_slices(&self, unit: MetalUnit) -> bool { + let (MetalUnit::Tile { slice, .. } | MetalUnit::Tail { slice }) = unit; + slice >= self.slices() + } + /// The tiles of `region` of `level` and `slice` that lie inside this grid, on each axis, or /// `None` where the region names no unit of it at all. /// /// The one place [`clipped_region`](Self::clipped_region)'s rule is written down, so the move - /// below reads the same bounds the three mapping selectors do. A level at + /// below reads the same bounds the three mapping selectors do, the slice's too (they read + /// [`clipped_level`](Self::clipped_level) on a slice past the texture's). A level at /// `firstMipmapInTail` answers one unit however large the region is — the slice's whole tail — /// which is what `[1, 1, 1]` stands for here; a level past the tail, a level or slice past the /// texture's own, an origin past the level's tiles and a size of 0 on an axis each answer /// `None`. fn clipped_size(&self, level: u64, slice: u64, region: &Region) -> Option<[u64; 3]> { - if level >= self.shape.levels || slice >= u64::from(self.slices()) { + if slice >= u64::from(self.slices()) { + return None; + } + self.clipped_level(level, region) + } + + /// [`clipped_size`](Self::clipped_size) on any slice. + fn clipped_level(&self, level: u64, region: &Region) -> Option<[u64; 3]> { + if level >= self.shape.levels { return None; } let level32 = level as u32; diff --git a/crates/metal2vulkan-runtime/src/tests/sparse.rs b/crates/metal2vulkan-runtime/src/tests/sparse.rs index 332b803ca..14c551083 100644 --- a/crates/metal2vulkan-runtime/src/tests/sparse.rs +++ b/crates/metal2vulkan-runtime/src/tests/sparse.rs @@ -666,9 +666,9 @@ fn texels(level: u32, layer: u32, origin: [u32; 2], size: [u32; 2]) -> TexelBox /// Max under macOS 27.0.1, through the direct /// `updateTextureMapping:mode:region:mipLevel:slice:` over this very shape — a 256 by 256 /// nine-level `R32Float` texture whose level 0 holds 4 by 4 of Metal's 16-KiB tiles — the heap's -/// `usedSize` 0 before each shape and the command buffer `Completed` with no error after. The one -/// reading that is not this rule's is a **slice** past the texture's, which took one page there and -/// maps none here. +/// `usedSize` 0 before each shape and the command buffer `Completed` with no error after. A +/// **slice** past the texture's took one page there: it names its tile at that slice, which the +/// heap counts and nothing holds. #[test] fn a_mapping_update_past_the_bounds_clips_as_plain_metal_does() { let grid = grid([256, 256, 1], 9, 1, 3, false); @@ -685,10 +685,14 @@ fn a_mapping_update_past_the_bounds_clips_as_plain_metal_does() { grid.clipped_region(0, 0, &Region::new_2d(0, 0, 8, 8)), whole ); - // A level past the texture's levels, a slice past its slices, and an origin past the level's - // last tile each map nothing, where Metal's `usedSize` stayed at 0. + // A level past the texture's levels and an origin past the level's last tile each map + // nothing, where Metal's `usedSize` stayed at 0; a slice past its slices names its tile there, + // past the texture's slices, where Metal took one page. assert!(grid.clipped_region(9, 0, &one).is_empty(), "level 9 of 9"); - assert!(grid.clipped_region(0, 1, &one).is_empty(), "slice 1 of 1"); + let past = grid.clipped_region(0, 1, &one); + assert_eq!(past, vec![tile(0, 1, [0, 0])], "slice 1 of 1"); + assert!(grid.past_slices(past[0])); + assert!(!grid.past_slices(tile(0, 0, [0, 0]))); assert!( grid.clipped_region(0, 0, &Region::new_2d(4, 4, 1, 1)) .is_empty(), @@ -1014,10 +1018,9 @@ fn texel_boxes_intersect_and_split() { /// Metal's rule is the plain one: it bounds the level and the origin and **does not bound the /// slice**, charging a region of a slice past the texture's exactly what the same region on an /// in-bounds slice costs — the region clipped to the level's tiles — and that charge then behaves -/// like any mapping, idempotent and given back on an unmap. The runtime instead maps and counts -/// nothing there, so its count is **lower by those tiles**, and that is the difference this test -/// pins: `metal` below is what Metal read, `ours` what the runtime answers, and a row where they -/// part names the gap rather than hiding it. +/// like any mapping, idempotent and given back on an unmap. The runtime's heap counts the same +/// tiles, which it maps nowhere (`UnitGrid::past_slices`): `metal` below is what Metal read, and +/// the runtime counts the units the list names. /// /// Each row is a probe shape. The in-bounds rows are the controls: their counts **must** move, or /// no row here is a measurement of anything. @@ -1039,67 +1042,50 @@ fn a_slice_past_the_textures_is_the_one_axis_metal_does_not_bound() { .count() }; - // shape, the argument list, Metal's pages for it, ours. - let rows: &[(&str, &[(u64, u64, Region)], usize, usize)] = &[ + // shape, the argument list, Metal's pages for it. + let rows: &[(&str, &[(u64, u64, Region)], usize)] = &[ // The controls, through the indirect selector: one in-bounds tile is one page, two are // two, so the reading follows the list rather than being fixed by construction. - ("indirect-control", &[(0, 0, one(0, 0))], 1, 1), + ("indirect-control", &[(0, 0, one(0, 0))], 1), ( "indirect-two-inbounds", &[(0, 0, one(0, 0)), (0, 0, one(1, 0))], 2, - 2, ), // 1. ALONE. Metal charges one page for the out-of-bounds slice; the direct selector read // the same one page for it (`direct-slice-alone`, which is the committed reading off // `sparse_mapping_past_the_bounds.m`). So "none alone" is false, for either selector. - ("indirect-slice-alone", &[(0, 2, one(0, 0))], 1, 0), + ("indirect-slice-alone", &[(0, 2, one(0, 0))], 1), // 2. BESIDE ANOTHER REGION. Two pages, where the in-bounds region alone is one: the // out-of-bounds region added exactly the one page it adds alone, never a tile more. ( "indirect-slice-beside", &[(0, 0, one(0, 0)), (0, 2, one(0, 0))], 2, - 1, ), // And with four pages already mapped it went 4 -> 5, again exactly one, so the charge is // the same in every configuration rather than varying with what else is mapped. - ("indirect-slice-after-four", &[(0, 2, one(0, 0))], 1, 0), + ("indirect-slice-after-four", &[(0, 2, one(0, 0))], 1), // The charge follows the REGION, clipped to the level: 8 by 8 tiles on a level holding // 4 by 4 cost 16 pages on the out-of-bounds slice, as they do on an in-bounds one. ( "indirect-slice-big-region", &[(0, 2, Region::new_2d(0, 0, 8, 8))], 16, - 0, ), // One page per out-of-bounds region, not one per update: slices 2 and 3 cost two. ( "indirect-two-oob-slices", &[(0, 2, one(0, 0)), (0, 3, one(0, 0))], 2, - 0, ), // The level and the origin ARE bounded, and cost nothing — which is what makes the slice // the one unbounded axis rather than a general "Metal does not check". - ("indirect-level-alone", &[(9, 0, one(0, 0))], 0, 0), - ("indirect-origin-alone", &[(0, 0, one(4, 4))], 0, 0), + ("indirect-level-alone", &[(9, 0, one(0, 0))], 0), + ("indirect-origin-alone", &[(0, 0, one(4, 4))], 0), ]; - for (shape, regions, metal, mine) in rows { - assert_eq!(ours(regions), *mine, "what the runtime counts for {shape}"); - // Where the runtime parts from Metal it is only ever by counting LESS, and only for a - // region whose slice is past the texture's: a row that counted more would be a bug the - // other way, and is not a thing any reading showed. - assert!( - *mine <= *metal, - "{shape}: the runtime counts {mine} pages where Metal counted {metal}" - ); - let out_of_bounds = regions.iter().any(|(_, slice, _)| *slice >= 2); - assert_eq!( - *mine == *metal, - !out_of_bounds, - "{shape}: only a slice past the texture's may part from Metal's count" - ); + for (shape, regions, metal) in rows { + assert_eq!(ours(regions), *metal, "what the runtime counts for {shape}"); } // 3. AN UNMAP OF IT, in every configuration measured. Metal's charge is reversible and @@ -1110,20 +1096,22 @@ fn a_slice_past_the_textures_is_the_one_axis_metal_does_not_bound() { // `indirect-map-then-unmap-slice` 0 -> 1 -> 0, the page given back exactly; // `indirect-slice-unmap-twice` 0 -> 1 -> 0 -> 0, a second unmap taking nothing more; // `indirect-slice-twice` 0 -> 1 -> 1, the charge idempotent per region. - // So "below zero" is false. The runtime cannot go below zero either, and for a stronger - // reason than a measurement: the clip names no unit for such a region at all, and - // `SparseHeap::give` saturates besides. - assert_eq!( - ours(&[(0, 2, one(0, 0))]), - 0, - "an unmap of slice 2 of 2 names no unit, whatever the count stands at" + // So "below zero" is false. The runtime gives a unit's page back only where its map took + // it (`SparseState::charged`, `sparse/bind.rs`'s `apply`), and `SparseHeap::give` + // saturates besides. + let past = array.clipped_region(0, 2, &one(0, 0)); + assert_eq!(past, vec![tile(0, 2, [0, 0])]); + assert!( + array.past_slices(past[0]), + "slice 2 of 2 is past the texture's" ); // A slice past a 1-slice texture's own, which is the shape the suite's non-array sparse // cases use, clips the same way. let plain = grid([256, 256, 1], 9, 1, 3, false); - assert!( - plain.clipped_region(0, 1, &one(0, 0)).is_empty(), + assert_eq!( + plain.clipped_region(0, 1, &one(0, 0)), + vec![tile(0, 1, [0, 0])], "slice 1 of 1" ); } diff --git a/docs/API.md b/docs/API.md index 8d0684eac..7ca8d3eda 100644 --- a/docs/API.md +++ b/docs/API.md @@ -4234,6 +4234,15 @@ each item named states the rule in full. - **A `Shared` heap's textures are linear images** where the device's optimal images take no host-visible memory. - **A sparse texture on a device without shader residency holds all its texels' memory.** +- **A sparse mapping update of a slice past the texture's own maps nothing.** Metal's API + validation refuses such an update; plain Metal takes it, charges its heap's `usedSize` one page + a tile of the region (clipped to the level's tiles), and binds that page at an address its own + page layout derives: on an Apple M3 Max under macOS 27.0.1 a 16 by 16 texel block of slice 0's + mapped tile (0, 0) then read Metal's unwritten pattern. The runtime charges the heap the same + pages, given back on an unmap of each tile (`ResourceStateCommandEncoder:: + update_texture_mapping`), and leaves every texel as it was: Vulkan binds nothing past an image's + layers (`VUID-VkSparseImageMemoryBindInfo-subresource-01723`), and which texels Metal's page + reaches is not derivable from what was measured. - **A heap's buffer and texture over the same bytes alias them, in the device's layout**, not Apple's tiled or compressed one.