Drop a stage-in fetch's reach check where no element of the region can reach 2^32 bytes
A kernel's [[stage_in]] fetch places element e at e * stride + offset in 64 bits. Each fetch checks that the element's bytes end in the first 2^32 bytes from the bind offset, and reads zero where they do not. For a dynamic stride that check is a division and two compares per fetch; for a fixed one, a compare. Almost every dispatch's region keeps every element far inside those bytes, so the check is work that never changes an answer there. A new SpecKey::StageInReach (bool, default true) gates the check of each thread-position step. The binder sets it per dispatch region (dispatch::stage_in_reach) from the stage-in region, Metal's grid and each grid fetch's stride (fixed, or the bound one for a dynamic layout), rate and attribute end. The furthest element is the origin plus the smaller of the region's last element and the grid's last position over the rate. A region of size 0 on the axis clamps nothing, so the grid alone bounds it. The key is false only where that element's bytes end by 2^32. It stays true where nothing bounds the element (an indirect grid over a region of size 0) or the origin's add wraps. An indexed step's element is whatever its index buffer holds, so it keeps its check whatever the key says. So a dispatch that cannot reach takes a VkPipeline without the check, and only a dispatch that can reach takes the one that keeps it. The answer is the same either way, so this is not a FAST-PATHS row. The compute template keeps the kernel's grid fetches (stage_in_grid), and the StageInStride push and the key read the bound stride through one helper. SEMANTICS_VERSION 1986 (translation output changes: the key and its select) and ARTIFACT_FORMAT_VERSION 492 (a SpecKey variant appended to the codec), the numbers the orchestrator assigned. Tests: bind::dispatch's a_dispatch_reaches_where_an_element_may_end_past_four_gigabytes covers the key's decision: fixed and dynamic strides, MTLAttributeStrideStatic, the origin, the grid and the rate bounding a region, a region of size 0 under a direct and an indirect grid, the step's axis, a wrapping origin, and stride 0. engine_kernel_stage_in's run_reaching now asserts, for every dispatch it runs, that each region's key is 1 exactly where some element lies past 2^32 bytes. The past-four-gigabytes cases are the negative control: they still read zero, at key 1. (cherry picked from commit 3ad366af8f72397345a8542a7a8c899562856f73)
This commit is contained in:
1 parent
3a34b49814
commit
13c22c1502
11 files changed
+344
-37
No files matched your search
@@ -52,7 +52,10 @@
|
||||
//! `BindError::MissingStageInRegion`, since what Metal reads then is not established. A step at a
|
||||
//! rate above 1 adds the region's origin to the quotient, and an indexed step adds it to the index
|
||||
//! it looks up at the thread position, as an M4 and an M3 Max read (`lower::stage_io::stage_in`):
|
||||
//! the binder writes the region whatever its origin.
|
||||
//! the binder writes the region whatever its origin. Each region's `SpecKey::StageInReach` says
|
||||
//! whether an element of a thread-position step may lie past the first `2^32` bytes from its bind
|
||||
//! offset ([`stage_in_reach`]). It is false where none can, which drops the fetch's reach check,
|
||||
//! so only a dispatch that can reach takes the `VkPipeline` that keeps it.
|
||||
//!
|
||||
//! **Indirect.** When any axis of `maxComputeWorkGroupCount` is below `2^32 - 1`, an indirect
|
||||
//! dispatch carries an [`IndirectClamp`] prepass and its region reads the clamp's scratch
|
||||
@@ -792,22 +795,102 @@ impl BindingPlan {
|
||||
threads_per_group: [u32; 3],
|
||||
) -> Result<SpecializationKey, BindError> {
|
||||
let t = self.compute_template("replay_specialization")?;
|
||||
Ok(region_specialization(t, threads_per_group, true))
|
||||
// A replay variant reads no stage-in region (`check_replay`), so no key bounds a fetch.
|
||||
Ok(region_specialization(t, threads_per_group, true, true))
|
||||
}
|
||||
}
|
||||
|
||||
/// The specialization of a region of `local` threads of `t`: the template's fixed constants, the
|
||||
/// local size, and whether the region reads its record (`MultiRegion`).
|
||||
fn region_specialization(t: &ComputeTemplate, local: [u32; 3], multi: bool) -> SpecializationKey {
|
||||
/// local size, whether the region reads its record (`MultiRegion`), and whether a stage-in element
|
||||
/// it fetches may lie past the first `2^32` bytes from its bind offset (`StageInReach`,
|
||||
/// [`stage_in_reach`]).
|
||||
fn region_specialization(
|
||||
t: &ComputeTemplate,
|
||||
local: [u32; 3],
|
||||
multi: bool,
|
||||
reach: bool,
|
||||
) -> SpecializationKey {
|
||||
let n: u64 = local.iter().map(|&x| u64::from(x)).product();
|
||||
spec_key(&t.spec, |k| match k {
|
||||
SpecKey::LocalSize(a) => Some(u64::from(local[a as usize])),
|
||||
SpecKey::FlatLocalSize => Some(n),
|
||||
SpecKey::MultiRegion => Some(u64::from(multi)),
|
||||
SpecKey::StageInReach => Some(u64::from(reach)),
|
||||
other => t.fixed.iter().find(|(key, _)| *key == other).map(|f| f.1),
|
||||
})
|
||||
}
|
||||
|
||||
/// The stride the compute encoder binds kernel buffer `index` with in `state`
|
||||
/// (`setBuffer:offset:attributeStride:atIndex:` and its forms, `MTLAttributeStrideStatic`'s low
|
||||
/// 32 bits), 0 where it binds none: what a stage-in layout of `MTLBufferLayoutStrideDynamic`
|
||||
/// fetches at.
|
||||
fn stage_in_stride(state: &BindState, index: u32) -> u32 {
|
||||
match state
|
||||
.stages
|
||||
.get(&Stage::Kernel)
|
||||
.and_then(|k| k.buffers.get(&index))
|
||||
{
|
||||
Some(
|
||||
&BoundBuffer::Buffer {
|
||||
attribute_stride: Some(s),
|
||||
..
|
||||
}
|
||||
| &BoundBuffer::Bytes {
|
||||
attribute_stride: Some(s),
|
||||
..
|
||||
},
|
||||
) => s,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `SpecKey::StageInReach` of a dispatch of `t` over Metal's `grid` (0 on each axis for an
|
||||
/// indirect dispatch, whose grid only the GPU knows) in stage-in region `region`, under `state`'s
|
||||
/// strides. It says whether an element that a thread-position fetch reads may lie past the first
|
||||
/// `2^32` bytes from its bind offset, where the fetch's reach check reads it as zero
|
||||
/// (`lower::stage_io::fetch`). Each element is `origin + min(position / rate, size - 1)` on the
|
||||
/// step's axis, so it is at most the origin plus the smaller of the region's last element and the
|
||||
/// grid's last position over the rate. In a region of size 0 on the axis, whose size less 1 clamps
|
||||
/// nothing, it is bounded by the grid alone. Where that bound is unknown (an indirect grid over
|
||||
/// such a region) or the sum leaves 32 bits (the shader's add wraps), any element may be read.
|
||||
fn stage_in_reach(
|
||||
t: &ComputeTemplate,
|
||||
region: Option<StageInRegion>,
|
||||
grid: [u32; 3],
|
||||
state: &BindState,
|
||||
) -> bool {
|
||||
let Some(region) = region else {
|
||||
return !t.stage_in_grid.is_empty();
|
||||
};
|
||||
t.stage_in_grid.iter().any(|f| {
|
||||
let (Some(axis), Some(end)) = (
|
||||
crate::lower::stage_io::stage_in::grid_axis(f),
|
||||
crate::lower::stage_io::stage_in::element_end(f),
|
||||
) else {
|
||||
return true;
|
||||
};
|
||||
let stride = f
|
||||
.stride
|
||||
.unwrap_or_else(|| stage_in_stride(state, f.buffer_index));
|
||||
// At stride 0 every element is the attribute's own bytes at the bind offset.
|
||||
if stride == 0 {
|
||||
return end > 1 << 32;
|
||||
}
|
||||
let rate = f.step_rate.max(1);
|
||||
let positions = grid[axis].checked_sub(1).map(|p| p / rate);
|
||||
let last = match (region.size[axis].checked_sub(1), positions) {
|
||||
(None, None) => return true,
|
||||
(None, Some(p)) => p,
|
||||
(Some(z), None) => z,
|
||||
(Some(z), Some(p)) => z.min(p),
|
||||
};
|
||||
let Some(element) = region.origin[axis].checked_add(last) else {
|
||||
return true;
|
||||
};
|
||||
u64::from(element) * u64::from(stride) + end > 1 << 32
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `t` is a device-replay variant's template that `state` can instantiate: every buffer
|
||||
/// slot is one of the 32 kernel buffers a record binds, read through its root entry; no field a
|
||||
/// record cannot supply (a descriptor slot's residual, a slot's `SlotGuestBase`, the stage-in
|
||||
@@ -942,24 +1025,7 @@ fn instantiate(
|
||||
// bits, whose elements past the first the fetch reads past the bind offset's 2^32
|
||||
// bytes (`lower::stage_io::fetch`).
|
||||
PushField::StageInStride(index) => {
|
||||
let stride = match state
|
||||
.stages
|
||||
.get(&Stage::Kernel)
|
||||
.and_then(|k| k.buffers.get(&index))
|
||||
{
|
||||
Some(
|
||||
&BoundBuffer::Buffer {
|
||||
attribute_stride: Some(s),
|
||||
..
|
||||
}
|
||||
| &BoundBuffer::Bytes {
|
||||
attribute_stride: Some(s),
|
||||
..
|
||||
},
|
||||
) => s,
|
||||
_ => 0,
|
||||
};
|
||||
FieldBytes::of(&stride.to_le_bytes())
|
||||
FieldBytes::of(&stage_in_stride(state, index).to_le_bytes())
|
||||
}
|
||||
field => slot_field(field, &bound.residuals, &t.resources, state)
|
||||
.ok_or_else(|| internal(format!("a compute push field {field:?}")))?,
|
||||
@@ -979,6 +1045,7 @@ fn instantiate(
|
||||
nominal,
|
||||
..
|
||||
} = planned;
|
||||
let reach = stage_in_reach(t, region, grid, state);
|
||||
let mut regions = Vec::with_capacity(planned.len());
|
||||
for r in planned {
|
||||
let mut bytes = push.clone();
|
||||
@@ -987,7 +1054,7 @@ fn instantiate(
|
||||
.ok_or_else(|| internal("an unpackable nominal threadgroup size"))?;
|
||||
put(&mut bytes, push_start, &mut [], loc, &b)?;
|
||||
}
|
||||
let specialization = region_specialization(t, r.local, r.multi);
|
||||
let specialization = region_specialization(t, r.local, r.multi, reach);
|
||||
let indirect = match *dispatch {
|
||||
Dispatch::ThreadgroupsIndirect { .. } if replay => Some(IndirectArgs::Replay),
|
||||
Dispatch::ThreadgroupsIndirect { indirect, .. } => {
|
||||
|
||||
@@ -101,6 +101,7 @@ fn template() -> ComputeTemplate {
|
||||
storage_alignment: 64,
|
||||
resources: Default::default(),
|
||||
stage_in_region: false,
|
||||
stage_in_grid: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -931,3 +932,129 @@ fn a_flat_region_that_cannot_cover_the_grid_is_refused() {
|
||||
let planned = regions(&rules, &d, false).expect("the split");
|
||||
assert_eq!(planned.regions.len(), 5 * 3 * 2);
|
||||
}
|
||||
|
||||
/// A dispatch's `StageInReach` is false exactly where every element a thread-position fetch reads
|
||||
/// ends in the first `2^32` bytes from its bind offset: the element `origin + min(position / rate,
|
||||
/// size - 1)` at its furthest, at the layout's stride, plus the end of its attribute's bytes. It is
|
||||
/// true where nothing bounds the element (an indirect grid over a region of size 0) or the origin's
|
||||
/// add wraps.
|
||||
#[test]
|
||||
fn a_dispatch_reaches_where_an_element_may_end_past_four_gigabytes() {
|
||||
use crate::metal::{AttributeFormat, StepFunction};
|
||||
use crate::pipeline::stage_io::StageInFetch;
|
||||
// A `uint` at offset 4 of an element of buffer 1: an element's bytes end 8 past its start.
|
||||
let fetch = |stride, step_function, step_rate| StageInFetch {
|
||||
format: AttributeFormat::UInt,
|
||||
buffer_index: 1,
|
||||
offset: 4,
|
||||
stride,
|
||||
step_function,
|
||||
step_rate,
|
||||
index: None,
|
||||
};
|
||||
let (x, y) = (
|
||||
StepFunction::ThreadPositionInGridX,
|
||||
StepFunction::ThreadPositionInGridY,
|
||||
);
|
||||
let bound = |stride: Option<u32>| {
|
||||
let mut s = state(0);
|
||||
let kernel = s.stages.get_mut(&Stage::Kernel).expect("kernel");
|
||||
kernel.buffers.insert(
|
||||
1,
|
||||
BoundBuffer::Buffer {
|
||||
length: 4096,
|
||||
offset: 0,
|
||||
gpu_address: 0x2_0000,
|
||||
device_address: None,
|
||||
attribute_stride: stride,
|
||||
},
|
||||
);
|
||||
s
|
||||
};
|
||||
let unbound = bound(None);
|
||||
let along_x = |o: u32, z: u32| StageInRegion::new([o, 0, 0], [z, 1, 1]);
|
||||
let reach = |fetches: Vec<StageInFetch>, region, grid, state: &BindState| {
|
||||
let mut t = template();
|
||||
t.stage_in_region = true;
|
||||
t.stage_in_grid = fetches;
|
||||
stage_in_reach(&t, Some(region), grid, state)
|
||||
};
|
||||
let quarter = 1 << 30;
|
||||
// At a fixed 2^30, elements 0 to 3 end by 3 · 2^30 + 8, and element 4 at 2^32 + 8.
|
||||
let fixed = || vec![fetch(Some(quarter), x, 1)];
|
||||
assert!(!reach(fixed(), along_x(0, 4), [64, 1, 1], &unbound));
|
||||
assert!(reach(fixed(), along_x(0, 5), [64, 1, 1], &unbound));
|
||||
// The origin adds to every element.
|
||||
assert!(reach(fixed(), along_x(1, 4), [64, 1, 1], &unbound));
|
||||
// The grid's last position bounds a larger region, over the step's rate.
|
||||
assert!(!reach(fixed(), along_x(0, 64), [4, 1, 1], &unbound));
|
||||
let quartered = || vec![fetch(Some(quarter), x, 4)];
|
||||
assert!(!reach(quartered(), along_x(0, 64), [16, 1, 1], &unbound));
|
||||
assert!(reach(quartered(), along_x(0, 64), [17, 1, 1], &unbound));
|
||||
// A region of size 0 clamps nothing: the grid alone bounds it, and an indirect one, whose
|
||||
// grid only the GPU knows, nothing; a region of a size bounds an indirect grid.
|
||||
assert!(!reach(fixed(), along_x(0, 0), [4, 1, 1], &unbound));
|
||||
assert!(reach(fixed(), along_x(0, 0), [0; 3], &unbound));
|
||||
assert!(!reach(fixed(), along_x(0, 4), [0; 3], &unbound));
|
||||
// The step's axis: a region of 4 along y, of 64 along x.
|
||||
let rows = StageInRegion::new([0; 3], [64, 4, 1]);
|
||||
assert!(!reach(
|
||||
vec![fetch(Some(quarter), y, 1)],
|
||||
rows,
|
||||
[64, 64, 1],
|
||||
&unbound
|
||||
));
|
||||
assert!(reach(
|
||||
vec![fetch(Some(quarter), x, 1)],
|
||||
rows,
|
||||
[64, 64, 1],
|
||||
&unbound
|
||||
));
|
||||
// An origin whose add wraps reaches any element.
|
||||
assert!(reach(
|
||||
vec![fetch(Some(4), x, 1)],
|
||||
along_x(u32::MAX, 2),
|
||||
[64, 1, 1],
|
||||
&unbound
|
||||
));
|
||||
// At stride 0 every element is the first one's bytes.
|
||||
assert!(!reach(
|
||||
vec![fetch(Some(0), x, 1)],
|
||||
along_x(u32::MAX, 2),
|
||||
[64, 1, 1],
|
||||
&unbound
|
||||
));
|
||||
// A dynamic layout reads the bound stride, 0 where none is bound; `MTLAttributeStrideStatic`
|
||||
// is its low 32 bits, past which only the first element is held.
|
||||
let dynamic = || vec![fetch(None, x, 1)];
|
||||
assert!(!reach(dynamic(), along_x(0, 64), [64, 1, 1], &unbound));
|
||||
assert!(!reach(
|
||||
dynamic(),
|
||||
along_x(0, 1),
|
||||
[64, 1, 1],
|
||||
&bound(Some(u32::MAX))
|
||||
));
|
||||
assert!(reach(
|
||||
dynamic(),
|
||||
along_x(0, 2),
|
||||
[64, 1, 1],
|
||||
&bound(Some(u32::MAX))
|
||||
));
|
||||
assert!(!reach(
|
||||
dynamic(),
|
||||
along_x(0, 2),
|
||||
[64, 1, 1],
|
||||
&bound(Some((1 << 31) + 4))
|
||||
));
|
||||
assert!(reach(
|
||||
dynamic(),
|
||||
along_x(0, 3),
|
||||
[64, 1, 1],
|
||||
&bound(Some((1 << 31) + 4))
|
||||
));
|
||||
// Any fetch that may reach makes the region's key true.
|
||||
let both = vec![fetch(Some(4), x, 1), fetch(Some(quarter), x, 1)];
|
||||
assert!(reach(both, along_x(0, 5), [64, 1, 1], &unbound));
|
||||
// A kernel without a thread-position fetch reaches nothing.
|
||||
assert!(!reach(Vec::new(), along_x(0, 64), [64, 1, 1], &unbound));
|
||||
}
|
||||
@@ -153,6 +153,11 @@ pub struct ComputeTemplate {
|
||||
/// without a region is `BindError::MissingStageInRegion`.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub(crate) stage_in_region: bool,
|
||||
/// The kernel's `[[stage_in]]` fetches of a thread-position step, whose elements decide each
|
||||
/// region's `SpecKey::StageInReach` (`dispatch::stage_in_reach`); empty where the kernel
|
||||
/// declares no such key.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub(crate) stage_in_grid: Vec<crate::pipeline::stage_io::StageInFetch>,
|
||||
}
|
||||
|
||||
/// The pipeline and device facts a render plan instantiates with: the buffer slots of both stages,
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! `maxComputeSharedMemorySize`. With emulated simdgroups the static part is the arena's own
|
||||
//! (`RuntimeFact::SimdgroupEmulation`), and every region also fits the scratch of its simdgroups
|
||||
//! beside the declared arena. A predicated walk's vote word (`RuntimeFact::PredicationVote`) is
|
||||
//! counted beside the arena too. Local size and `MultiRegion` are per region.
|
||||
//! counted beside the arena too. Local size, `MultiRegion` and `StageInReach` are per region.
|
||||
//! - **Variant.** The shape's storage-image choices and device-address slots, and the emulated
|
||||
//! simdgroups of a pipeline compiled for them (`RuntimeFact::EmulatedSimdgroups`); a dispatch
|
||||
//! adds those where its threadgroups need them (`BindingPlan::dispatch_variant`). The flat grid
|
||||
@@ -51,7 +51,8 @@
|
||||
//! - **Stage-in strides**. A layout of a fixed stride reads its own, whatever stride the shape
|
||||
//! binds its buffer with; one of `MTLBufferLayoutStrideDynamic` (`RuntimeFact::StageInStride`)
|
||||
//! reads the bound one, which instantiation pushes (`PushField::StageInStride`, 0 for a buffer
|
||||
//! bound without one).
|
||||
//! bound without one). The template keeps each fetch of a thread-position step, from whose
|
||||
//! elements each region decides `SpecKey::StageInReach`.
|
||||
//! - **Push fields.** Every placed field is one the binder fills: the root-table and status
|
||||
//! addresses (holes the consumer fills), `DispatchRegion` (always written), `StageInRegion` (the
|
||||
//! dispatch's `BindState::stage_in_region`), `StageInStride` (the bound buffer's attribute
|
||||
@@ -683,7 +684,11 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
continue;
|
||||
}
|
||||
let v = match c.key {
|
||||
SpecKey::LocalSize(_) | SpecKey::FlatLocalSize | SpecKey::MultiRegion => continue,
|
||||
// Each region decides these (`dispatch::region_specialization`).
|
||||
SpecKey::LocalSize(_)
|
||||
| SpecKey::FlatLocalSize
|
||||
| SpecKey::MultiRegion
|
||||
| SpecKey::StageInReach => continue,
|
||||
SpecKey::TgLength(n) => {
|
||||
let len = u64::from(ks.threadgroup_lengths.get(&n).copied().unwrap_or(0));
|
||||
let len = len.next_multiple_of(TG_ALIGN);
|
||||
@@ -881,6 +886,13 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
.dependencies
|
||||
.iter()
|
||||
.any(|d| d.fact == RuntimeFact::StageInRegion),
|
||||
stage_in_grid: match layout.iter().any(|c| c.key == SpecKey::StageInReach) {
|
||||
true => (p.interface.io.stage_in.iter())
|
||||
.map(|s| s.fetch)
|
||||
.filter(|f| crate::lower::stage_io::stage_in::grid_axis(f).is_some())
|
||||
.collect(),
|
||||
false => Vec::new(),
|
||||
},
|
||||
}),
|
||||
views: Default::default(),
|
||||
})
|
||||
|
||||
+1
-1
@@ -865,7 +865,7 @@ codec_enum! {
|
||||
ConstantLanes(f0), UnmeasuredTexels(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0),
|
||||
SamplerAnisotropy(f0), RangeAtBindOffset(f0), PlainHalfTexels(f0),
|
||||
NearestPixelSampler(f0), BoundSamplerWord(f0), HeapYCbCrTextures(f0),
|
||||
FilteringArgumentSampler,
|
||||
FilteringArgumentSampler, StageInReach,
|
||||
}
|
||||
PushField {
|
||||
RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance,
|
||||
|
||||
Vendored
+2
-2
@@ -60,7 +60,7 @@ mod tests;
|
||||
/// unchanged version, and its bless records the version. Independent of the crate's version and of
|
||||
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
|
||||
/// history.
|
||||
pub const SEMANTICS_VERSION: u32 = 1987;
|
||||
pub const SEMANTICS_VERSION: u32 = 1989;
|
||||
|
||||
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
|
||||
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
|
||||
@@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1987;
|
||||
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
|
||||
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
|
||||
/// bumps it says what changed; this comment keeps no history.
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 491;
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 492;
|
||||
|
||||
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
|
||||
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
|
||||
|
||||
@@ -69,10 +69,11 @@
|
||||
//! from `PushField::StageInStride(buffer_index)`, where `element` is the step's ([`Step::Grid`],
|
||||
//! [`Step::Indexed`], [`Step::Constant`]; `super::stage_in` plans them), with the same reach as a
|
||||
//! vertex attribute's: the runtime refuses a dispatch that may fetch past `2^32` bytes from a
|
||||
//! buffer that holds those bytes. A dynamic layout bound with `MTLAttributeStrideStatic`, a vertex
|
||||
//! layout's or a kernel's, reads at its low 32 bits, `2^32 - 1`, so its first element is the one
|
||||
//! at the bind offset and every element past it reads zero, as plain Metal on an M3 Max answers
|
||||
//! both.
|
||||
//! buffer that holds those bytes. A thread-position step's reach check is dropped where the binder
|
||||
//! finds that no element of the dispatch region reaches past them (`SpecKey::StageInReach`). A
|
||||
//! dynamic layout bound with `MTLAttributeStrideStatic`, a vertex layout's or a kernel's, reads at
|
||||
//! its low 32 bits, `2^32 - 1`, so its first element is the one at the bind offset and every
|
||||
//! element past it reads zero, as plain Metal on an M3 Max answers both.
|
||||
//!
|
||||
//! **Source buffers**. This family records which Metal buffer indices the fetch reads
|
||||
//! ([`super::StageIoPlan::buffers`]); their slots are the access family's (`lower::access::pulled`,
|
||||
@@ -444,7 +445,9 @@ impl PulledRead {
|
||||
// to the stage-in region, reads its index the way it reads the attribute, and adds the
|
||||
// region's origin. Every step with an element checks its reach.
|
||||
let element = match self.step {
|
||||
Step::Grid { .. } => GRID_POSITION_WORDS + REGION_AXIS_WORDS + REACH_WORDS + 16,
|
||||
Step::Grid { .. } => {
|
||||
GRID_POSITION_WORDS + REGION_AXIS_WORDS + REACH_WORDS + REACH_KEY_WORDS + 16
|
||||
}
|
||||
Step::Indexed { index, .. } => {
|
||||
GRID_POSITION_WORDS + REGION_AXIS_WORDS + REACH_WORDS + index.leaf().cost() + 176
|
||||
}
|
||||
@@ -466,6 +469,10 @@ const GRID_POSITION_WORDS: u32 = 400;
|
||||
/// selects, and their constants.
|
||||
const REACH_WORDS: u32 = 96;
|
||||
|
||||
/// An upper bound of the words of a thread-position step's `SpecKey::StageInReach` over its
|
||||
/// reach (`stage_in::reach_key`): the constant, its decoration, `true`, and the select.
|
||||
const REACH_KEY_WORDS: u32 = 24;
|
||||
|
||||
/// An upper bound of the words of a step's clamp to the stage-in region (`region_axis`): the
|
||||
/// region's push-field read, its origin and size, the size less 1, the `UMin`, and the origin's
|
||||
/// add, with their constants.
|
||||
@@ -1015,6 +1022,21 @@ pub(super) fn emit(
|
||||
Some((e, s)) => within_reach(fb, e, s, r.stride, r.offset, n)?,
|
||||
None => None,
|
||||
};
|
||||
// A thread-position step's check holds wherever the binder finds no element of the region
|
||||
// reaching (`SpecKey::StageInReach` false); an indexed step's element bounds nothing.
|
||||
let fits = match (r.step, fits) {
|
||||
(Step::Grid { .. }, Some(fits)) => {
|
||||
let reach = super::stage_in::reach_key(fb)?;
|
||||
let ty = fb.module().ty(Type::Bool)?;
|
||||
let c = fb.module().constant(Constant::Scalar {
|
||||
ty,
|
||||
bits: ConstBits(1),
|
||||
})?;
|
||||
let all = fb.module().const_value(c)?;
|
||||
Some(fb.select(reach, fits, all)?)
|
||||
}
|
||||
(_, fits) => fits,
|
||||
};
|
||||
let m = displacement(fb, element, r.offset)?;
|
||||
let read = match fits {
|
||||
Some(fits) => pulled::prepare_within(cx, fb, r.buffer, m, fits, n, r.check)?,
|
||||
|
||||
@@ -165,7 +165,7 @@ pub(crate) mod color_write;
|
||||
pub(crate) mod extended_color;
|
||||
pub mod fetch;
|
||||
mod plan;
|
||||
mod stage_in;
|
||||
pub(crate) mod stage_in;
|
||||
pub(crate) mod word_color;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -31,6 +31,13 @@
|
||||
//! (`fetch::within_reach`), which is what `MTLAttributeStrideStatic`'s `2^32 - 1` gives every
|
||||
//! element past the first.
|
||||
//!
|
||||
//! **The reach check** of a thread-position step reads `SpecKey::StageInReach` ([`reach_key`]).
|
||||
//! Where the binder finds that no element of the dispatch region lies past those bytes, at the
|
||||
//! layout's stride and its attributes' ends ([`element_end`]), it sets the key to false. The check
|
||||
//! then holds for every element and is dropped, so a dispatch that cannot reach takes the
|
||||
//! `VkPipeline` without it, and only one that can reach takes a second. An indexed step's element
|
||||
//! is whatever its index buffer holds, so it runs its check whatever the key says.
|
||||
//!
|
||||
//! **Formats** decode as a vertex format of the same raw value (`MTLAttributeFormat` and
|
||||
//! `MTLVertexFormat` list the same formats), and they meet the attribute's numeric class exactly
|
||||
//! as a pulled vertex attribute's do (`fetch::class_match`, `fetch::decode`): an unnormalized 8- or
|
||||
@@ -47,15 +54,45 @@ use crate::memory::contain;
|
||||
use crate::metal::{AttributeFormat, IndexType, StepFunction, VertexFormat};
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::stage_io::{StageInFetch, StageInInput};
|
||||
use crate::pipeline::sym::{PushField, Stage};
|
||||
use crate::pipeline::sym::{PushField, SpecKey, Stage};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::Value as SValue;
|
||||
use crate::spirv::ir::{ConstBits, Type};
|
||||
|
||||
use super::fetch::{self, IndexRead, PulledRead, Step, Stride};
|
||||
use super::plan::{io_form, io_type, param_ty};
|
||||
use super::{not_lowered, PlannedParam, Source};
|
||||
|
||||
/// The axis (0 for x, 1 for y) of fetch `f`'s thread-position step; `None` for any other step.
|
||||
/// These are the steps whose element the region clamps, and which `SpecKey::StageInReach` bounds.
|
||||
pub(crate) fn grid_axis(f: &StageInFetch) -> Option<usize> {
|
||||
match f.step_function {
|
||||
StepFunction::ThreadPositionInGridX => Some(0),
|
||||
StepFunction::ThreadPositionInGridY => Some(1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of fetch `f`'s attribute bytes in an element: its offset plus its format's store
|
||||
/// size. An element `e` at stride `s` lies in the first `2^32` bytes from the bind offset exactly
|
||||
/// where `e · s` plus this end is at most `2^32` (`fetch::within_reach`). `None` for a format no
|
||||
/// fetch decodes.
|
||||
pub(crate) fn element_end(f: &StageInFetch) -> Option<u64> {
|
||||
let format = VertexFormat::try_from(f.format.as_raw()).ok()?;
|
||||
let bytes = fetch::encoding(format).ok()?.bytes();
|
||||
Some(u64::from(f.offset) + u64::from(bytes))
|
||||
}
|
||||
|
||||
/// The `SpecKey::StageInReach` of the kernel's thread-position fetches: a `bool`, true by
|
||||
/// default, false where the binder finds that no element of the region lies past the first
|
||||
/// `2^32` bytes from its bind offset, so the fetch's reach check holds everywhere and is dropped.
|
||||
pub(super) fn reach_key(fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
|
||||
let ty = fb.module().ty(Type::Bool)?;
|
||||
let c = fb.module().spec(SpecKey::StageInReach, ty, ConstBits(1))?;
|
||||
fb.module().const_value(c)
|
||||
}
|
||||
|
||||
/// Record that the kernel reads the stage-in region, which the binder writes into
|
||||
/// `PushField::StageInRegion`.
|
||||
fn read_region(cx: &mut SelectCx<'_>) {
|
||||
|
||||
@@ -850,6 +850,17 @@ pub enum SpecKey {
|
||||
/// reads. Read by a specialized note's test alone, given by a plan, as
|
||||
/// [`HeapYCbCrTextures`](Self::HeapYCbCrTextures) is.
|
||||
FilteringArgumentSampler,
|
||||
/// Boolean: an element that a kernel's `[[stage_in]]` fetch of a thread-position step reads
|
||||
/// in this dispatch region may lie past the first `2^32` bytes from its bind offset (default
|
||||
/// true). Each such element is the region's origin plus the thread's position over the step
|
||||
/// rate, clamped to the region's last element. Where an element lies there, the fetch's reach
|
||||
/// check reads it as zero (`lower::stage_io::fetch`). The binder sets the key to false only
|
||||
/// where every element of the region (or of the grid, in a region of size 0 on the axis)
|
||||
/// fits, at the layout's stride and the end of its attributes' bytes. A false key drops the
|
||||
/// check; it answers the same everywhere it holds. An indexed step's element is whatever its
|
||||
/// index buffer holds, which bounds nothing, so an indexed step runs its check whatever the
|
||||
/// key says.
|
||||
StageInReach,
|
||||
}
|
||||
|
||||
impl SpecKey {
|
||||
|
||||
@@ -1104,6 +1104,24 @@ fn run_strided(bc: &[u8], d: &StageInputDescriptor, strides: &[(u32, u32)], s1:
|
||||
);
|
||||
}
|
||||
|
||||
/// The `SpecKey::StageInReach` each region of `cmds` takes, which `pipe`'s kernel declares.
|
||||
fn reach_values(pipe: &ComputePipeline, cmds: &DispatchCommands) -> Vec<u64> {
|
||||
let id = (pipe.stage.specialization.constants.iter())
|
||||
.find(|c| c.key == SpecKey::StageInReach)
|
||||
.map(|c| c.id)
|
||||
.expect("a thread-position fetch declares StageInReach");
|
||||
(cmds.regions.iter())
|
||||
.map(|r| {
|
||||
let key = &r.specialization;
|
||||
let e = (key.entries.iter())
|
||||
.find(|e| e.constant_id == id)
|
||||
.expect("each region sets StageInReach");
|
||||
let bytes = &key.data[e.offset as usize..][..e.size as usize];
|
||||
bytes.iter().rev().fold(0, |v, &b| v << 8 | u64::from(b))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// [`run_strided`] where `at1(x)` and `at2(y)` name the byte each thread reads layout 1 and
|
||||
/// layout 2 at, `None` where its element lies past the first `2^32` bytes and reads zero.
|
||||
fn run_reaching(
|
||||
@@ -1123,8 +1141,16 @@ fn run_reaching(
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let mut world = World::new(fetch_buffers(), StageInRegion::new([0; 3], [W, H, 1]))
|
||||
.with_strides(strides.iter().copied());
|
||||
execute(&dev, &pipe, &m, &mut world, &threads(W, H))
|
||||
let cmds = execute(&dev, &pipe, &m, &mut world, &threads(W, H))
|
||||
.unwrap_or_else(|e| panic!("{what} {strides:?}: {e}"));
|
||||
// Each region keeps the reach check (`StageInReach` 1) exactly where an element lies past
|
||||
// the first `2^32` bytes, and drops it everywhere else.
|
||||
let reaches = (0..W).any(|gx| at1(gx).is_none()) || (0..H).any(|gy| at2(gy).is_none());
|
||||
assert_eq!(
|
||||
reach_values(&pipe, &cmds),
|
||||
vec![u64::from(reaches); cmds.regions.len()],
|
||||
"{what} {strides:?}"
|
||||
);
|
||||
let out = words(&world.buffers[&0].bytes);
|
||||
for gy in 0..H {
|
||||
for gx in 0..W {
|
||||
|
||||
Reference in new issue
Block a user