Let the device say whether a binding of several variables may be dynamic

The steps this packet landed as, in order:
- Re-pin the runtime sources at the landing tip

Content: the tree of `development` at 20c998aa93, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:22 +02:00
1 parent f92fcd5893
commit 20b73503c0
10 files changed
+589 -11

No files matched your search

@@ -366,6 +366,12 @@ pub(super) struct DeviceShared {
/// commit is the only way a command of the program's reaches the device, so this one count
/// stands for every route its GPU work could write a texture by.
gpu_work: AtomicU64,
/// Whether the device takes a set-0 buffer binding whose entry point uses it through more
/// than one variable as a **dynamic** descriptor, asked of the device the first time a
/// variant has such a binding and kept for its lifetime
/// (`pipeline::objects::takes_multi_variable_dynamic`). `None` until then, and on a device no
/// variant has asked.
pub(super) dynamic_multi_variable: OnceLock<bool>,
/// The crate-owned compute kernels the runtime dispatches for itself, made on first use
/// (`owned_kernel.rs`).
pub(super) owned_kernels: Mutex<OwnedKernels>,
@@ -1750,6 +1756,7 @@ impl Device {
mutable_rate_map_called: AtomicBool::new(false),
sparse_image_made: AtomicBool::new(false),
gpu_work: AtomicU64::new(0),
dynamic_multi_variable: OnceLock::new(),
owned_kernels: Mutex::new(OwnedKernels::default()),
mipmap_scratch: Mutex::default(),
planes: Mutex::new(PlanesObjects::default()),
@@ -32,7 +32,7 @@ use crate::release;
use crate::shader_cache::driver::Making;
use crate::Device;
use ash::vk;
use metal2vulkan::bind::DispatchRegion;
use metal2vulkan::bind::{DispatchRegion, DynamicViewsModule};
use metal2vulkan::cache::{Hash256, SpecializationKey};
use metal2vulkan::error::{Feature, RuntimeDriverDefect, Unsupported};
use metal2vulkan::pipeline::{
@@ -1274,26 +1274,45 @@ fn needs_of(
/// (`DescriptorBinding::variables`) and no stage the pipeline adds reads (a tessellation control
/// or geometry stage, whose variables the layout does not count), in binding order while the
/// device's `maxDescriptorSetUniformBuffersDynamic` and `maxDescriptorSetStorageBuffersDynamic`
/// take them; every other binding stays of its own type. A binding of several variables stays
/// static: MoltenVK 1.4.1's SPIRV-Cross writes Metal that does not compile for a dynamic buffer an
/// entry point uses through more than one (it declares one variable's local alone).
/// take them; every other binding stays of its own type.
///
/// A binding each stage using it uses through **several** variables (a slot or store sink reached
/// through its word view and its narrow or `uvec4` unit views) stays static where the device does
/// not take such a binding dynamically, which the device answers itself
/// ([`takes_multi_variable_dynamic`]): it is one driver's shader-translation defect, not a limit
/// of Vulkan, which bounds the variables at a binding nowhere.
fn dynamic_bindings(device: &Device, layout: &PipelineLayout, push_set_zero: bool) -> Vec<u32> {
let Some(set) = layout.sets.first().filter(|_| !push_set_zero) else {
return Vec::new();
};
// Asked of the device only where a binding needs the answer, so a layout of one variable a
// binding -- every layout but the few with a narrow-unit store sink or a slot read through
// several types -- compiles nothing.
let several =
set.bindings.iter().any(|b| b.variables > 1) && takes_multi_variable_dynamic(device);
dynamic_numbers(set, device.shared().dynamic_buffers, several)
}
/// [`dynamic_bindings`]' choice over `set`, with `[uniform, storage]` dynamic buffers left of the
/// device's limits and `several` whether a binding of more than one variable may be dynamic.
fn dynamic_numbers(
set: &DescriptorSetLayout,
[mut uniform, mut storage]: [u32; 2],
several: bool,
) -> Vec<u32> {
let added = vk::ShaderStageFlags::TESSELLATION_CONTROL
| vk::ShaderStageFlags::TESSELLATION_EVALUATION
| vk::ShaderStageFlags::GEOMETRY;
let [mut uniform, mut storage] = device.shared().dynamic_buffers;
let mut dynamic = Vec::new();
for binding in &set.bindings {
let stages: vk::ShaderStageFlags = binding.stages.into();
let flags: vk::DescriptorBindingFlags = binding.flags.into();
if binding.count != 1
|| binding.variables != 1
|| stages.intersects(added)
|| !flags.is_empty()
{
let variables = match binding.variables {
0 => false,
1 => true,
_ => several,
};
if binding.count != 1 || !variables || stages.intersects(added) || !flags.is_empty() {
continue;
}
let left = match binding.ty.into() {
@@ -1309,6 +1328,106 @@ fn dynamic_bindings(device: &Device, layout: &PipelineLayout, push_set_zero: boo
dynamic
}
/// Whether `device` takes a set-0 buffer binding whose entry point uses it through more than one
/// variable as a dynamic descriptor: the device's own answer, asked once and kept
/// (`DeviceShared::dynamic_multi_variable`).
///
/// Vulkan bounds the variables at a binding nowhere, dynamic or not, so this asks about the
/// driver: MoltenVK's SPIRV-Cross writes Metal that does not compile for such a binding (it
/// declares one variable's local alone). Read in 1.4.1's source, and measured on **1.4.2**
/// (Homebrew's, `driverVersion` 10402) on an Apple M3 Max, where `vkCreateComputePipelines`
/// answers `VK_ERROR_INITIALIZATION_FAILED` for a kernel of three and of four variables at one
/// dynamic binding. A driver without the defect must not pay for it -- a descriptor set of its
/// own per command -- so the device answers for itself rather than being named.
///
/// It answers by creating one compute pipeline of exactly that shape, the crate-owned self-check
/// module with one variable per unit view the device's storage views can declare, so any plan's
/// binding is a subset of it (`bind::DynamicViewsModule`), and destroying it. A creation that
/// fails, for any reason, answers no, which is what every device answered before it was asked.
///
/// The check proves the driver **compiles** the shape. A driver that compiled it and then applied
/// the dynamic offset to one of its variables alone would still be wrong, and none is measured to
/// (`docs/FAST-PATHS.md`).
fn takes_multi_variable_dynamic(device: &Device) -> bool {
if let Some(&answered) = device.shared().dynamic_multi_variable.get() {
return answered;
}
// A host step makes no object of its own and must not compile here (`exit_guard`): its
// variant takes the static form every device took before, and the answer stays unasked for a
// later variant outside a step.
if exit_guard::in_host_step() {
return false;
}
*device
.shared()
.dynamic_multi_variable
.get_or_init(|| multi_variable_dynamic_creates(device).unwrap_or(false))
}
/// Create the self-check pipeline of [`takes_multi_variable_dynamic`] and destroy it: whether the
/// device made it.
fn multi_variable_dynamic_creates(device: &Device) -> Result<bool, Error> {
let module = metal2vulkan::bind::dynamic_views_module(device.compile_device())
.map_err(Error::Compile)?;
let shared = device.shared();
let raw = shared.vk();
let mut shader = vk::ShaderModule::null();
let mut set_layout = vk::DescriptorSetLayout::null();
let mut layout = vk::PipelineLayout::null();
let mut pipeline = vk::Pipeline::null();
let made = (|| {
let info = vk::ShaderModuleCreateInfo::default().code(&module.spirv);
// SAFETY: the code is live SPIR-V words for the call.
shader = unsafe { raw.create_shader_module(&info, None) }.map_err(vulkan)?;
let bindings = [vk::DescriptorSetLayoutBinding::default()
.binding(DynamicViewsModule::BINDING)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER_DYNAMIC)
.descriptor_count(1)
.stage_flags(vk::ShaderStageFlags::COMPUTE)];
let info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings);
// SAFETY: `info` and its array are live for the call.
set_layout = unsafe { raw.create_descriptor_set_layout(&info, None) }.map_err(vulkan)?;
let set_layouts = [set_layout];
let info = vk::PipelineLayoutCreateInfo::default().set_layouts(&set_layouts);
// SAFETY: as above.
layout = unsafe { raw.create_pipeline_layout(&info, None) }.map_err(vulkan)?;
let stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::COMPUTE)
.module(shader)
.name(c"main");
let info = vk::ComputePipelineCreateInfo::default()
.stage(stage)
.layout(layout);
// SAFETY: every pointer in `info` outlives the call; no pipeline cache, since the
// self-check's pipeline is never made again.
let created =
unsafe { raw.create_compute_pipelines(vk::PipelineCache::null(), &[info], None) };
match created {
Ok(made) => {
pipeline = made.first().copied().unwrap_or(vk::Pipeline::null());
Ok(true)
}
Err(_) => Ok(false),
}
})();
// SAFETY: nothing uses the objects: no command recorded them, and the pipeline, where it was
// made, was never bound.
unsafe {
release::object(raw, pipeline);
release::object(raw, layout);
release::object(raw, set_layout);
release::object(raw, shader);
}
made
}
/// The device's answer of [`takes_multi_variable_dynamic`], for the check that the restriction is
/// the device's and not every device's (`tests::dynamic_multi_variable`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn asks_multi_variable_dynamic(device: &Device) -> bool {
takes_multi_variable_dynamic(device)
}
/// The descriptor types a pushed set 0 takes: those a set-0 write (`binding::Info`) carries, but
/// the dynamic buffers, inline uniform blocks and mutable descriptors a push descriptor set layout
/// cannot hold (`VkDescriptorSetLayoutCreateInfo`'s valid usage).
@@ -0,0 +1,247 @@
//! A set-0 buffer binding an entry point uses through more than one variable: whether the device
//! takes it as a dynamic descriptor, and that its answer agrees with what its pipelines do.
//!
//! A slot or store sink declares one variable per view at its binding -- a word view, and the
//! narrow or `uvec4` unit views an access needs -- so a kernel whose dropped stores move a narrow
//! leaf has a binding of several variables (`pipeline::objects::dynamic_bindings`). Vulkan bounds
//! the variables at a binding nowhere, but MoltenVK's SPIRV-Cross writes Metal that does not
//! compile for a **dynamic** one, so the device is asked (one pipeline of that shape created and
//! destroyed, `objects::takes_multi_variable_dynamic`) rather than every device paying for it.
//!
//! What each test holds, on any device:
//!
//! - the pipelines of such a kernel are made and run, whatever the device answered, and
//! `record_stride_not_a_multiple_of_four` answers exactly what Metal's `sizeof` and its two
//! narrow stores say;
//! - and the binding type follows the answer: where the device takes it and the variant does not
//! push set 0, every dispatch after the first binds its predecessor's set, and where it does
//! not, each allocates and writes its own.
//!
//! On an Apple M3 Max under MoltenVK 1.4.2 the answer is no, so these hold the second branch
//! there; a driver that takes it holds the first.
//!
//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`).
use crate::{
Device, DeviceKind, DeviceOptions, PipelineOptions, ResourceOptions, ShaderCacheOptions, Size,
};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use std::path::{Path, PathBuf};
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Scratch {
let path = std::env::temp_dir().join(format!(
"m2v-dynmulti-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
Scratch(path)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn device(cache: &Path) -> Device {
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
false => vec![
DeviceKind::Discrete,
DeviceKind::Integrated,
DeviceKind::Virtual,
],
},
shader_cache: ShaderCacheOptions {
directory: Some(cache.to_owned()),
..ShaderCacheOptions::default()
},
..DeviceOptions::default()
};
Device::system_default_with(&options).unwrap()
}
/// What a run of `entry` answered: the bytes of each bound buffer, and the counter steps.
struct Ran {
buffers: Vec<Vec<u8>>,
reused: u64,
found: u64,
pushed: u64,
}
/// Dispatch `entry` of fixture `file` `dispatches` times with `slots` buffers of `bytes` bytes
/// bound, each its own buffer, `threads` threads a dispatch.
fn run(
file: &str,
entry: &str,
slots: u32,
bytes: u64,
threads: u64,
dispatches: usize,
) -> Result<Ran, String> {
let scratch = Scratch::new();
let device = device(&scratch.0);
let queue = device.new_command_queue().unwrap();
let ll = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public")
.join(file);
let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).map_err(|e| format!("{e:?}"))?;
let library = metal2vulkan::library::Library::from_air(&bitcode).map_err(|e| format!("{e}"))?;
let function = device
.new_library_with_compile_library(library)
.new_function_with_name(entry)
.map_err(|e| format!("{e}"))?;
let descriptor =
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
let state = device
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
.map_err(|e| format!("pipeline: {e}"))?;
let buffers: Vec<_> = (0..slots)
.map(|_| device.new_buffer(bytes, ResourceOptions::shared()).unwrap())
.collect();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&state).unwrap();
for (index, buffer) in buffers.iter().enumerate() {
encoder.set_buffer(Some(buffer), 0, index as u32).unwrap();
}
let before = device.work_counts();
for _ in 0..dispatches {
encoder
.dispatch_threads(Size::new(threads, 1, 1), Size::new(threads.min(32), 1, 1))
.unwrap();
}
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer
.wait_until_completed_for(std::time::Duration::from_secs(60))
.unwrap();
if let Some(e) = command_buffer.error() {
return Err(format!("command buffer: {e:?}"));
}
let after = device.work_counts();
Ok(Ran {
buffers: buffers
.iter()
.map(|b| {
let p = b.contents().unwrap();
// SAFETY: the command buffer completed, so the GPU's writes are visible, and the
// mapping holds the buffer's whole length.
unsafe { std::slice::from_raw_parts(p.as_ptr(), b.length() as usize) }.to_vec()
})
.collect(),
reused: after.set_zero_sets_reused - before.set_zero_sets_reused,
found: after.set_zero_sets_found - before.set_zero_sets_found,
pushed: after.dispatches_pushing_set_zero - before.dispatches_pushing_set_zero,
})
}
/// `record_stride_not_a_multiple_of_four`: `sizeof(Rec)` is 18 and `alignof` 2, so
/// `sizes[tid] == 18002`, and its two narrow stores land at `18 * tid + 6` (a `short`) and
/// `18 * tid + 11` (a `uchar`). Its store sink uses a `u16` and a `u8` unit view, so its sink
/// binding is one of three variables.
#[test]
fn a_narrow_unit_kernel_runs_and_its_set_follows_the_devices_answer() {
const THREADS: u64 = 8;
let answer = answered();
for dispatches in [8usize, 16] {
let ran = run(
"kernel_record_stride_not_a_multiple_of_four.ll",
"record_stride_not_a_multiple_of_four",
2,
1024,
THREADS,
dispatches,
)
.unwrap_or_else(|e| panic!("{dispatches} dispatches: {e}"));
let recs = &ran.buffers[0];
let sizes = &ran.buffers[1];
for tid in 0..THREADS as usize {
let size = u32::from_le_bytes(sizes[tid * 4..tid * 4 + 4].try_into().unwrap());
let short = i16::from_le_bytes(recs[18 * tid + 6..18 * tid + 8].try_into().unwrap());
let byte = recs[18 * tid + 11];
assert_eq!(
(size, short, byte),
(18002, (tid as i16) * 7 + 1, (tid as u8) ^ 0xa5),
"thread {tid} of {dispatches} dispatches answered ({size}, {short}, {byte}): \
Metal's `sizeof` is 18 and `alignof` 2, and the two narrow stores land at \
18 * tid + 6 and 18 * tid + 11"
);
}
ran.holds_the_answer(answer, dispatches, "record_stride_not_a_multiple_of_four");
}
}
/// `encoders_plain` of the reflection fixtures, whose store sink uses a `u16`, a `u8` and a
/// `uvec4` unit view: its sink binding is one of four variables. Its answers are not Metal's to
/// check here (its buffers are its own), only that it is made, runs, answers the same bytes at
/// both dispatch counts, and takes the binding type the device's answer calls for.
#[test]
fn a_four_variable_kernel_runs_and_its_set_follows_the_devices_answer() {
let answer = answered();
let mut digests = Vec::new();
for dispatches in [8usize, 16] {
let ran = run(
"reflection/encoders.ll",
"encoders_plain",
8,
4096,
4,
dispatches,
)
.unwrap_or_else(|e| panic!("{dispatches} dispatches: {e}"));
digests.push(ran.buffers.clone());
ran.holds_the_answer(answer, dispatches, "encoders_plain");
}
assert_eq!(
digests[0], digests[1],
"eight and sixteen dispatches of `encoders_plain` answered different bytes"
);
}
/// The device's own answer, from a device of this test's own making: what every check here reads.
fn answered() -> bool {
let scratch = Scratch::new();
let device = device(&scratch.0);
crate::pipeline::objects::asks_multi_variable_dynamic(&device)
}
impl Ran {
/// Hold the binding type the device's `answer` calls for: where it takes a binding of several
/// variables dynamically and the variant does not push set 0, every dispatch after the first
/// binds the set its predecessor wrote; where it does not, each allocates and writes its own,
/// which `set_zero_sets_reused` and `set_zero_sets_found` both count none of.
fn holds_the_answer(&self, answer: bool, dispatches: usize, what: &str) {
if self.pushed > 0 {
assert_eq!(
self.pushed, dispatches as u64,
"{what}: {} of {dispatches} dispatches pushed set 0, which is all or none",
self.pushed
);
return;
}
let want = match answer {
true => dispatches as u64 - 1,
false => 0,
};
assert_eq!(
(self.reused, self.found),
(want, 0),
"{what}: the device {} a binding of several variables dynamically, and {dispatches} \
dispatches reused {} and found {} of their predecessors' sets, not {want} and 0",
match answer {
true => "takes",
false => "does not take",
},
self.reused,
self.found
);
}
}
@@ -82,6 +82,8 @@ mod driver_defects;
mod driver_pipeline_compile;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod dropped_usage;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod dynamic_multi_variable;
mod enables;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod encoder_holds;
@@ -1 +1 @@
910c256f8c1505a85e6e48c3707b45b299ffda568ac542a2c41bd1423e749332
bfc6bdab5af7249a96683e4af8a5b39c16bd0d98fb07ccf3057b63f69a656179
@@ -0,0 +1,186 @@
//! The device self-check module: a storage-buffer binding one entry point uses through **several
//! variables**.
//!
//! A plan's slot or store sink declares one variable per view at its binding -- a word view, and
//! the narrow and `uvec4` unit views an access of it needs (`memory::views`, all of them at the one
//! binding, so the stage counts one descriptor). A consumer that binds such a descriptor
//! *dynamically* (`VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC`, the offset given as the set is
//! bound) lets commands that differ only in that offset share one descriptor set; a consumer that
//! cannot must give each command a set of its own.
//!
//! Whether a device takes one is not a Vulkan question -- the spec puts no limit on the variables
//! at a binding, dynamic or not -- but a driver that translates SPIR-V to another shader language
//! may handle it wrongly. So the consumer asks the device, by creating one pipeline of exactly
//! that shape and seeing whether it is made: this module is that pipeline's shader.
//!
//! **The module.** One `GLCompute` entry `main` with local size (1, 1, 1), no push constants, and
//! at [`DynamicViewsModule::BINDING`] of set [`DynamicViewsModule::SET`] one storage buffer
//! declared through a word view and **one variable per unit view the profile's storage views can
//! declare** ([`Units::storage_on`]), which is every kind a plan can ask for: so a device that
//! makes this pipeline makes one of any plan's binding, whose variables are a subset of these. The
//! entry references each variable (the length of each view's runtime array, summed and stored
//! through the word view), since a variable a module declares but its entry point does not
//! reference is not one of the binding's (`pipeline::link`'s `count_variables`).
use std::sync::Arc;
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::Error;
use crate::memory::leaf::Units;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol};
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, TypeId};
use crate::spirv::ir::{
natural_layout, BinOp, ExecMode, ExecModel, LayoutRule, MemAccess, StorageClass, Type,
TypedModule,
};
/// The crate-owned self-check module on one device, validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DynamicViewsModule {
/// SPIR-V 1.5 words, entry point `main`, one binding as below.
pub spirv: Arc<[u32]>,
/// What the module needs from the device (within every Vulkan 1.2 device, plus the 8- and
/// 16-bit storage access its profile's unit views already need).
pub requirements: Requirements,
}
impl DynamicViewsModule {
/// The one descriptor set.
pub const SET: u32 = 0;
/// The one binding, which the module uses through several variables.
pub const BINDING: u32 = 0;
/// Invocations of its one workgroup.
pub const LOCAL_SIZE: u32 = 1;
/// Bytes the consumer binds at the binding: enough for the one word the entry stores, and a
/// multiple of every unit view's stride.
pub const BYTES: u64 = 64;
}
/// The binding symbol of the views in the typed module.
const VIEWS: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 0,
};
/// A `Block { elem values[]; }` of `stride`-byte elements.
fn block_of(b: &mut ModuleBuilder, elem: TypeId, stride: u32) -> BResult<TypeId> {
let rta = b.ty(Type::RuntimeArray {
elem,
stride: Some(stride),
})?;
let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?;
b.ty(Type::Struct {
members: [rta].into(),
layout: Some(layout),
})
}
/// The self-check module as a typed module, with one variable at [`VIEWS`] per view of `units`
/// beside its word view (the module docs).
fn typed_module(units: Units) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let words = block_of(&mut b, u32_, 4)?;
let word = b.resource(VIEWS, StorageClass::StorageBuffer, words)?;
let mut views: Vec<GlobalId> = Vec::new();
for (declared, width, stride) in [(units.u16, 16, 2), (units.u8, 8, 1)] {
if !declared {
continue;
}
let narrow = b.ty(Type::Int {
width,
signed: false,
})?;
let block = block_of(&mut b, narrow, stride)?;
views.push(b.resource_view(VIEWS, StorageClass::StorageBuffer, block)?);
}
if units.vec4 {
let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?;
let block = block_of(&mut b, uvec4, 16)?;
views.push(b.resource_view(VIEWS, StorageClass::StorageBuffer, block)?);
}
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let base = f.module().global_value(word)?;
// Each view's own runtime-array length, which references its variable and reads no memory.
let mut total = f.array_length(base, 0)?;
for view in views {
let p = f.module().global_value(view)?;
let len = f.array_length(p, 0)?;
total = f.binary(BinOp::IAdd, total, len)?;
}
let zero = f.u32_const(0)?;
let zero = f.module().const_value(zero)?;
let at = f.access_chain(base, &[zero, zero])?;
f.store(at, total, MemAccess::default())?;
f.ret(None)?;
let id = f.finish()?;
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize {
x: DynamicViewsModule::LOCAL_SIZE,
y: 1,
z: 1,
}],
)?;
b.finalize()
}
/// The set and binding numbers of the module's symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(DynamicViewsModule::SET),
Symbol::Binding(s) if *s == VIEWS => Some(DynamicViewsModule::BINDING),
_ => None,
}
}
/// The self-check module of `device`: built with the typed builder, checked by the owned verifier
/// against the device's profile (requirements included), serialized, and numbered with
/// [`DynamicViewsModule`]'s set and binding.
pub fn dynamic_views_module(device: &Device) -> Result<DynamicViewsModule, Error> {
let profile = device.profile();
let m = typed_module(Units::storage_on(profile))?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
profile.check(&r.requirements).map_err(|c| {
Error::Internal(crate::error::InternalError::new(
crate::error::InternalKind::RequirementsExceedProfile,
format!("the dynamic-views self-check needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &binding_of)?;
Ok(DynamicViewsModule {
spirv: words.into(),
requirements: r.requirements,
})
}
#[cfg(test)]
mod tests {
use super::typed_module;
use crate::memory::leaf::Units;
use crate::spirv::testing::{assert_valid, committed_profiles};
/// The module is valid on every committed profile, with the units that profile's storage views
/// can declare.
#[test]
fn the_dynamic_views_self_check_is_valid_on_every_committed_profile() {
for (stem, p) in committed_profiles().expect("profiles") {
let units = Units::storage_on(&p);
let m = typed_module(units).unwrap_or_else(|e| panic!("{stem}: {e:?}"));
assert_valid(m, &p);
}
}
}
+2
View File
@@ -148,6 +148,7 @@ pub(crate) mod depth_magnitude;
pub(crate) mod depth_stencil_copy;
pub(crate) mod depth_stencil_resolve;
pub(crate) mod dispatch;
pub(crate) mod dynamic_views;
pub(crate) mod etc_decode;
pub(crate) mod extended_shadow;
pub(crate) mod graphics;
@@ -307,6 +308,7 @@ pub use state::{
};
// 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.
pub use dynamic_views::{dynamic_views_module, DynamicViewsModule};
pub use plane_bytes_copy::{
plane_bytes_copy_module, PlaneBytes, PlaneBytesCopyModule, PlaneSource,
};
@@ -116,6 +116,10 @@ assoc-const metal2vulkan::bind::DrawReplayModule::PUSH_BYTES pub const PUSH_BYTE
assoc-const metal2vulkan::bind::DrawReplayModule::RECORDS_PUSH pub const RECORDS_PUSH: u32
assoc-const metal2vulkan::bind::DrawReplayModule::RESIDENT_PUSH pub const RESIDENT_PUSH: u32
assoc-const metal2vulkan::bind::DrawReplayModule::STATUS_PUSH pub const STATUS_PUSH: u32
assoc-const metal2vulkan::bind::DynamicViewsModule::BINDING pub const BINDING: u32
assoc-const metal2vulkan::bind::DynamicViewsModule::BYTES pub const BYTES: u64
assoc-const metal2vulkan::bind::DynamicViewsModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::DynamicViewsModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::EtcDecode::ALL pub const ALL: [EtcDecode; 7]
assoc-const metal2vulkan::bind::ExecutionStatus::BYTES pub const BYTES: usize
assoc-const metal2vulkan::bind::ExecutionStatus::WORDS pub const WORDS: usize
@@ -614,6 +618,10 @@ assoc-const-value metal2vulkan::bind::DrawReplayModule::PUSH_BYTES 24
assoc-const-value metal2vulkan::bind::DrawReplayModule::RECORDS_PUSH 16
assoc-const-value metal2vulkan::bind::DrawReplayModule::RESIDENT_PUSH 0
assoc-const-value metal2vulkan::bind::DrawReplayModule::STATUS_PUSH 8
assoc-const-value metal2vulkan::bind::DynamicViewsModule::BINDING 0
assoc-const-value metal2vulkan::bind::DynamicViewsModule::BYTES 64
assoc-const-value metal2vulkan::bind::DynamicViewsModule::LOCAL_SIZE 1
assoc-const-value metal2vulkan::bind::DynamicViewsModule::SET 0
assoc-const-value metal2vulkan::bind::EtcDecode::ALL [EtcDecode::Rgb8, EtcDecode::Rgb8A1, EtcDecode::Rgba8, EtcDecode::R11Unorm, EtcDecode::R11Snorm, EtcDecode::Rg11Unorm, EtcDecode::Rg11Snorm]
assoc-const-value metal2vulkan::bind::ExecutionStatus::BYTES 32
assoc-const-value metal2vulkan::bind::ExecutionStatus::WORDS 8
@@ -3179,6 +3187,8 @@ field metal2vulkan::bind::DrawReplayPreprocess.parent pub parent: Vec<u8>
field metal2vulkan::bind::DrawReplayPreprocess.push_constants pub push_constants: Vec<u8>
field metal2vulkan::bind::DrawReplayPreprocess.push_holes pub push_holes: Vec<PushHole>
field metal2vulkan::bind::DrawReplayPreprocess.resident pub resident: RootTable
field metal2vulkan::bind::DynamicViewsModule.requirements pub requirements: Requirements
field metal2vulkan::bind::DynamicViewsModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::ExtendedShadowModule.requirements pub requirements: Requirements
field metal2vulkan::bind::ExtendedShadowModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::FlatDispatchModule.layout pub layout: PipelineLayout
@@ -4591,6 +4601,7 @@ fn metal2vulkan::bind::draw_replay_preprocess pub fn draw_replay_preprocess(devi
fn metal2vulkan::bind::draw_replay_primitive_type pub fn draw_replay_primitive_type(command_types: IndirectCommandType, (inherit_pipeline_state, inherit_buffers): (bool, bool), written: CommandWrites) -> Result<PrimitiveType, DrawReplayRule>
fn metal2vulkan::bind::draw_replay_slots pub fn draw_replay_slots(interface: &PipelineInterface) -> (u32, u32)
fn metal2vulkan::bind::draw_replay_state pub fn draw_replay_state(graphics: &GraphicsState, merged: bool) -> Result<(), DrawReplayRule>
fn metal2vulkan::bind::dynamic_views_module pub fn dynamic_views_module(device: &Device) -> Result<DynamicViewsModule, Error>
fn metal2vulkan::bind::etc_decode_module pub fn etc_decode_module(device: &Device, decode: EtcDecode, texels: EtcTexels) -> Result<BlockDecodeModule, Error>
fn metal2vulkan::bind::extended_shadow_module pub fn extended_shadow_module(device: &Device, form: ExtendedRange) -> Result<ExtendedShadowModule, Error>
fn metal2vulkan::bind::flat_dispatch_module pub fn flat_dispatch_module(device: &Device) -> Result<FlatDispatchModule, Error>
@@ -9499,6 +9510,7 @@ struct metal2vulkan::bind::DrawReplay #[derive(Clone, Debug, PartialEq, Eq)] #[n
struct metal2vulkan::bind::DrawReplayLayout #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DrawReplayLayout
struct metal2vulkan::bind::DrawReplayModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DrawReplayModule
struct metal2vulkan::bind::DrawReplayPreprocess #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DrawReplayPreprocess
struct metal2vulkan::bind::DynamicViewsModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DynamicViewsModule
struct metal2vulkan::bind::ExecutionStatus #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ExecutionStatus
struct metal2vulkan::bind::ExtendedShadowModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ExtendedShadowModule
struct metal2vulkan::bind::FlatDispatchModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FlatDispatchModule
Can't render this file because it is too large.
+2
View File
@@ -653,6 +653,8 @@ surface! {
struct ShadowCopyInModule N;
fn rows_copy_module;
struct RowsCopyModule N;
fn dynamic_views_module;
struct DynamicViewsModule N;
fn shadow_merge_module;
struct ShadowMergeModule N;
fn shadow_merge_image_module;
+1
View File
@@ -85,6 +85,7 @@ known. The rest of the differences are docs/API.md section 9's precision notes.
| On MoltenVK a no-copy buffer or heap released with no keep-alive while batches are in flight runs its deallocator once the batches submitted before its release completed, and the program's own submissions through `CommandQueue::with_vk_queue` before it, where Metal runs it at the release. | MoltenVK 1.4.1 fails pending work that reads device addresses where memory a device-address buffer lay in is freed (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), so freed memory waits for the batches in flight (`WorkCounts::freed_memory_parked`). | `HostDeallocatorDelayed` (`host-deallocator-delayed`) |
| On MoltenVK a `Shared` or `Managed` texture whose format packs more than one texel into a block (every block-compressed family) keeps its image out of host-transfer memory, so its CPU copies take submissions where another driver's take none. The stored texels are Metal's either way; what changes is the work, in `WorkCounts::command_buffers_begun_batch_work` and the `command_buffers_begun` and `command_buffers_submitted` that carry it (`bc1-rgba`, four 16 x 16 `BC1_RGBA` levels: `command_buffers_begun` 8 on the bind-time path and 15 off it; `fresh-texture-bc1-rgba-managed`: 3 and 5). A `replaceRegion` of such a texture stages its bytes for the device's next submission and waits for none (`texture/first_move.rs`). Its CPU **reads** come out of a host shadow of the image's texels, made at the first read of the texture by the submission that read waits for either way and read from by every read after it: exact (it holds the image's own bytes, and a CPU write writes both), bounded (`host_shadow::SHADOW_BYTES`, past which a read takes the submission path), and lazy, so a texture nobody reads back holds nothing. It is dropped wherever anything but a CPU write may have written the texels: every commit of the program's, its own Vulkan submissions, another `VkImage`, a detach, or the program taking the image's handle (`texture/host_shadow.rs`; `WorkCounts::texel_shadows_made`, `texel_shadow_reads`, `texel_shadows_dropped`). Measured on an M3 Max: `compressed-moves-bc1-rgba` reads `internal_submissions` 5 where it read 56 and `command_buffers_begun` 30 where it read 81, for 1,168 bytes of shadow over its five textures and 56 reads out of them. | MoltenVK 1.4.2 binds such an image through a `flushToDevice` that `replaceRegion:`s every subresource at one block's bytes a row instead of the row of blocks, tripping AGX's `bytes_per_row >= used_bytes_per_row` assertion (`RuntimeDriverDefect::HostTransferImagesCopiedAtBind`). The copy is the driver's own and no call of the program's asks for it, so the only way not to provoke it is not to ask for the image; every other driver keeps the host-transfer path, as does a device without `VK_EXT_host_image_copy`. A write cannot leave the GPU's copy of the texels unwritten, so only reads come off the host shadow. | None (cost only, and exact) |
| On ANV (Mesa 26.2.4) a pipeline whose largest stage module, under the consumer's exact forms, passes 400,000 words is retranslated with those forms dropped until it fits: native sampling first, then every module-growing exact answer native. Every kind is fitted: render (vertex and fragment), mesh render (object, mesh and fragment, or the stages that emulate them), compute and tile render; the notice names the state's kind. On a large enough module the driver's register allocator reads past its interference bitset and the process faults at pipeline creation. | ANV's `brw` register allocator faults on such modules (`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`), no documented Vulkan form bounds a module's register pressure, and a refusal would withhold the consumer's large shaders. | `ExactFormsOverCompilerLimit` (`exact-forms-over-compiler-limit`) |
| On a driver that does not take a set-0 buffer binding whose entry point uses it through several variables as a **dynamic** descriptor, every draw or dispatch of such a variant allocates and writes a descriptor set of its own, where one dynamic binding would let them share one set, bound again at each command's own offset. Such a binding is a slot or store sink reached through its word view and a narrow or `uvec4` unit view (`memory::views`): of the 1,378 store sinks the public fixtures plan on this profile, 20 entries have one (`record_stride_not_a_multiple_of_four`, `encoders_plain`, `encoder_types_*`, `hwd_half_reads`, `kernel_copy_runtime_ulong_length`, `kernel_simdgroup_matrix_block`). The stored values are the same either way; what changes is the set a command allocates and writes (`WorkCounts::set_zero_sets_reused` counts none of them). The device answers for itself, by creating one pipeline of exactly that shape and destroying it (`pipeline::objects::takes_multi_variable_dynamic`, `bind::DynamicViewsModule`, asked once and only where a layout has such a binding), so a driver without the defect pays nothing. A device whose set 0 is pushed (`VK_KHR_push_descriptor` with an eligible layout) never reaches the choice. | Nothing in Vulkan bounds the variables at a binding, dynamic or not, so there is no exact form to switch to: the driver either compiles the shape or does not. MoltenVK's SPIRV-Cross declares one variable's local alone -- read in 1.4.1's source and measured on 1.4.2 (`driverVersion` 10402) on an Apple M3 Max, where `vkCreateComputePipelines` answers `VK_ERROR_INITIALIZATION_FAILED` for a kernel of three and of four variables at one dynamic binding. The check proves the driver compiles the shape, not that it applies the dynamic offset to every variable at it; no device is measured to get that wrong. | None (cost only, and exact) |
## Accuracy switches whose default is Metal's