RUNTIME 2412: Bind shapes tell buffer length classes apart only as far as the device's range limits do

What: a new public bind::BufferRanges (a device's maxUniformBufferRange and
maxStorageBufferRange, BufferRanges::of(limits)), carried on each StageTable (buffer_ranges,
serde default), which the runtime sets on every table it reads (argument_table's AtBindViews,
beside the view base alignment: stage_table_reading, refresh_reading and the in-part
refreshes, AtBindViews::holds, and the debug check of a kept table). A buffer's shape states its
length class rounded up to the greatest class that fits the same limits
(BufferRanges::length_class); a class past both stays its own. BoundBuffer::shape and same_shape
take the ranges; BoundKind::of_bound and instantiate::bound_buffer class the bound length under
the table's ranges, so the instantiation's kind check takes a binding exactly where its class is
the plan's. The default (both 0) tells every class apart, as before.

Why: a guest compositor's serial compute encoder of ~1,140 fix-up dispatches over buffers of
many sizes made a new bind shape at 46% of its dispatches and planned again at 69% (the
consumer's XTX walks). A plan reads a length class only through class_fits against those two
limits (storage_view_variant and large_view_candidates against maxUniformBufferRange,
psb_variant and range_variant against maxStorageBufferRange); otherwise it only stores the class
for the kind check. On an RX 7900 XTX both limits are 4294967295, so every buffer below 4 GiB
takes the same plan decisions, and the dispatch_chain bench's 44 length-class shapes were one
plan. The bench there (job m3-max-34605, interleaved) matched the walk's split exactly (made
46%, found 18%, kept 36%) at 7.1-7.6 us a dispatch, against 4.1-4.4 us for the same stream of
one shape.

Exact: under the device's own limits, every class_fits answer of the rounded class is the exact
class's, so every plan decision, variant key and specialization is the same; under any other
limits the rounded class still bounds the padded length from above (padded < 2^class), so no
plan reads a range past a limit (it may take only a longer buffer's form).

Digests, cache keys and stored records: none carries the class. BindShape keys only in-memory
memos (Variant::plans, a state's kept Planned entries, the dispatch memo, the render draw
shapes); artifact digests and region keys are functions of the variant key and specializations,
which this leaves equal; validation and executor states keep the default ranges, so their shapes
and plans are unchanged; no pipeline record or warm record holds a shape. The serde form of
StageTable gains a defaulted field. So no SEMANTICS bump, in my reading.

Tests: bind::plan::slots length_classes_are_told_apart_as_far_as_a_plan_reads_them (4 GiB
limits, 64 KiB/128 MiB both ways round, 16 KiB, and none: every length's class answers both
limits' class_fits as the exact class does, bounds its padded length, is exact under none, and
bound_buffer takes a binding for another length's kind exactly where the classes are one, only
where the exact classes answer both limits alike); bind_shape_of's has_shape states and
same_shape pairs over range limits; runtime grid_classes
lengths_the_device_tells_apart_nowhere_plan_once (outputs of four length classes under 16 KiB,
one shape, 23 of 24 dispatches planned as before; 20 without this), and
shapes_and_classes_in_turn_each_plan_once re-made from the constant's binding (inline bytes, a
buffer, a buffer with a per-bind stride), since its three length classes are now one shape.
API: signatures blessed, api_surface, docs/API.md.

Also: 674c995a42 (dispatch_chain --zero-classes and --stay: a guest's fix-up dispatches over buffers of
many sizes), ad406afa87 (clippy in the new test).

Verified in the lane (m3-max-34674, gem10, at ad406afa87): clippy -D warnings -p metal2vulkan
-p metal2vulkan-runtime --all-targets --all-features; translator tests 21/21 (the new
length_classes test, bind_shape_of, the slots tests). Still running when landed: the XTX bench before
and after (release, interleaved), the lavapipe bench, the runtime suite under m2v_cpu_icd on lavapipe,
the negative control (AtBindViews ranges set back to the default fails the new runtime test), clippy
gpucfg and cpuicd, rustdoc.

API: adds bind::BufferRanges and StageTable::buffer_ranges (serde default); additive.
This commit is contained in:
Anees Iqbal committed 2026-11-15 19:20:06 -08:00
1 parent a842f346cb
commit 725d2913d7
13 files changed
+526 -115

No files matched your search

@@ -6,7 +6,8 @@
//! cargo run --release -p metal2vulkan-runtime --example dispatch_chain -- \
//! [--dispatches N] [--groups G] [--threads T] [--runs R] [--only SHAPE,...] \
//! [--binds 1|4|tex|ptr] [--host C] [--pages] [--heap] [--heap-churn K] [--heap-kept H] \
//! [--live L] [--idle MS]
//! [--live L] [--idle MS] [--vary] [--ragged] [--samplers K] [--classes K] [--zero-classes Z]
//! [--stay Q]
//! ```
//!
//! Each run is one command buffer of `N` dispatches (200 by default) of `G` threadgroups of `T`
@@ -98,7 +99,13 @@
//! device holds its programs' samplers. `--classes K` binds `--binds moved`'s and `fixed`'s 1s at
//! index 3 from `K` buffers (1 to 12, of 16 KiB up to 32 MiB) of `K` length classes in turn
//! (`BindState::shape`'s `length_class`), so the dispatches' bind state takes `K` shapes, as a
//! guest's buffers of many sizes do.
//! guest's buffers of many sizes do. `--zero-classes Z` binds the zeros at indices 1 and 2 from `Z`
//! pairs of buffers (1 to 8, each class twice the length of the one before), dispatch `n` the pair
//! of class `n / K % Z`, so the bind state takes `K * Z` shapes. `--stay Q` binds dispatch `n`'s
//! classes as dispatch `n - 1` bound them at a chance of `Q` percent, and else a pair of the
//! `K * Z` drawn evenly, from a generator of a fixed seed (every command buffer binds the same
//! sequence): as a guest's fix-up dispatches take the buffers of the draws they fix, some in a row
//! of one buffer, the rest scattered over many.
//! With `--binds tex` they run `bump_tex`, which samples two 16 by 16 `RGBA8Unorm` textures at
//! indices 0 and 1 through a sampler at 0, and reads a word of 1 set as bytes at buffer index 1
//! (`a[gid] += k`, plus 1000 where a texel's red is below -1e30, which none is): each dispatch
@@ -425,6 +432,11 @@ struct Shape {
samplers: u32,
/// The length classes of the buffers of 1s (`--classes`).
classes: u32,
/// The length classes of the pairs of buffers of zeros (`--zero-classes`).
zero_classes: u32,
/// The percent chance that a dispatch binds the classes the one before it bound, each other
/// dispatch any pair of classes in turn from a fixed sequence (`--stay`).
stay: Option<u32>,
}
/// The dispatches of `--ragged`'s cycle of thread counts.
@@ -459,6 +471,8 @@ impl Shape {
ragged: false,
samplers: 0,
classes: 1,
zero_classes: 1,
stay: None,
};
let mut args = std::env::args().skip(1);
while let Some(flag) = args.next() {
@@ -494,6 +508,8 @@ impl Shape {
"--idle" => shape.idle = Duration::from_millis(value.parse()?),
"--samplers" => shape.samplers = value.parse()?,
"--classes" => shape.classes = value.parse()?,
"--zero-classes" => shape.zero_classes = value.parse()?,
"--stay" => shape.stay = Some(value.parse()?),
_ => return Err(format!("unknown flag {flag}").into()),
}
}
@@ -512,6 +528,16 @@ impl Shape {
if !(1..=12).contains(&shape.classes) {
return Err("--classes takes 1 to 12".into());
}
if !(1..=8).contains(&shape.zero_classes) {
return Err("--zero-classes takes 1 to 8".into());
}
if shape.stay.is_some_and(|stay| stay > 100) {
return Err("--stay takes a percent, 0 to 100".into());
}
let moved = matches!(shape.binds, Binds::Moved | Binds::Fixed);
if (shape.zero_classes > 1 || shape.stay.is_some()) && !moved {
return Err("--zero-classes and --stay take --binds moved or fixed".into());
}
let zeros_read = matches!(shape.binds, Binds::Wide | Binds::Pointer);
if shape.churn.is_some() && (shape.host.is_none() || !zeros_read) {
return Err("--heap-churn takes --host and --binds 4 or ptr".into());
@@ -529,6 +555,40 @@ impl Shape {
u64::from(self.groups) * u64::from(self.threads)
}
/// The length classes each dispatch of a command buffer binds, of its buffer of 1s
/// (`--classes`) and of its pair of zeros (`--zero-classes`): dispatch `n`'s are `n % K` and
/// `n / K % Z`, but under `--stay Q`, where dispatch `n` binds those of dispatch `n - 1` at a
/// chance of `Q` percent, and else a pair drawn evenly from all `K * Z`, from a generator of a
/// fixed seed, so every command buffer binds the same sequence.
fn picks(&self) -> Vec<(usize, usize)> {
let (ones, zeros) = (self.classes as usize, self.zero_classes as usize);
let Some(stay) = self.stay else {
return (0..self.dispatches as usize)
.map(|n| (n % ones, n / ones % zeros))
.collect();
};
// A 64-bit linear congruential generator (Knuth's MMIX constants), its high bits drawn.
let mut state = 0x5eed_u64;
let mut draw = |below: u64| {
state = (state.wrapping_mul(6_364_136_223_846_793_005))
.wrapping_add(1_442_695_040_888_963_407);
(state >> 33) % below
};
let mut picks: Vec<(usize, usize)> = Vec::with_capacity(self.dispatches as usize);
for _ in 0..self.dispatches {
let kept = picks
.last()
.copied()
.filter(|_| draw(100) < u64::from(stay));
let pick = kept.unwrap_or_else(|| {
let pair = draw((ones * zeros) as u64) as usize;
(pair % ones, pair / ones)
});
picks.push(pick);
}
picks
}
/// The threadgroups of an encoder's dispatch `n`: all of them, or `1 + n % groups` with
/// `--vary`.
fn grid(&self, n: u32) -> Size {
@@ -893,13 +953,20 @@ const CHUNK: u64 = 0x1_0000;
struct Placed {
heap: Heap,
_ram: Buffer,
/// Each buffer's offset in the heap and length, in the order they are placed.
places: Vec<(u64, u64)>,
}
impl Placed {
/// Room for three buffers of `bytes` bytes, each in chunks of its own.
fn new(device: &Device, bytes: u64) -> Result<Placed> {
let each = bytes.div_ceil(CHUNK) * CHUNK;
let length = CHUNK + 3 * each;
/// Room for buffers of `lengths` bytes, each in chunks of its own.
fn new(device: &Device, lengths: &[u64]) -> Result<Placed> {
let mut places = Vec::with_capacity(lengths.len());
let mut room = 0;
for &bytes in lengths {
places.push((room, bytes));
room += bytes.div_ceil(CHUNK) * CHUNK;
}
let length = CHUNK + room;
let pages = host_pages(length as usize)?;
// SAFETY: page-aligned read-write memory of `length` bytes, never unmapped, which outlives
// the buffer.
@@ -913,21 +980,24 @@ impl Placed {
}?;
// SAFETY: inside the mapping, past its first chunk.
let at = NonNull::new(unsafe { pages.as_ptr().add(CHUNK as usize) }).ok_or("null")?;
let descriptor =
HeapDescriptor::new(HeapType::Placement, 3 * each, ResourceOptions::shared());
let descriptor = HeapDescriptor::new(HeapType::Placement, room, ResourceOptions::shared());
// SAFETY: the mapping past its first chunk, which outlives the heap.
let heap = unsafe {
device.new_heap_with_bytes_no_copy(HostMemory::new(at), &descriptor, None, None)
}?;
Ok(Placed { heap, _ram: ram })
Ok(Placed {
heap,
_ram: ram,
places,
})
}
/// The `n`th buffer of `bytes` bytes placed in the heap.
fn buffer(&self, n: u64, bytes: u64) -> Result<Buffer> {
let each = bytes.div_ceil(CHUNK) * CHUNK;
/// The `n`th buffer placed in the heap, of the `n`th length it has room for.
fn buffer(&self, n: usize) -> Result<Buffer> {
let (offset, bytes) = *self.places.get(n).ok_or("no room in the placed heap")?;
Ok(self
.heap
.new_buffer_at_offset(bytes, ResourceOptions::shared(), n * each)?)
.new_buffer_at_offset(bytes, ResourceOptions::shared(), offset)?)
}
}
@@ -1046,10 +1116,13 @@ struct Ours<'a> {
device: &'a Device,
state: ComputePipelineState,
words: Buffer,
zeros: [Buffer; 2],
/// Pairs of buffers of zeros, of one length class each (`--zero-classes`), the least first.
zeros: Vec<[Buffer; 2]>,
/// Words of 1, [`MOVES`] places of [`MOVE_STRIDE`] bytes, for `--binds moved` and `fixed`, of
/// one length class each (`--classes`).
ones: Vec<Buffer>,
/// The classes of 1s and of zeros each dispatch of a command buffer binds ([`Shape::picks`]).
picks: Vec<(usize, usize)>,
textures: [Texture; 2],
sampler: SamplerState,
readback: Buffer,
@@ -1136,7 +1209,7 @@ impl Ours<'_> {
Binds::One => encoder.set_buffer(Some(&self.words), 0, 0)?,
Binds::Wide | Binds::Pointer => {
let (b, c) = match churned.len() {
0 => (&self.zeros[n % 2], &self.zeros[1 - n % 2]),
0 => (&self.zeros[0][n % 2], &self.zeros[0][1 - n % 2]),
k => (&churned[(2 * n) % k], &churned[(2 * n + 1) % k]),
};
encoder.set_buffer(Some(&self.words), 0, 0)?;
@@ -1152,12 +1225,13 @@ impl Ours<'_> {
Binds::Moved => MOVE_STRIDE * (n as u64 % MOVES),
_ => 0,
};
let (b, c) = (&self.zeros[n % 2], &self.zeros[1 - n % 2]);
let (one, zero) = self.picks[n % self.picks.len()];
let zeros = &self.zeros[zero];
let (b, c) = (&zeros[n % 2], &zeros[1 - n % 2]);
encoder.set_buffers(&[Some(&self.words)], &[0], 0)?;
encoder.set_buffers(&[Some(b)], &[at], 1)?;
encoder.set_buffers(&[Some(c)], &[at], 2)?;
let ones = &self.ones[n % self.ones.len()];
encoder.set_buffers(&[Some(ones)], &[at], 3)?;
encoder.set_buffers(&[Some(&self.ones[one])], &[at], 3)?;
}
Binds::Textures => {
encoder.set_texture(Some(&self.textures[n % 2]), 0)?;
@@ -1452,7 +1526,7 @@ impl Ours<'_> {
let command_buffer = queue.command_buffer()?;
let mut blit = command_buffer.blit_command_encoder()?;
blit.fill_buffer(&self.words, 0..self.words.length(), value)?;
for zeros in &self.zeros {
for zeros in self.zeros.iter().flatten() {
blit.fill_buffer(zeros, 0..zeros.length(), 0)?;
}
blit.end_encoding()?;
@@ -2009,15 +2083,19 @@ fn main() -> Result<()> {
Binds::Moved | Binds::Fixed => bytes + MOVE_STRIDE * MOVES,
_ => bytes,
};
// Each pair of zeros of class `z` is `2^z` times the least pair's length.
let lengths: Vec<u64> = std::iter::once(bytes)
.chain((0..shape.zero_classes).flat_map(|z| [zeros << z; 2]))
.collect();
let placed = match shape.heap {
true => Some(Placed::new(&device, zeros)?),
true => Some(Placed::new(&device, &lengths)?),
false => None,
};
let mut place = 0;
let mut buffer = |bytes: u64| -> Result<Buffer> {
if let Some(placed) = &placed {
place += 1;
return placed.buffer(place - 1, bytes);
return placed.buffer(place - 1);
}
if !shape.pages {
return Ok(device.new_buffer(bytes, ResourceOptions::private())?);
@@ -2066,11 +2144,14 @@ fn main() -> Result<()> {
let ours = Ours {
device: &device,
state: state(&device, shape.binds)?,
words: buffer(bytes)?,
zeros: [buffer(zeros)?, buffer(zeros)?],
words: buffer(lengths[0])?,
zeros: (lengths[1..].chunks(2))
.map(|pair| Ok([buffer(pair[0])?, buffer(pair[1])?]))
.collect::<Result<_>>()?,
ones: (0..shape.classes)
.map(|class| ones(&device, class))
.collect::<Result<_>>()?,
picks: shape.picks(),
textures: [texture()?, texture()?],
sampler: device.new_sampler_state(&SamplerDescriptor::new())?,
readback: device.new_buffer(bytes, ResourceOptions::shared())?,
@@ -53,7 +53,9 @@ use super::tracker::{Access, Use};
use super::upload::Upload;
use super::work_counts::{Counting, ReshapedBy};
use ash::vk;
use metal2vulkan::bind::{BindState, BoundBuffer, BoundSampler, BoundTexture, StageTable};
use metal2vulkan::bind::{
BindState, BoundBuffer, BoundSampler, BoundTexture, BufferRanges, StageTable,
};
use metal2vulkan::device::DriverWorkaround;
use metal2vulkan::pipeline::{
BufferKind, PipelineInterface, RenderPipeline, SlotClass, SlotInterface, SlotRef, Stage,
@@ -106,6 +108,9 @@ pub(crate) struct AtBindViews {
zero_slots: [AtomicU64; VIEW_STAGES.len()],
/// The device's view base alignment (`BindState::view_base_alignment_of`).
alignment: u32,
/// The device's buffer range limits (`BufferRanges::of`), under which its states' tables
/// class their buffers' lengths (`StageTable::buffer_ranges`).
ranges: BufferRanges,
/// Whether the device reads every uniform view at its residual
/// (`pipeline::reads_views_at_bind`), which a bind state states
/// (`BindState::uniform_views_at_residual`).
@@ -141,6 +146,7 @@ impl AtBindViews {
slots: VIEW_STAGES.map(|stage| AtomicU64::new(interface.uniform_view_buffers(stage))),
zero_slots: VIEW_STAGES.map(|stage| AtomicU64::new(storage(stage))),
alignment: BindState::view_base_alignment_of(limits),
ranges: BufferRanges::of(limits),
at_residual: !crate::pipeline::reads_views_at_bind(device),
read,
}
@@ -168,13 +174,15 @@ impl AtBindViews {
}
/// Whether `stage`'s slots of both sets are those `table` holds (none for a stage it does not
/// keep): a table read under them that binds the same offsets leaves the same out
/// ([`ArgumentTable::at_bind_views`], [`ArgumentTable::zero_offset_views`]), as it left out
/// its own as it was read.
/// keep), and its buffer range limits the device's: a table read under them that binds the
/// same offsets leaves the same out ([`ArgumentTable::at_bind_views`],
/// [`ArgumentTable::zero_offset_views`]), as it left out its own as it was read, and classes
/// its buffers' lengths alike.
pub(super) fn holds(&self, stage: Stage, table: &StageTable) -> bool {
let now = |slots: Option<&AtomicU64>| slots.map_or(0, |s| s.load(Ordering::Relaxed));
now(self.of(stage)) == table.at_bind_views
&& now(self.zero_of(stage)) == table.zero_offset_views
&& table.buffer_ranges == self.ranges
}
/// `stage`'s slots, none for a stage it does not keep.
@@ -1510,8 +1518,9 @@ impl ArgumentTable {
/// stops the command (an M3 Max and an M4), and so is a table bound where it reads a buffer,
/// whose slot then reads zeros, as plain Metal's read (an M4). Its slots that tell the device's
/// view base alignment apart are those of `views`, the state's, as
/// [`at_bind_views`](Self::at_bind_views) leaves them, and its slots that tell offset 0 apart
/// as [`zero_offset_views`](Self::zero_offset_views) leaves them.
/// [`at_bind_views`](Self::at_bind_views) leaves them, its slots that tell offset 0 apart
/// as [`zero_offset_views`](Self::zero_offset_views) leaves them, and its buffers' lengths
/// classed under the device's buffer range limits, the state's `views` hold.
pub(super) fn stage_table_reading(
&self,
stage: Stage,
@@ -1521,6 +1530,7 @@ impl ArgumentTable {
let mut table = self.stage_table();
table.at_bind_views = self.at_bind_views(stage, views);
table.zero_offset_views = self.zero_offset_views(stage, views);
table.buffer_ranges = views.ranges;
let read = |class, index| views.read.reads(stage, class, index);
table
.buffers
@@ -1613,14 +1623,15 @@ impl ArgumentTable {
reshape: &mut Reshape,
) {
let read = (stage, interface);
// The slots that tell the view base alignment and offset 0 apart first, which the
// buffers' shapes read.
// The slots that tell the view base alignment and offset 0 apart and the buffer range
// limits first, which the buffers' shapes read.
reshape.field(&mut kept.at_bind_views, self.at_bind_views(stage, views));
reshape.field(
&mut kept.zero_offset_views,
self.zero_offset_views(stage, views),
);
let alignment = views.alignment;
reshape.field(&mut kept.buffer_ranges, views.ranges);
let (alignment, ranges) = (views.alignment, views.ranges);
// The slots the state holds alone (`ReadSlots`).
let held = |class, index| views.read.reads(stage, class, index);
kept.buffers.retain(|&index, _| {
@@ -1643,7 +1654,7 @@ impl ArgumentTable {
if let Some(bound) = bound_buffer(buffer, *offset, stride) {
let a = kept.class_alignment(index, alignment);
reshape.slot(SlotClass::Buffer, &mut kept.buffers, index, bound, |b| {
b.shape(a)
b.shape(a, ranges)
});
}
}
@@ -1655,7 +1666,7 @@ impl ArgumentTable {
&mut kept.buffers,
index,
bound_bytes(bytes),
|b| b.shape(a),
|b| b.shape(a, ranges),
);
}
}
@@ -1739,9 +1750,11 @@ impl ArgumentTable {
let Some(changed) = self.changes.since(read) else {
return false;
};
// A buffer's shape reads these slots: where they changed, every buffer is read again.
// A buffer's shape reads these slots and the buffer range limits: where they changed,
// every buffer is read again.
if self.at_bind_views(stage, views) != kept.at_bind_views
|| self.zero_offset_views(stage, views) != kept.zero_offset_views
|| views.ranges != kept.buffer_ranges
{
return false;
}
@@ -1833,7 +1846,7 @@ impl ArgumentTable {
(alignment, counts): (u32, Counting<'_>),
reshape: &mut Reshape,
) {
let a = kept.class_alignment(index, alignment);
let (a, ranges) = (kept.class_alignment(index, alignment), kept.buffer_ranges);
let held = (self.buffers.get(&index)).filter(|(buffer, offset)| *offset <= buffer.length());
let (Some((buffer, offset)), Some(slot)) = (held, kept.buffers.get_mut(&index)) else {
return self.refresh_buffer((kept, index), read, alignment, reshape);
@@ -1869,7 +1882,7 @@ impl ArgumentTable {
);
counts.bound_offset_moved();
reshape.replace_by(ReshapedBy::BufferOffset, slot, bound, |was, now| {
was.same_shape(now, a)
was.same_shape(now, a, ranges)
});
}
@@ -1893,20 +1906,20 @@ impl ArgumentTable {
}
return;
}
let a = kept.class_alignment(index, alignment);
let (a, ranges) = (kept.class_alignment(index, alignment), kept.buffer_ranges);
if let Some(bytes) = self.bytes.get(&index) {
reshape.slot(
SlotClass::Buffer,
&mut kept.buffers,
index,
bound_bytes(bytes),
|b| b.shape(a),
|b| b.shape(a, ranges),
);
} else if let Some((buffer, offset)) = self.buffers.get(&index) {
let stride = self.attribute_strides.get(&index).copied();
if let Some(bound) = bound_buffer(buffer, *offset, stride) {
reshape.slot(SlotClass::Buffer, &mut kept.buffers, index, bound, |b| {
b.shape(a)
b.shape(a, ranges)
});
}
}
@@ -1973,6 +1986,13 @@ impl ArgumentTable {
);
}
}
assert!(
kept.buffer_ranges == views.ranges,
"{DIFFERS}: {stage:?} classes its buffers' lengths under {:?}, the device's limits \
are {:?}",
kept.buffer_ranges,
views.ranges
);
// A buffer slot as `stage_table_reading` reads it: inline bytes where they are bound,
// else the buffer within its length, and nothing where the function reads it unbound.
let held = |class, index| views.read.reads(stage, class, index);
@@ -16,10 +16,15 @@
//! second, at another offset, leaves its slot out from then on (`argument_table::AtBindViews`), so
//! the next dispatch of the first slice's class is the first of its class in that shape.
//!
//! [`shapes_and_classes_in_turn_each_plan_once`]: the flat kernel's output bound from buffers of
//! three length classes, three bind state shapes, by grids of two classes, dispatched in turn: six
//! plans, which the state keeps all of (`pipeline::PLANNED`), so each plans once; on a profile whose
//! storage views declare the key, one more, the first dispatch's at offset 0 (as above).
//! [`shapes_and_classes_in_turn_each_plan_once`]: the flat kernel's constant bound as inline
//! bytes, from a buffer and from a buffer with a per-bind stride, three bind state shapes, by grids
//! of two classes, dispatched in turn: six plans, which the state keeps all of
//! (`pipeline::PLANNED`), so each plans once; on a profile whose storage views declare the key,
//! one more, the first dispatch's at offset 0 (as above).
//!
//! [`lengths_the_device_tells_apart_nowhere_plan_once`]: the flat kernel's output bound from
//! buffers of four length classes under 16 KiB, which every device's buffer range limits tell
//! apart nowhere (`bind::BufferRanges`): one bind state shape, which plans once.
//!
//! [`a_grid_past_the_device_limits_meets_the_refusal_a_fresh_state_meets`]: a grid of a class
//! planned before whose group counts no device holds is refused as a state that planned nothing
@@ -170,6 +175,11 @@ fn dispatch(
) -> Result<(), Error> {
encoder.set_buffer(Some(out), (slice * SLICE * 4) as u64, 0)?;
encoder.set_bytes(&k.to_le_bytes(), 1)?;
run(encoder, grid)
}
/// Dispatch `grid` of the state `encoder` binds, as it binds it.
fn run(encoder: &mut ComputeCommandEncoder, grid: Grid) -> Result<(), Error> {
let [lx, ly] = grid.local();
let local = Size::new(u64::from(lx), u64::from(ly), 1);
match grid {
@@ -306,11 +316,19 @@ fn a_grid_past_the_device_limits_meets_the_refusal_a_fresh_state_meets() {
);
}
/// The bind state shapes [`shapes_and_classes_in_turn_each_plan_once`] dispatches in turn.
/// The bind state shapes [`shapes_and_classes_in_turn_each_plan_once`] dispatches in turn: the
/// kernel's constant bound as inline bytes, from a buffer, and from a buffer with a per-bind
/// stride (`BufferShape`'s `attribute_stride`, which the kernel, of no stage-in layout, does not
/// read).
const SHAPES: usize = 3;
/// The flat kernel's output bound from buffers of [`SHAPES`] length classes (`BindState::shape`'s
/// `length_class`), each its own bind state shape, by ragged and whole one-row grids, two classes
/// The bytes between the constants of [`shapes_and_classes_in_turn_each_plan_once`]'s buffer of
/// them: a multiple of every device's view base alignment, so that the uniform view of each bound
/// starts at its bind offset alike (`SpecKey::RangeAtBindOffset`), one shape for them all.
const CONSTANT_STRIDE: usize = 256;
/// The flat kernel's constant bound in [`SHAPES`] ways, each its own bind state shape, by ragged
/// and whole one-row grids, two classes
/// ([`GridClass`](crate::pipeline::GridClass)): six plans, dispatched in turn [`ROUNDS`] times in
/// one encoder, every grid its own. Each plans at its first dispatch alone, and every later
/// dispatch takes what its shape and class planned (`WorkCounts::dispatches_planned_as_before`),
@@ -334,10 +352,13 @@ fn shapes_and_classes_in_turn_each_plan_once() {
}
}
let plans = 2 * SHAPES;
// Lengths of one, two and four times the words every dispatch needs: three length classes.
let outs: Vec<Buffer> = (0..SHAPES)
.map(|shape| words_buffer(&device, &vec![UNWRITTEN; (SLICE * grids.len()) << shape]))
let out = words_buffer(&device, &vec![UNWRITTEN; SLICE * grids.len()]);
// Dispatch `n`'s constant, `n + 1`, at `n * CONSTANT_STRIDE` bytes.
let places = CONSTANT_STRIDE / 4;
let constants: Vec<u32> = (0..grids.len() * places)
.map(|word| (word / places) as u32 + 1)
.collect();
let constants = words_buffer(&device, &constants);
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
@@ -345,8 +366,15 @@ fn shapes_and_classes_in_turn_each_plan_once() {
let mut took = Vec::new();
for (slice, &(shape, grid)) in grids.iter().enumerate() {
let before = device.work_counts().dispatches_planned_as_before;
dispatch(&mut encoder, &outs[shape], (slice, slice as u32 + 1), grid)
.unwrap_or_else(|e| panic!("dispatch {slice} of {grid:?}: {e:?}"));
let (k, at) = (slice as u32 + 1, (slice * CONSTANT_STRIDE) as u64);
(encoder.set_buffer(Some(&out), (slice * SLICE * 4) as u64, 0)).unwrap();
match shape {
0 => encoder.set_bytes(&k.to_le_bytes(), 1),
1 => encoder.set_buffer(Some(&constants), at, 1),
_ => encoder.set_buffer_with_stride(Some(&constants), at, 4, 1),
}
.unwrap();
run(&mut encoder, grid).unwrap_or_else(|e| panic!("dispatch {slice} of {grid:?}: {e:?}"));
took.push(device.work_counts().dispatches_planned_as_before - before);
}
encoder.end_encoding().unwrap();
@@ -359,14 +387,77 @@ fn shapes_and_classes_in_turn_each_plan_once() {
took, want,
"the dispatches that took what their shape and class planned"
);
let written: Vec<Vec<u32>> = outs.iter().map(words).collect();
let written = words(&out);
for (slice, &(shape, grid)) in grids.iter().enumerate() {
let k = slice as u32 + 1;
let want = metal(grid, |i, _| 3 * i + k);
let got = &written[shape][slice * SLICE..(slice + 1) * SLICE];
let got = &written[slice * SLICE..(slice + 1) * SLICE];
assert_eq!(got, want, "dispatch {slice} of {grid:?} of shape {shape}");
}
}
/// The lengths of [`lengths_the_device_tells_apart_nowhere_plan_once`]'s outputs, in words: 1 to
/// 8 KiB, four length classes (`bind::length_class`), every one under 16 KiB, Vulkan's least
/// `maxUniformBufferRange`, so that every device's limits tell them apart nowhere
/// (`bind::BufferRanges::length_class`).
const OUTPUT_WORDS: [usize; 4] = [256, 512, 1024, 2048];
/// The flat kernel's output bound from buffers of [`OUTPUT_WORDS`], in turn [`ROUNDS`] times in
/// one encoder, each at offset 0, by one grid: lengths a plan reads only against the device's
/// buffer range limits, which tell none of them apart, so the encoder's bind state keeps one
/// shape, found or made once (`WorkCounts::dispatch_shapes_made` and `dispatch_shapes_found`),
/// and every dispatch but the first takes what that one planned
/// (`WorkCounts::dispatches_planned_as_before`): a state of a shape for each length class planned
/// each of its four first dispatches, a guest's stream of fix-up dispatches over buffers of many
/// sizes a shape and a plan at most of its dispatches. Every output holds its last dispatch's
/// words, as Metal's does.
#[test]
fn lengths_the_device_tells_apart_nowhere_plan_once() {
let scratch = Scratch::new("grid-classes-lengths");
let device = device(&scratch.0);
let state = state(&device, FLAT, "flat2d");
let grid = Grid::Threads([64, 1], [64, 1]);
let outs: Vec<Buffer> = (OUTPUT_WORDS.iter())
.map(|&words| words_buffer(&device, &vec![UNWRITTEN; words]))
.collect();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&state).unwrap();
let counts = || {
let c = device.work_counts();
(
c.dispatches_planned_as_before,
c.dispatch_shapes_made + c.dispatch_shapes_found,
)
};
let before = counts();
let dispatches = ROUNDS * outs.len();
for n in 0..dispatches {
let out = &outs[n % outs.len()];
dispatch(&mut encoder, out, (0, n as u32 + 1), grid)
.unwrap_or_else(|e| panic!("dispatch {n}: {e:?}"));
}
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let after = counts();
assert_eq!(
(after.0 - before.0, after.1 - before.1),
(dispatches as u64 - 1, 1),
"the dispatches that took what the first planned, and the shapes looked for"
);
for (at, out) in outs.iter().enumerate() {
let k = (dispatches - outs.len() + at) as u32 + 1;
let want: Vec<u32> = (0..OUTPUT_WORDS[at] as u32)
.map(|i| if i < 64 { 3 * i + k } else { UNWRITTEN })
.collect();
assert_eq!(
got, want,
"dispatch {slice} of {grid:?} into the output of shape {shape}"
words(out),
want,
"output {at} of {} words",
OUTPUT_WORDS[at]
);
}
}
+7 -7
View File
@@ -655,13 +655,13 @@ pub(crate) fn bound_buffer(
slot: SlotRef,
expected: BoundKind,
) -> Result<Option<&BoundBuffer>, BindError> {
let b = state
.stages
.get(&slot.stage)
.and_then(|t| t.buffers.get(&slot.index));
// The kind alone is compared, which no offset class changes.
let kind = BoundKind::of_bound(b);
debug_assert_eq!(kind, BoundKind::of(b.map(|b| b.shape(0)).as_ref()));
let table = state.stages.get(&slot.stage);
let b = table.and_then(|t| t.buffers.get(&slot.index));
// The kind alone is compared, which no offset class changes, its length classed as the
// table's buffer ranges class it in the shape.
let ranges = table.map(|t| t.buffer_ranges).unwrap_or_default();
let kind = BoundKind::of_bound(b, ranges);
debug_assert_eq!(kind, BoundKind::of(b.map(|b| b.shape(0, ranges)).as_ref()));
if kind != expected {
return Err(internal(format!(
"the bind state's shape differs from the plan's at {slot:?}"
+5 -5
View File
@@ -305,11 +305,11 @@ pub use replay::{
pub use state::{
ArgumentFunctionTable, ArgumentSampler, ArgumentSamplersShape, BindShape, BindState,
BoundAccelerationStructure, BoundBuffer, BoundSampler, BoundSamplerShape, BoundTexture,
BufferShape, CompensatedViewport, FragmentTests, FunctionTablesShape, HeapPlacement,
ImageblockSize, ResourceClass, SamplerDescriptor, SamplerShape, StageInRegion, StageShape,
StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts, TextureShape,
TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource, UsedShape,
VertexAmplification, ViewMapping, ZERO_OFFSET_CLASS, ZERO_OFFSET_TOLD,
BufferRanges, BufferShape, CompensatedViewport, FragmentTests, FunctionTablesShape,
HeapPlacement, ImageblockSize, ResourceClass, SamplerDescriptor, SamplerShape, StageInRegion,
StageShape, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts,
TextureShape, TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource,
UsedShape, VertexAmplification, ViewMapping, ZERO_OFFSET_CLASS, ZERO_OFFSET_TOLD,
};
// How `BindState::shape` classes a buffer: the crate reads it from `state`, and a consumer takes
// shapes from `BindState::shape`; only the crate's tests and validation reach it here.
+7 -5
View File
@@ -5,7 +5,9 @@
use std::collections::BTreeMap;
use super::{AccessClass, BoundKind, ByteRange, PlannedBuffer, ResourceUse, UseTarget};
use crate::bind::state::{BindShape, BoundBuffer, BufferShape, TextureShape, UsedClass, UsedShape};
use crate::bind::state::{
BindShape, BoundBuffer, BufferRanges, BufferShape, TextureShape, UsedClass, UsedShape,
};
use crate::device::profile::Limits;
use crate::device::requirements::VkFeature;
use crate::device::{mechanism, DeviceProfile};
@@ -88,9 +90,9 @@ impl BoundKind {
}
}
/// What `bound` binds at a buffer slot: [`of`](Self::of) its shape, which no offset class
/// changes, read without making the shape.
pub(crate) fn of_bound(bound: Option<&BoundBuffer>) -> BoundKind {
/// What `bound` binds at a buffer slot of a table of buffer range limits `ranges`: [`of`](Self::of)
/// its shape, which no offset class changes, read without making the shape.
pub(crate) fn of_bound(bound: Option<&BoundBuffer>, ranges: BufferRanges) -> BoundKind {
match bound {
None => BoundKind::Unbound,
Some(&BoundBuffer::Buffer {
@@ -99,7 +101,7 @@ impl BoundKind {
..
}) => BoundKind::Buffer {
device_address: device_address.is_some(),
length_class: crate::bind::state::length_class(length),
length_class: ranges.length_class(length),
},
Some(BoundBuffer::Bytes { .. }) => BoundKind::Bytes,
}
@@ -2,7 +2,8 @@
use super::*;
use crate::bind::state::{
length_class, BindState, BoundBuffer, ResourceClass, StageShape, UsedResource,
length_class, BindState, BoundBuffer, BufferRanges, ResourceClass, StageShape, StageTable,
UsedResource,
};
use crate::device::profile::BufferAccess;
use crate::pipeline::facts::{Mechanism, UniformViewChoice};
@@ -337,6 +338,102 @@ fn used_resources_are_written_only_by_stages_that_write_memory() {
);
}
/// Buffer range limits tell a buffer's length class apart as far as a plan reads it
/// (`BufferRanges::length_class`), under 4 GiB limits (an RX 7900 XTX's), limits of 64 KiB and
/// 128 MiB either way round, one limit of 16 KiB, and none (the default, every class its own):
/// the class a buffer's shape states of each length answers `class_fits` against each limit as
/// the exact class does (all a plan reads of it: `large_view_candidates`, `range_variant`), still
/// bounds the padded length from above, and is the exact one under none; and instantiation's kind
/// check (`instantiate::bound_buffer`) takes a binding of each length for the kind a plan of
/// another length stored exactly where the two classes are one, which is only where their exact
/// classes answer both limits alike.
#[test]
fn length_classes_are_told_apart_as_far_as_a_plan_reads_them() {
let mut lengths = vec![0u64, 1, 15, 16, 17, u64::MAX];
for bit in 4..64 {
lengths.extend([(1u64 << bit) - 1, 1 << bit, (1 << bit) + 1]);
}
let limits = [
BufferRanges::default(),
BufferRanges {
uniform: u32::MAX,
storage: u32::MAX,
},
BufferRanges {
uniform: 1 << 16,
storage: 1 << 27,
},
BufferRanges {
uniform: 1 << 27,
storage: 1 << 16,
},
BufferRanges {
uniform: 1 << 14,
storage: 1 << 14,
},
];
for ranges in limits {
let fits = |class| {
[ranges.uniform, ranges.storage].map(|limit| class_fits(class, u64::from(limit)))
};
let states: Vec<BindState> = (lengths.iter())
.map(|&length| {
let mut table = StageTable {
buffer_ranges: ranges,
..StageTable::default()
};
let bound = BoundBuffer::Buffer {
gpu_address: 0x1_0000,
length,
offset: 0,
device_address: Some(0x2_0000),
attribute_stride: None,
};
table.buffers.insert(0, bound);
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);
state
})
.collect();
for (&a, state) in lengths.iter().zip(&states) {
let (exact, class) = (length_class(a), ranges.length_class(a));
let what = format!("{ranges:?}, {a} bytes");
assert_eq!(
fits(class),
fits(exact),
"{what}: class {class}, exact {exact}"
);
let padded = u128::from(a).next_multiple_of(16);
assert!(padded < 1u128 << class, "{what}: class {class}");
if ranges == BufferRanges::default() {
assert_eq!(class, exact, "{what}");
}
let shape = state.shape();
let expected = BoundKind::of(shape.stages[&Stage::Kernel].buffers.get(&0));
for (&b, other) in lengths.iter().zip(&states) {
let took = crate::bind::instantiate::bound_buffer(other, slot(0), expected).is_ok();
assert_eq!(
took,
ranges.length_class(b) == class,
"{what}: a binding of {b} bytes for its kind"
);
if took {
assert_eq!(
fits(length_class(b)),
fits(exact),
"{what}: {b} bytes alike"
);
}
}
}
}
// Under 4 GiB limits every length up to 4 GiB is one class, past them each its own.
let ranges = limits[1];
assert_eq!(ranges.length_class(1), ranges.length_class((1 << 32) - 16));
assert_ne!(ranges.length_class(1), ranges.length_class(1 << 32));
assert_ne!(ranges.length_class(1 << 32), ranges.length_class(1 << 33));
}
/// A buffer bound by shape and state agree on the bound kind, including the length class.
#[test]
fn the_bound_kind_carries_the_length_class() {
@@ -348,7 +445,7 @@ fn the_bound_kind_carries_the_length_class() {
attribute_stride: None,
};
assert_eq!(
BoundKind::of(Some(&b.shape(0))),
BoundKind::of(Some(&b.shape(0, BufferRanges::default()))),
BoundKind::Buffer {
device_address: true,
length_class: 7
@@ -509,7 +606,7 @@ fn a_uniform_range_starts_at_the_bind_offset_where_the_specialization_says() {
device_address: None,
attribute_stride: None,
}
.shape(alignment as u32);
.shape(alignment as u32, BufferRanges::default());
let at = range_at_bind_offset(&b, Some(&shape), limits);
let what = format!("{stem} {window:?} {bind_offset}");
// A window starting below the bind offset, or past the allocation's end (whose
@@ -582,12 +679,12 @@ fn a_storage_range_starts_at_the_bind_offset_only_at_offset_0() {
device_address: None,
attribute_stride: None,
};
let untold = bound.shape(0);
let untold = bound.shape(0, BufferRanges::default());
assert!(
!range_at_bind_offset(&b, Some(&untold), limits),
"{what}: untold"
);
let told = bound.shape(crate::bind::ZERO_OFFSET_TOLD);
let told = bound.shape(crate::bind::ZERO_OFFSET_TOLD, BufferRanges::default());
let at = range_at_bind_offset(&b, Some(&told), limits);
let pb = plan_buffer((slot(0), &b, Some(&told)), false, limits, &bindings)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
+102 -20
View File
@@ -745,11 +745,11 @@ impl BindState {
/// The projection of this state that can change a plan: per stage, which slots are bound and
/// with what kind of resource, whether a buffer has a device address, its per-bind stride, its
/// length class and bind-offset alignment class (the largest power of two up to 4 that
/// divides the offset, or [`view_base_alignment`](Self::view_base_alignment) where that
/// divides it at a slot of [`StageTable::at_bind_views`]), texture types and formats, sampler
/// modes,
/// threadgroup lengths, the vertex amplification, the render target array length, whether a
/// length class as the table's [`StageTable::buffer_ranges`] tell it apart and bind-offset
/// alignment class (the largest power of two up to 4 that divides the offset, or
/// [`view_base_alignment`](Self::view_base_alignment) where that divides it at a slot of
/// [`StageTable::at_bind_views`]), texture types and formats, sampler modes, threadgroup
/// lengths, the vertex amplification, the render target array length, whether a
/// tessellation factor buffer is set, a tile dispatch's render area, the argument samplers'
/// capacity class and shapes ([`ArgumentSamplersShape::of`]), and the tile threadgroup memory
/// ([`TileThreadgroupMemory`]). Offsets, addresses, lengths, and resource ids are otherwise
@@ -939,8 +939,12 @@ impl BindState {
let mut key = FxHasher::default();
let alignment = self.view_base_alignment;
for (stage, t) in self.stages.iter().filter(|(_, t)| !t.has_empty_shape()) {
let buffers =
(t.buffers.iter()).map(|(i, b)| (*i, b.shape(t.class_alignment(*i, alignment))));
let buffers = (t.buffers.iter()).map(|(i, b)| {
(
*i,
b.shape(t.class_alignment(*i, alignment), t.buffer_ranges),
)
});
let textures = t.textures.iter().map(|(i, x)| (*i, x.shape()));
let samplers = t.samplers.iter().map(|(i, s)| (*i, s.shape()));
key_stage(&mut key, *stage, (buffers, textures, samplers));
@@ -1175,10 +1179,15 @@ impl ViewMapping {
impl StageTable {
/// The shape of this stage's tables ([`BindState::shape`]), the bind offsets of its buffers at
/// [`at_bind_views`](Self::at_bind_views) classed under the uniform views' base alignment
/// `view_base_alignment` ([`BindState::view_base_alignment`]).
/// `view_base_alignment` ([`BindState::view_base_alignment`]) and their lengths under its
/// [`buffer_ranges`](Self::buffer_ranges).
pub fn shape(&self, view_base_alignment: u32) -> StageShape {
let ranges = self.buffer_ranges;
let buffer = |(i, b): (&u32, &BoundBuffer)| {
(*i, b.shape(self.class_alignment(*i, view_base_alignment)))
(
*i,
b.shape(self.class_alignment(*i, view_base_alignment), ranges),
)
};
StageShape {
buffers: self.buffers.iter().map(buffer).collect(),
@@ -1205,8 +1214,13 @@ impl StageTable {
samplers,
threadgroup_lengths,
} = shape;
let buffer_shapes = (self.buffers.iter())
.map(|(i, b)| (*i, b.shape(self.class_alignment(*i, view_base_alignment))));
let ranges = self.buffer_ranges;
let buffer_shapes = (self.buffers.iter()).map(|(i, b)| {
(
*i,
b.shape(self.class_alignment(*i, view_base_alignment), ranges),
)
});
let texture_shapes = self.textures.iter().map(|(i, t)| (*i, t.shape()));
let sampler_shapes = self.samplers.iter().map(|(i, s)| (*i, s.shape()));
buffer_shapes.eq(buffers.iter().map(|(i, b)| (*i, *b)))
@@ -1233,8 +1247,9 @@ impl StageTable {
impl BoundBuffer {
/// The shape of this binding, its bind offset classed under the uniform views' base alignment
/// `view_base_alignment` (`BufferShape::Buffer`'s `offset_alignment`).
pub fn shape(&self, view_base_alignment: u32) -> BufferShape {
/// `view_base_alignment` (`BufferShape::Buffer`'s `offset_alignment`) and its length under the
/// buffer range limits `ranges` (its `length_class`, [`BufferRanges::length_class`]).
pub fn shape(&self, view_base_alignment: u32, ranges: BufferRanges) -> BufferShape {
match *self {
BoundBuffer::Buffer {
length,
@@ -1245,7 +1260,7 @@ impl BoundBuffer {
} => BufferShape::Buffer {
attribute_stride,
device_address: device_address.is_some(),
length_class: length_class(length),
length_class: ranges.length_class(length),
offset_alignment: offset_alignment(offset, view_base_alignment),
},
BoundBuffer::Bytes {
@@ -1254,9 +1269,15 @@ impl BoundBuffer {
}
}
/// Whether this binding and `other` have one shape under `view_base_alignment`, as their
/// [`shape`](Self::shape)s compare: a length or bind offset the two share is not classed.
pub fn same_shape(&self, other: &BoundBuffer, view_base_alignment: u32) -> bool {
/// Whether this binding and `other` have one shape under `view_base_alignment` and `ranges`,
/// as their [`shape`](Self::shape)s compare: a length or bind offset the two share is not
/// classed.
pub fn same_shape(
&self,
other: &BoundBuffer,
view_base_alignment: u32,
ranges: BufferRanges,
) -> bool {
match (*self, *other) {
(
BoundBuffer::Buffer {
@@ -1277,7 +1298,7 @@ impl BoundBuffer {
attribute_stride == other_stride
&& device_address.is_some() == other_address.is_some()
&& (length == other_length
|| length_class(length) == length_class(other_length))
|| ranges.length_class(length) == ranges.length_class(other_length))
&& (offset == other_offset
|| offset_alignment(offset, view_base_alignment)
== offset_alignment(other_offset, view_base_alignment))
@@ -1478,6 +1499,12 @@ pub struct StageTable {
/// keep one shape.
#[cfg_attr(feature = "serde", serde(default))]
pub zero_offset_views: u64,
/// The device's buffer range limits, which the runtime sets: its buffers' length classes are
/// told apart only as far as those limits tell them apart ([`BufferRanges::length_class`]),
/// all a plan reads of a buffer's length, so its buffers of lengths they do not tell apart
/// keep one shape. None (the default) tells every class apart.
#[cfg_attr(feature = "serde", serde(default))]
pub buffer_ranges: BufferRanges,
}
/// What the consumer knows of a Metal acceleration structure bound at a buffer slot.
@@ -1822,12 +1849,66 @@ pub enum ResourceClass {
/// The length class of an allocation of `length` bytes: the bit length of its padded length, so
/// `padded(length) < 2^class`. A plan compares `2^class - 1` with a descriptor range limit to know
/// that every range of the buffer fits it without the exact length, which is per-draw data.
/// that every range of the buffer fits it without the exact length, which is per-draw data. A
/// buffer's shape states it as its stage table's [`BufferRanges`] tell it apart.
pub fn length_class(length: u64) -> u8 {
let padded = u128::from(length).next_multiple_of(16);
(u128::BITS - padded.leading_zeros()) as u8
}
/// The range limits of a device's buffer views (`maxUniformBufferRange` and
/// `maxStorageBufferRange`, [`BufferRanges::of`]), the only values a plan compares a bound
/// buffer's [`length_class`] with (whether every range of the buffer fits each), which the runtime
/// sets on each stage table ([`StageTable::buffer_ranges`]). A buffer's shape tells apart only the
/// classes those comparisons tell apart ([`BufferRanges::length_class`]), so buffers of lengths
/// the device's limits do not tell apart bind one shape and take one plan, as a stream of
/// dispatches over buffers of many sizes binds them. The default, both 0, tells every class apart.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BufferRanges {
/// `maxUniformBufferRange`.
pub uniform: u32,
/// `maxStorageBufferRange`.
pub storage: u32,
}
impl BufferRanges {
/// The range limits of a device of `limits`.
pub fn of(limits: &Limits) -> BufferRanges {
BufferRanges {
uniform: limits.max_uniform_buffer_range,
storage: limits.max_storage_buffer_range,
}
}
/// The length class a buffer's shape states of an allocation of `length` bytes
/// ([`BufferShape::Buffer`]'s `length_class`): its [`length_class`] rounded up to the greatest
/// class whose every range fits the least of the two limits it fits, so a plan's comparison of
/// the class with either limit answers as the exact class's does; a class past both limits is
/// its own. Rounded up, the class still bounds the padded length (`padded(length) <
/// 2^class`), so under limits other than its device's no plan reads a range past a limit
/// either: it may take only the form a longer buffer takes.
pub fn length_class(&self, length: u64) -> u8 {
let class = length_class(length);
let (uniform, storage) = (widest_class(self.uniform), widest_class(self.storage));
let (least, most) = (uniform.min(storage), uniform.max(storage));
if class <= least {
least
} else if class <= most {
most
} else {
class
}
}
}
/// The greatest length class whose every range fits a limit of `limit` bytes:
/// `2^class - 1 <= limit`.
fn widest_class(limit: u32) -> u8 {
(u64::from(limit) + 1).ilog2() as u8
}
/// The projection of a [`BindState`] that can change a [`BindingPlan`](super::plan::BindingPlan):
/// which slots are bound and with what kind of resource, texture types and formats, sampler modes,
/// threadgroup lengths, inline bytes, per-bind strides, buffer length and bind-offset alignment
@@ -2330,7 +2411,8 @@ pub enum BufferShape {
/// vertex input can fetch with it decides the pulled-vertex-buffer variant.
attribute_stride: Option<u32>,
device_address: bool,
/// The length class of the allocation, as [`BindState::shape`] computes it.
/// The length class of the allocation as its stage table's buffer ranges tell it apart
/// ([`BufferRanges::length_class`]), as [`BindState::shape`] computes it.
length_class: u8,
/// The alignment class of the bind offset, as [`BindState::shape`] computes it: the
/// uniform views' base alignment ([`BindState::view_base_alignment`]) where the slot
+1 -1
View File
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523;
/// 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 = 2411;
pub const RUNTIME_VERSION: u32 = 2412;
/// 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
+37 -14
View File
@@ -5,8 +5,8 @@
use crate::bind::{
ArgumentFunctionTable, ArgumentSampler, BindState, BoundBuffer, BoundSampler, BoundTexture,
CompensatedViewport, FragmentTests, ImageblockSize, ResourceClass, SamplerDescriptor,
StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts,
BufferRanges, CompensatedViewport, FragmentTests, ImageblockSize, ResourceClass,
SamplerDescriptor, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts,
TileThreadgroupArgument, TileThreadgroupMemory, UsedResource, VertexAmplification,
};
use crate::metal::{
@@ -26,6 +26,11 @@ fn buffer(length: u64, offset: u64) -> BoundBuffer {
}
}
/// Buffer range limits of `uniform` and `storage` bytes.
fn ranges(uniform: u32, storage: u32) -> BufferRanges {
BufferRanges { uniform, storage }
}
/// A 2D texture of `format`.
fn texture(format: PixelFormat) -> BoundTexture {
BoundTexture::Texture {
@@ -115,6 +120,14 @@ fn states() -> Vec<BindState> {
with(|s| {
vertex(s).buffers.insert(0, buffer(256, 2));
}),
// Buffer range limits that tell the buffer's class apart, of the base's shape; limits of
// 4 GiB, which tell apart no class of either length, of one other shape twice.
with(|s| vertex(s).buffer_ranges = ranges(255, 255)),
with(|s| vertex(s).buffer_ranges = ranges(u32::MAX, u32::MAX)),
with(|s| {
vertex(s).buffer_ranges = ranges(u32::MAX, u32::MAX);
vertex(s).buffers.insert(0, buffer(1 << 20, 0));
}),
// A view base alignment no slot tells apart, or a slot that tells apart none, or one
// that tells it apart at an offset it does not divide, all of the base's shape; one that
// tells it apart where it divides the offset, of another.
@@ -273,11 +286,12 @@ fn a_state_has_exactly_the_shape_it_makes() {
);
}
}
// The states of the base's shape (the base, the four its comment names, the three of a view
// base alignment told apart nowhere it divides an offset, and the base with another argument
// sampler of the same shape) and the used resources' two of one shape: each against the
// The states of the base's shape (the base, the four its comment names, the one of buffer
// range limits that tell its class apart, the three of a view base alignment told apart
// nowhere it divides an offset, and the base with another argument sampler of the same
// shape), the two of 4 GiB limits and the used resources' two of one shape: each against the
// others of its shape.
assert_eq!(same, 9 * 8 + 2, "pairs of one shape");
assert_eq!(same, 10 * 9 + 2 + 2, "pairs of one shape");
}
/// A state's shape key is its shape's, and the key of every shape it has beside its used
@@ -462,10 +476,11 @@ fn a_state_listed_in_token_order_compares_its_used_resources_in_place() {
assert_eq!(same, 2 + 3 * 2, "pairs of one shape");
}
/// `BoundBuffer::same_shape` answers `a.shape(x) == b.shape(x)` for every pair of bindings over
/// lengths of one length class and of others, bind offsets of one alignment class and of others,
/// with and without a device address and a stride, and inline bytes, at view base alignments that
/// tell no offset class past the vertex fetch's apart and one that does.
/// `BoundBuffer::same_shape` answers `a.shape(x, r) == b.shape(x, r)` for every pair of bindings
/// over lengths of one length class and of others, bind offsets of one alignment class and of
/// others, with and without a device address and a stride, and inline bytes, at view base
/// alignments that tell no offset class past the vertex fetch's apart and one that does, under
/// buffer range limits that tell every length class apart, some, and few.
#[test]
fn a_buffer_binding_has_the_shape_of_another_exactly_where_their_shapes_compare_equal() {
let mut bindings = Vec::new();
@@ -484,6 +499,9 @@ fn a_buffer_binding_has_the_shape_of_another_exactly_where_their_shapes_compare_
}
}
}
for length in [1 << 16, (1 << 16) + 1, 1 << 27, 1 << 33] {
bindings.push(buffer(length, 0));
}
for len in [4, 8] {
for attribute_stride in [None, Some(4)] {
bindings.push(BoundBuffer::Bytes {
@@ -493,14 +511,19 @@ fn a_buffer_binding_has_the_shape_of_another_exactly_where_their_shapes_compare_
}
}
let (mut alike, mut apart) = (0, 0);
for alignment in [0, 4, 64] {
let limits = [
ranges(0, 0),
ranges(1 << 16, 1 << 27),
ranges(u32::MAX, u32::MAX),
];
for (alignment, r) in [0, 4, 64].into_iter().flat_map(|a| limits.map(|r| (a, r))) {
for (at, binding) in bindings.iter().enumerate() {
for (of, other) in bindings.iter().enumerate() {
let equal = binding.shape(alignment) == other.shape(alignment);
let equal = binding.shape(alignment, r) == other.shape(alignment, r);
assert_eq!(
binding.same_shape(other, alignment),
binding.same_shape(other, alignment, r),
equal,
"binding {at} against binding {of} at alignment {alignment}"
"binding {at} against binding {of} at alignment {alignment} under {r:?}"
);
alike += usize::from(equal && at != of);
apart += usize::from(!equal);
+8 -2
View File
@@ -3963,6 +3963,8 @@ field metal2vulkan::bind::BufferExtent.slot pub slot: SlotRef
field metal2vulkan::bind::BufferExtent.window pub window: Window
field metal2vulkan::bind::BufferRange.offset pub offset: u64
field metal2vulkan::bind::BufferRange.range pub range: u64
field metal2vulkan::bind::BufferRanges.storage pub storage: u32
field metal2vulkan::bind::BufferRanges.uniform pub uniform: u32
field metal2vulkan::bind::ByteRange.len pub len: u64
field metal2vulkan::bind::ByteRange.offset pub offset: u64
field metal2vulkan::bind::CheckDrawModules.fragment pub fragment: Arc<[u32]>
@@ -4373,6 +4375,7 @@ field metal2vulkan::bind::StageShape.textures pub textures: BTreeMap<u32, Textur
field metal2vulkan::bind::StageShape.threadgroup_lengths pub threadgroup_lengths: BTreeMap<u32, u32>
field metal2vulkan::bind::StageTable.acceleration_structures pub acceleration_structures: BTreeMap<u32, BoundAccelerationStructure>
field metal2vulkan::bind::StageTable.at_bind_views pub at_bind_views: u64
field metal2vulkan::bind::StageTable.buffer_ranges pub buffer_ranges: BufferRanges
field metal2vulkan::bind::StageTable.buffers pub buffers: BTreeMap<u32, BoundBuffer>
field metal2vulkan::bind::StageTable.samplers pub samplers: BTreeMap<u32, BoundSampler>
field metal2vulkan::bind::StageTable.textures pub textures: BTreeMap<u32, BoundTexture>
@@ -9491,11 +9494,13 @@ method metal2vulkan::bind::BindingPlan::specialized_value pub fn specialized_val
method metal2vulkan::bind::BindingPlan::unit_axes_variant pub fn unit_axes_variant(&self, dispatch: &Dispatch) -> Result<Option<VariantKey>, BindError>
method metal2vulkan::bind::BlockDecodeModule::shape pub fn shape([width, height, depth]: [u32; 3]) -> [u8; Self::SHAPE_WORDS as usize * 4]
method metal2vulkan::bind::BoundAccelerationStructure::new pub fn new(instance_count: u32) -> BoundAccelerationStructure
method metal2vulkan::bind::BoundBuffer::same_shape pub fn same_shape(&self, other: &BoundBuffer, view_base_alignment: u32) -> bool
method metal2vulkan::bind::BoundBuffer::shape pub fn shape(&self, view_base_alignment: u32) -> BufferShape
method metal2vulkan::bind::BoundBuffer::same_shape pub fn same_shape(&self, other: &BoundBuffer, view_base_alignment: u32, ranges: BufferRanges) -> bool
method metal2vulkan::bind::BoundBuffer::shape pub fn shape(&self, view_base_alignment: u32, ranges: BufferRanges) -> BufferShape
method metal2vulkan::bind::BoundSampler::new pub fn new(desc: SamplerDescriptor) -> BoundSampler
method metal2vulkan::bind::BoundSampler::shape pub fn shape(&self) -> BoundSamplerShape
method metal2vulkan::bind::BoundTexture::shape pub fn shape(&self) -> TextureShape
method metal2vulkan::bind::BufferRanges::length_class pub fn length_class(&self, length: u64) -> u8
method metal2vulkan::bind::BufferRanges::of pub fn of(limits: &Limits) -> BufferRanges
method metal2vulkan::bind::ChromaConvertModule::shape pub fn shape(size: [u32; 2], first: u32, row: u32) -> [u8; Self::SHAPE_WORDS as usize * 4]
method metal2vulkan::bind::ChromaDecode::block_extent pub fn block_extent(self) -> [u32; 2]
method metal2vulkan::bind::ChromaDecode::decode pub fn decode(self, pairs: &[u8], size: [u32; 3]) -> Vec<u8>
@@ -10657,6 +10662,7 @@ struct metal2vulkan::bind::BoundSamplerShape #[cfg_attr(feature = "serde", deriv
struct metal2vulkan::bind::BoundsRunDraw #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct BoundsRunDraw
struct metal2vulkan::bind::BufferExtent #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferExtent
struct metal2vulkan::bind::BufferRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferRange
struct metal2vulkan::bind::BufferRanges #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferRanges
struct metal2vulkan::bind::ByteRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ByteRange
struct metal2vulkan::bind::CheckDrawModules #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct CheckDrawModules
struct metal2vulkan::bind::ChromaConvertModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ChromaConvertModule
Can't render this file because it is too large.
+1
View File
@@ -548,6 +548,7 @@ surface! {
struct BoundSampler N;
struct BoundSamplerShape N;
enum BoundTexture N;
struct BufferRanges N;
enum BufferShape N;
enum HeapPlacement N;
enum ResourceClass N;
+8
View File
@@ -1487,6 +1487,14 @@ for dependency in &pipeline.dependencies {
bytes ran in 161.8 us a dispatch with the bytes' uniform view read at its bind offset, and in
142.8 us with it read at its residual. Elsewhere no storage view declares the key, and `zero_offset_views`
changes nothing.
- A bound buffer's length enters its shape only as a length class (`bind::length_class`), which a
plan compares with the device's `maxUniformBufferRange` and `maxStorageBufferRange` alone
(whether every range of the buffer fits each). Set each table's
`buffer_ranges = BufferRanges::of(limits)` and its shape tells apart only the classes those
limits tell apart (`BufferRanges::length_class`: a class rounded up to the greatest one that fits
the same limits), so commands over buffers of many sizes keep one shape and one plan: on a device
whose two limits are both 4 GiB, every buffer below 4 GiB. The default tells every class apart.
The runtime sets them on every table it reads.
- A two-plane YCbCr texture whose planes a function may read in place states them in its facts
(`TextureFacts::ycbcr_in_place`, a `YCbCrInPlace` of its planes; the runtime states one on a
device whose memory is the host's, `DeviceProfile::reads_ycbcr_planes_in_place`: an integrated