Validation: an L4 kernel row is made through the runtime, its pipeline state and one encoded dispatch

corpus-pipeline asked the driver for a kernel row's compute pipeline at
the region the binder planned for one representative dispatch
(acceptance::dispatch), and tallied the binder's answer (BIND_REFUSED,
BIND_ERROR). That is not the pipeline a guest's kernel gets. A kernel row
is now made as a guest's kernel is made (platform::runtime_acceptance):
- the row's AIR becomes a runtime library, and its function is
  specialized with the row's function-constant values;
- one ComputePipelineState is made on the sweep's device, restricted to
  --profiles-layer's profile where one is given;
- one dispatch of one threadgroup of the state's thread execution width
  (or its maxTotalThreadsPerThreadgroup where that is fewer) is encoded
  into a command buffer that is dropped uncommitted, so the runtime picks
  the module that threadgroup runs on, asks the driver for its pipeline,
  and nothing executes.

The verdicts:
- The creation time is the runtime's own count of it
  (pipeline_creation_nanos).
- A message from the validation layer is INVALID_USAGE.
- A Vulkan error is REFUSED.
- The runtime's typed refusal (the translator's, a known gap, a limit) is
  RUNTIME_REFUSED, counted.
- A kernel the runtime runs as Metal's without effects, and makes no
  pipeline for, is NO_EFFECT, counted.

The row still compiles in its compile worker first, for its words, its
outcome, --compile-only and --keep-modules. The make runs in the sweep's
process, held to the per-attempt ceilings (runtime::within_ceilings).

Removed:
- acceptance::dispatch (plan_compute_row, ComputeCreation, NoCreation,
  BinderAnswer);
- RowCompile::Binder and UnmodelledKind::Dispatch;
- the tally's bind_refused and bind_errors, and the detail's
  imageblock=WxH;
- the own context's compute arm of create_acceptance_pipeline, which now
  takes a render pipeline, with its region test.
The summary line's bind_refused= and bind_errors= become
runtime_refused= and no_effect=.

What is lost: L4 kernel acceptance on Mesa's drm-shim drivers (RADV, ANV
and NVK), which stood for hardware we do not own. The runtime does not
open those devices, so the rung runs on lavapipe and the real cards
only. NVK is lost entirely: the shim was its only venue, and it never
ran here.

Committed rows removed: none. No L4 row is committed. Counted by
environment over corpus/observations/vulkan and observations/refusals at
bcc88a43cf, there are 55 rows in 6 environments (the 780M, Iris Xe,
RTX 5080 Laptop twice, lavapipe twice), and none is from a drm-shim
environment.
This commit is contained in:
Anees Iqbal committed 2026-11-22 06:05:19 -08:00
1 parent 9a01f1e8ee
commit 71f93243d9
13 files changed
+570 -920

No files matched your search

@@ -1,25 +1,28 @@
//! Driver acceptance for the engine.
//!
//! `corpus-pipeline --profile P` compiles each row through the public compile API
//! and asks a Vulkan driver to create the pipeline **from the binder layout the artifact
//! carries** ([`PipelineLayout`](metal2vulkan::pipeline::PipelineLayout), vertex input, stage
//! modules with their specialization and subgroup facts, the graphics state). Nothing is bound or
//! dispatched. A row is built as [`PipelineRequest::Row`] says ([`row`]): a kernel's compute
//! pipeline; a vertex function's rasterization-disabled pipeline with a vertex descriptor for the
//! attributes it declares; a fragment function's rasterizing pipeline drawn with its generated
//! passthrough vertex companion ([`crate::companion`], the one the executors draw with).
//! `corpus-pipeline --profile P` compiles each row through the public compile API. A render row's
//! pipeline is created by a Vulkan driver **from the binder layout the artifact carries**
//! ([`PipelineLayout`](metal2vulkan::pipeline::PipelineLayout), vertex input, stage modules with
//! their specialization and subgroup facts, the graphics state), with nothing bound or drawn. A
//! kernel row is made as a guest's kernel is, through the runtime: its pipeline state on the
//! sweep's device and one dispatch of one representative threadgroup encoded, never committed
//! ([`crate::candidate::create_runtime_kernel`]). A row is built as [`PipelineRequest::Row`] says
//! ([`row`]): a kernel's compute pipeline; a vertex function's rasterization-disabled pipeline with
//! a vertex descriptor for the attributes it declares; a fragment function's rasterizing pipeline
//! drawn with its generated passthrough vertex companion ([`crate::companion`], the one the
//! executors draw with).
//! This module is the device-free half: compiling a row and deciding whether the opened device
//! enabled and provides what the pipeline requires ([`unenabled`] for the API version, features,
//! and extensions, by the product's `DeviceDescription::required_enables` on the opened
//! description; [`unmet_device_facts`] for properties, limits, formats, stage create flags, and
//! float-controls independence, against the opened device's queried profile). The device half is
//! [`crate::candidate::create_acceptance_pipeline`].
//! [`crate::candidate::create_acceptance_pipeline`] for a render row and
//! [`crate::candidate::create_runtime_kernel`] for a kernel row.
//!
//! The sweep compiles every row in a killable worker ([`compile_row_in_worker`]), never in the
//! process that holds the device; [`compile_pipeline`] is the compile the worker runs, and it
//! derives a row's descriptor and companion from the AIR there too.
pub mod dispatch;
pub mod metal_report;
pub mod row;
@@ -31,7 +34,6 @@ use crate::worker::compile::{
compile_compute_request, compile_render_request, CompileWorker, NotCompiled, WorkerDevice,
};
use crate::worker::{Measured, WorkerFailure};
use dispatch::{BinderAnswer, ComputeCreation, NoCreation};
use metal2vulkan::bind::{BindShape, Dispatch};
use metal2vulkan::cache::VariantKey;
use metal2vulkan::device::Independence;
@@ -99,14 +101,14 @@ fn stage_precision_notes(stages: &[StageModule]) -> Vec<PrecisionNote> {
notes
}
/// An L4 row compiled for a driver: a kernel with the dispatch region its pipeline is created from
/// ([`dispatch::plan_compute_row`]), or a render pipeline, created at its stages' default
/// specializations, of a `row` function.
/// An L4 row compiled: a kernel's compute pipeline, its module the words the sweep counts (the
/// driver is asked for the pipeline the runtime makes of the row's AIR,
/// [`crate::candidate::create_runtime_kernel`]), or a render pipeline, created at its stages'
/// default specializations, of a `row` function.
#[derive(Clone, Debug)]
pub enum RowPipeline {
Compute {
pipeline: Box<ComputePipeline>,
creation: ComputeCreation,
},
Render {
pipeline: Box<RenderPipeline>,
@@ -115,23 +117,15 @@ pub enum RowPipeline {
}
impl RowPipeline {
/// The row's pipeline as compiled: compute rows from [`compile_row`] have a creation region,
/// render rows the stage of their own function.
fn of(
device: &Device,
pipeline: AcceptancePipeline,
stage: RowStage,
) -> Result<RowPipeline, NoCreation> {
Ok(match pipeline {
AcceptancePipeline::Compute(pipeline) => {
let creation = dispatch::plan_compute_row(device, &pipeline)?;
RowPipeline::Compute { pipeline, creation }
}
/// The row's pipeline as compiled: a render row's with the stage of its own function.
fn of(pipeline: AcceptancePipeline, stage: RowStage) -> RowPipeline {
match pipeline {
AcceptancePipeline::Compute(pipeline) => RowPipeline::Compute { pipeline },
AcceptancePipeline::Render(pipeline) => RowPipeline::Render {
pipeline,
row: stage,
},
})
}
}
/// What the pipeline needs from the device.
@@ -208,9 +202,6 @@ pub enum RowCompile {
/// a vertex attribute of a type no Metal vertex format reads, or a fragment function no
/// generated companion draws, by kind. A modelled limit of the tool, never a product verdict.
Unmodelled(row::Unmodelled),
/// The binder's error for a kernel row's representative dispatch ([`dispatch`]): a typed
/// refusal the product documents, or an error that fails the sweep.
Binder(BinderAnswer),
/// The worker boundary stopped the compile or its result was unusable (a deadline, the memory
/// limit, a crashed worker, an artifact that does not load): the outcome
/// ([`crate::worker::WorkerFailure::outcome`]) and the failure text. A budget breach is a
@@ -218,17 +209,6 @@ pub enum RowCompile {
Stopped(Outcome, String),
}
impl RowCompile {
/// A compiled row, or why the tool creates no pipeline from it.
fn of(pipeline: Result<RowPipeline, NoCreation>) -> RowCompile {
match pipeline {
Ok(pipeline) => RowCompile::Compiled(Box::new(pipeline)),
Err(NoCreation::Unmodelled(why)) => RowCompile::Unmodelled(why),
Err(NoCreation::Binder(answer)) => RowCompile::Binder(answer),
}
}
}
/// How an L4 row's vertex function fetches its attributes ([`row`]): the projection the
/// product derives from the synthesized descriptor (fixed-function wherever the device fetches
/// the format), or every vertex buffer pulled in the shader (`VariantKey::pulled_vertex_buffers`),
@@ -524,7 +504,7 @@ pub fn compile_row(
constants: FunctionConstantValues::defaults(),
};
match compile_pipeline(&[bitcode], &request, device, deadline) {
Ok(pipeline) => RowCompile::of(RowPipeline::of(device, pipeline, stage)),
Ok(pipeline) => RowCompile::Compiled(Box::new(RowPipeline::of(pipeline, stage))),
Err(PipelineCompileError::Product(error)) => {
RowCompile::NotCompiled(Outcome::from(&error), bounded_detail(&error.to_string()))
}
@@ -589,21 +569,20 @@ pub fn compile_row_in_worker(
)
}
};
worker_row(device, compiled, stage)
worker_row(compiled, stage)
}
/// What a compile worker answered for a row whose own function is a `stage` function: the
/// pipeline made ready for a driver, the compile's refusal, or the boundary's stop, with what the
/// parent measured around the worker when one ran.
fn worker_row(
device: &WorkerDevice,
compiled: Result<(Result<AcceptancePipeline, NotCompiled>, Measured), WorkerFailure>,
stage: RowStage,
) -> (RowCompile, Option<Measured>) {
match compiled {
Ok((result, measured)) => (
match result {
Ok(pipeline) => RowCompile::of(RowPipeline::of(device.device(), pipeline, stage)),
Ok(pipeline) => RowCompile::Compiled(Box::new(RowPipeline::of(pipeline, stage))),
Err(NotCompiled::Product(outcome, detail)) => {
RowCompile::NotCompiled(outcome, detail)
}
@@ -646,7 +625,7 @@ pub fn compile_draw_in_worker(
compiled.measured,
)
});
worker_row(device, compiled, RowStage::Fragment)
worker_row(compiled, RowStage::Fragment)
}
/// A library's bitcode as a worker input: its bytes, base64 as a retained row stores them.
@@ -925,6 +904,21 @@ pub enum Acceptance {
/// `VK_LAYER_KHRONOS_validation` reported invalid usage while the pipeline was created:
/// whatever the driver did, the row is not evidence.
InvalidUsage(Vec<String>),
/// The runtime refused a kernel row with its typed error, as it refuses a guest's kernel: the
/// translator's refusal, a known gap, or a limit of the device. No driver was asked.
RuntimeRefused(String),
/// The runtime made a kernel row's pipeline state and ran its dispatch as Metal's without
/// effects (the kernel writes no memory): no driver was asked for a pipeline, as none is for a
/// guest's.
NoEffect,
}
/// A kernel row as the runtime makes it ([`crate::candidate::create_runtime_kernel`]): its AIR,
/// its kernel, and the function-constant values the function is made with.
pub struct RuntimeRow<'a> {
pub bitcode: &'a [u8],
pub entry: &'a str,
pub constants: &'a FunctionConstantValues,
}
/// Why an acceptance attempt gave no verdict about a pipeline. The kinds are kept apart because
@@ -1163,8 +1157,7 @@ mod tests {
/// A kernel row reading stage inputs compiles under the stage-input descriptor its AIR implies
/// (each attribute its own buffer at the executors' slot), and the pipeline binds those
/// buffers. Under the resident-table domains, the executor's own context's: the binder plans
/// the row, and the identity domains' binder refuses stage input's encoder values.
/// buffers.
#[test]
fn a_stage_input_kernel_row_compiles_under_its_implied_descriptor() {
let Some(bitcode) = fixture("kernel_stage_in.ll") else {
@@ -1,351 +0,0 @@
//! The dispatch region an L4 kernel row's pipeline is created from.
//!
//! A kernel's stage carries its specialization constants at placeholder defaults (a local size
//! of 1) that the binder replaces, and the stage create flags of its simd tier: in a `Direct` or
//! `Cluster32` tier `REQUIRE_FULL_SUBGROUPS`, valid only with a local size of whole subgroups. A
//! pipeline created at the defaults is therefore invalid usage
//! (`VUID-VkPipelineShaderStageCreateInfo-flags-02759`: 897 kernel rows), and one the binder never
//! creates. The executors create each region's pipeline from the region the binder plans (its
//! specialization, stage flags, and required subgroup size); so does the sweep, for a
//! representative dispatch of the row: one threadgroup of the fewest threads that are whole
//! simdgroups (Metal's thread execution width, 32, or a multiple of it where the tier's subgroups
//! are wider), within the pipeline's `max_total_threads_per_threadgroup`, the smallest the binder
//! runs on the compiled pipeline itself rather than on its emulated-simdgroups variant.
//!
//! The binder plans it for the encoder's defaults, as `BindState::default` states them: nothing
//! bound, no threadgroup memory length set (Metal's 0), and a stage-in region of the dispatch's
//! own threads (which only a dispatch's bytes read, never its specialization). A kernel with an
//! explicit imageblock (`RuntimeFact::ImageblockSize`) has no default: Metal's encoder must set its
//! extent (`setImageblockWidth:height:`), so the dispatch sets one cell per thread of the
//! threadgroup, `w` by 1. That extent is this sweep's representative choice, not a binder fact.
//! Another extent is another specialization of the same pipeline (the binder plans no other variant
//! for it), and its `width · height · cell_bytes` bytes join the threadgroup total that must fit
//! `maxComputeSharedMemorySize`: a larger extent can be refused where this one is created. The
//! row's detail names the extent it was created with (`imageblock=WxH`).
//!
//! The row is compiled as the translation sweep compiles it, with no variant, so a row whose plan
//! asks for one, or that no such threadgroup runs on, is [`Unmodelled`] of kind
//! [`UnmodelledKind::Dispatch`]: the representative dispatch does not reach it. A binder error
//! for the representative dispatch is the binder's answer, not a tool limit
//! ([`BinderAnswer`]). A typed refusal the product documents (`BindError::Unsupported`: the
//! device cannot bind what the dispatch needs) is counted. Any other error fails the sweep: a
//! binder defect (`BindError::Internal`), or a state the binder rejects, which the representative
//! state never should be.
use super::row::{Unmodelled, UnmodelledKind};
use metal2vulkan::bind::{BindState, Dispatch, DispatchRegion, ImageblockSize, StageInRegion};
use metal2vulkan::cache::VariantKey;
use metal2vulkan::device::Device;
use metal2vulkan::error::BindError;
use metal2vulkan::pipeline::{ComputePipeline, RuntimeFact};
/// How the driver is asked to create a kernel row's compute pipeline: the representative
/// dispatch and the binder's region of it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ComputeCreation {
/// One threadgroup of `threads_per_group` `[w, 1, 1]` (the module docs).
pub dispatch: Dispatch,
/// The binder's region of `dispatch`: its specialization (the plan's constants, the local
/// size, `MultiRegion`), stage flags, and required subgroup size.
pub region: DispatchRegion,
/// The representative imageblock extent the dispatch sets, for a kernel with an explicit
/// imageblock (the module docs); `None` for any other.
pub imageblock: Option<ImageblockSize>,
}
/// Why a kernel row has no [`ComputeCreation`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NoCreation {
/// The representative dispatch does not reach the row: a modelled limit of the tool, of kind
/// [`UnmodelledKind::Dispatch`].
Unmodelled(Unmodelled),
/// The binder's error for the representative dispatch.
Binder(BinderAnswer),
}
/// The binder's error for a kernel row's representative dispatch (the module docs).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BinderAnswer {
/// A typed refusal the product documents (`BindError::Unsupported`), which the sweep counts.
/// Any other binder error fails the sweep.
pub documented: bool,
/// The step and the error.
pub detail: String,
}
impl BinderAnswer {
fn of(error: &BindError, step: String) -> BinderAnswer {
BinderAnswer {
documented: matches!(error, BindError::Unsupported(_)),
detail: format!("{step}: {error}"),
}
}
}
/// The [`ComputeCreation`] of `pipeline`, a kernel row compiled for `device` with no variant (the
/// module docs).
pub fn plan_compute_row(
device: &Device,
pipeline: &ComputePipeline,
) -> Result<ComputeCreation, NoCreation> {
let unmodelled = |detail: String| {
NoCreation::Unmodelled(Unmodelled {
kind: UnmodelledKind::Dispatch,
detail,
})
};
let binder =
|error: BindError, step: String| NoCreation::Binder(BinderAnswer::of(&error, step));
let info = &pipeline.metal_info;
let imageblock = pipeline
.dependencies
.iter()
.any(|dependency| matches!(dependency.fact, RuntimeFact::ImageblockSize { .. }));
for width in widths(
info.thread_execution_width,
info.max_total_threads_per_threadgroup,
) {
let mut state = BindState::default();
let extent = imageblock.then(|| ImageblockSize::new(width, 1));
if let Some(extent) = extent {
state.imageblock_size = extent;
}
let plan = pipeline
.plan(device, &state.shape())
.map_err(|error| binder(error, format!("plan for a threadgroup of {width}")))?;
if plan.variant != VariantKey::new() {
return Err(unmodelled(format!(
"the binder plans a threadgroup of {width} on variant {:?}, not the row's",
plan.variant
)));
}
let dispatch = Dispatch::Threadgroups {
groups: [1, 1, 1],
threads_per_group: [width, 1, 1],
};
let variant = plan
.dispatch_variant(&dispatch)
.map_err(|error| binder(error, format!("the variant of a threadgroup of {width}")))?;
// A threadgroup that is not whole subgroups of the tier runs on the emulated variant.
if variant != plan.variant {
continue;
}
state.stage_in_region = Some(StageInRegion::new([0; 3], [width, 1, 1]));
let commands = plan
.instantiate_dispatch(&state, &dispatch)
.map_err(|error| binder(error, format!("instantiate a threadgroup of {width}")))?;
let region = commands.regions.into_iter().next().ok_or_else(|| {
unmodelled(format!(
"the binder plans no region for one threadgroup of {width}"
))
})?;
return Ok(ComputeCreation {
dispatch,
region,
imageblock: extent,
});
}
Err(unmodelled(format!(
"no threadgroup of whole simdgroups within the pipeline's {} threads runs on the row's \
variant",
info.max_total_threads_per_threadgroup
)))
}
/// The threadgroup widths tried, fewest first: the thread execution width `width` (or `max`, the
/// most threads a threadgroup may have, when it is smaller), then each multiple of `width` up to
/// `max`.
fn widths(width: u32, max: u32) -> impl Iterator<Item = u32> {
let width = width.max(1);
std::iter::once(width.min(max).max(1)).chain(
(2..)
.map_while(move |k: u32| k.checked_mul(width))
.take_while(move |&w| w <= max),
)
}
#[cfg(test)]
mod tests {
use super::{widths, BinderAnswer};
use crate::acceptance::{compile_row, Projection, RowCompile, RowPipeline, RowStage};
use metal2vulkan::bind::Dispatch;
use metal2vulkan::pipeline::{Axis, SpecKey};
use metal2vulkan::vk::PipelineShaderStageCreateFlags;
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
/// A kernel whose simd tier requires full subgroups on `moltenvk-m3` keeps the flag, and is
/// created from the binder's region of one threadgroup of 32 threads, not at its stage's
/// placeholder local size of 1, with which the flag is
/// `VUID-VkPipelineShaderStageCreateInfo-flags-02759`.
#[test]
fn a_full_subgroup_kernel_row_is_created_from_a_region_of_whole_subgroups() {
let bitcode = match llvm_assemble(&engine_dir().join("simd_ops.ll")) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected simd_ops.ll: {why}"),
};
let device = crate::engine::load_device("moltenvk-m3").unwrap();
let compiled = compile_row(
&bitcode,
"simd_shuffle_k",
RowStage::Kernel,
Projection::Derived,
&device,
None,
);
let RowCompile::Compiled(row) = compiled else {
panic!("simd_shuffle_k: {compiled:?}");
};
let RowPipeline::Compute { pipeline, creation } = *row else {
panic!("a kernel row is a compute pipeline");
};
let full = PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS;
assert!(pipeline.stage.stage_flags.contains(full));
assert!(creation.region.stage_flags.contains(full));
assert_eq!(
creation.dispatch,
Dispatch::Threadgroups {
groups: [1, 1, 1],
threads_per_group: [32, 1, 1],
}
);
// Every local-size constant: its placeholder default, and its value in the region, where
// the binder clears the bits the module never reads. The flattened tier's workgroup size is
// `(FlatLocalSize, 1, 1)`, which the module reads whole.
let mut local = Vec::new();
for constant in &pipeline.stage.specialization.constants {
let size = match constant.key {
SpecKey::FlatLocalSize => 32,
SpecKey::LocalSize(Axis::X) => 32,
SpecKey::LocalSize(_) => 1,
_ => continue,
};
if constant.key == SpecKey::FlatLocalSize {
assert_eq!(constant.unread_bits, 0, "the workgroup size is read whole");
}
let size = size & !constant.unread_bits;
assert_eq!(constant.default, 1, "{:?}", constant.key);
let specialization = &creation.region.specialization;
let entry = specialization
.entries
.iter()
.find(|entry| entry.constant_id == constant.id)
.unwrap_or_else(|| panic!("the region does not specialize {:?}", constant.key));
let at = entry.offset as usize;
let bytes = &specialization.data[at..at + entry.size as usize];
let mut value = [0u8; 8];
value[..bytes.len()].copy_from_slice(bytes);
assert_eq!(u64::from_le_bytes(value), size, "{:?}", constant.key);
local.push(constant.key);
}
assert!(local.contains(&SpecKey::FlatLocalSize), "{local:?}");
}
/// A kernel with an explicit imageblock, whose extent Metal's encoder must set, is created from
/// the region of one threadgroup of 32 threads with an imageblock of one cell per thread, 32 by
/// 1, not refused for the encoder's default of 0 by 0.
#[test]
fn an_imageblock_kernel_row_is_created_with_one_cell_per_thread() {
let bitcode = match llvm_assemble(&engine_dir().join("a4_imageblock_extent.ll")) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => {
panic!("llvm-as rejected a4_imageblock_extent.ll: {why}")
}
};
let device = crate::engine::load_device("moltenvk-m3").unwrap();
let compiled = compile_row(
&bitcode,
"a4_imageblock_extent",
RowStage::Kernel,
Projection::Derived,
&device,
None,
);
let RowCompile::Compiled(row) = compiled else {
panic!("a4_imageblock_extent: {compiled:?}");
};
let RowPipeline::Compute { pipeline, creation } = *row else {
panic!("a kernel row is a compute pipeline");
};
let Dispatch::Threadgroups {
threads_per_group, ..
} = creation.dispatch
else {
panic!("{:?}", creation.dispatch);
};
let width = threads_per_group[0];
assert_eq!(
creation.imageblock,
Some(metal2vulkan::bind::ImageblockSize::new(width, 1))
);
let mut extent = Vec::new();
for constant in &pipeline.stage.specialization.constants {
let want = match constant.key {
SpecKey::ImageblockWidth => u64::from(width),
SpecKey::ImageblockHeight => 1,
_ => continue,
};
let specialization = &creation.region.specialization;
let entry = specialization
.entries
.iter()
.find(|entry| entry.constant_id == constant.id)
.unwrap_or_else(|| panic!("the region does not specialize {:?}", constant.key));
let at = entry.offset as usize;
let bytes = &specialization.data[at..at + entry.size as usize];
let mut value = [0u8; 8];
value[..bytes.len()].copy_from_slice(bytes);
assert_eq!(u64::from_le_bytes(value), want, "{:?}", constant.key);
extent.push(constant.key);
}
assert_eq!(
extent.len(),
2,
"the stage specializes the imageblock's extent: {extent:?}"
);
}
/// A binder error for the representative dispatch is a documented refusal only when it is the
/// product's typed `Unsupported`; a binder defect or a rejected state is not, so it fails the
/// sweep instead of counting as a tool limit.
#[test]
fn only_a_typed_unsupported_binder_error_is_a_documented_refusal() {
use metal2vulkan::error::{BindError, Feature, InternalError, InternalKind, Unsupported};
let refused = BindError::Unsupported(Unsupported::not_implemented(Feature::Imageblocks));
let answer = BinderAnswer::of(&refused, "plan".into());
assert!(answer.documented, "{answer:?}");
assert!(answer.detail.starts_with("plan: "), "{answer:?}");
for error in [
BindError::Internal(InternalError::new(
InternalKind::Invariant,
"a binder defect",
)),
BindError::InvalidImageblockSize {
width: 0,
height: 0,
},
BindError::MissingStageInRegion,
] {
assert!(
!BinderAnswer::of(&error, "plan".into()).documented,
"{error:?}"
);
}
}
#[test]
fn threadgroup_widths_are_whole_simdgroups_within_the_pipelines_most_threads() {
assert_eq!(widths(32, 128).collect::<Vec<_>>(), [32, 64, 96, 128]);
assert_eq!(widths(32, 32).collect::<Vec<_>>(), [32]);
// A pipeline that allows fewer threads than one simdgroup tries those.
assert_eq!(widths(32, 16).collect::<Vec<_>>(), [16]);
assert_eq!(widths(32, 0).collect::<Vec<_>>(), [1]);
}
}
@@ -80,9 +80,6 @@ pub enum UnmodelledKind {
/// A kernel stage input: a location that is not a constant, or an IR type no format reads
/// exactly (`executor_contract::stage_inputs::implied`).
StageInput,
/// A kernel's representative dispatch: no region the binder plans for the encoder's
/// defaults runs on the row as compiled (`acceptance::dispatch`).
Dispatch,
/// An object or mesh function: the derivation builds no mesh render pipeline around it yet.
MeshPipeline,
}
@@ -97,7 +94,6 @@ impl UnmodelledKind {
UnmodelledKind::Attachment => "attachment",
UnmodelledKind::Companion => "companion",
UnmodelledKind::StageInput => "stage_input",
UnmodelledKind::Dispatch => "dispatch",
UnmodelledKind::MeshPipeline => "mesh_pipeline",
}
}
@@ -1,5 +1,5 @@
//! Whole-corpus driver acceptance: does the Vulkan driver accept the pipeline we produce? Nothing
//! is bound, nothing is dispatched, nothing is read back.
//! is bound or submitted, nothing is read back.
//!
//! That question has no other asker in this repository. `spirv-val` checks the module against the
//! SPIR-V specification; the authored cases put a real pipeline on the device but reach only a
@@ -9,24 +9,26 @@
//! It runs the engine: `--profile P` compiles every kernel (compute pipeline), vertex function
//! (rasterization-disabled render pipeline, with a vertex descriptor for the attributes it
//! declares), and fragment function (drawn with its generated passthrough vertex companion into
//! the attachments its outputs imply) with the engine's public compile API for profile P
//! (`acceptance::row`), and creates the pipeline from the **binder layout the artifact carries**
//! (set layouts, push ranges, specialization, subgroup size, vertex input, graphics state). A
//! kernel is created from the region the binder plans for one representative dispatch, a
//! threadgroup of whole simdgroups (its specialization, stage flags, and required subgroup size,
//! and a representative imageblock extent of one cell per thread where it has an explicit
//! imageblock; `acceptance::dispatch`), as the executors create it, never at its stage's
//! placeholder local size. The binder's typed refusal of that dispatch is `BIND_REFUSED`,
//! counted; any other binder error is `BIND_ERROR` and fails the sweep. A render row's stages are
//! created at their default specialization, not the graphics plan's (a limit). A fragment
//! function's attachments have no more channels than its outputs write. It times each
//! `vkCreate*Pipelines` (`budgets::CreationClock`: its wall time less its thread's wait for a
//! CPU), with the drivers' shader disk caches off (`budgets::turn_driver_shader_caches_off`); a
//! creation above 5 s is a bug. A row's detail
//! prints its own stage's module words, which are what the translation sweep (`corpus-triage
//! --audit translation`) counts for it, a render row's other stages' apart as `companion_words`,
//! and a kernel's representative imageblock extent as `imageblock=WxH`, then the pipeline's
//! precision notes as `precision=[...]`. `--driver-caches-on` leaves the drivers' shader disk caches as the environment sets
//! the attachments its outputs imply) with the engine's public compile API for profile P
//! (`acceptance::row`). A render row's pipeline is created from the **binder layout the artifact
//! carries** (set layouts, push ranges, specialization, subgroup size, vertex input, graphics
//! state), its stages at their default specialization, not the graphics plan's (a limit). A
//! fragment function's attachments have no more channels than its outputs write. A kernel row is
//! made as a guest's kernel is, through the runtime (`candidate::create_runtime_kernel`): its
//! `ComputePipelineState` on the sweep's device, with the row's function-constant values, and one
//! dispatch of one representative threadgroup (the state's thread execution width of threads, or
//! its `maxTotalThreadsPerThreadgroup` where fewer) encoded into a command buffer that is never
//! committed, so the runtime asks the driver for the pipeline that threadgroup runs on. The
//! runtime's typed refusal (the translator's, a known gap, a device limit) is `RUNTIME_REFUSED`,
//! counted; a kernel that writes no memory, whose dispatch the runtime runs as Metal's without
//! effects and makes no pipeline for, is `NO_EFFECT`, counted. The make runs in this process,
//! held to the per-attempt ceilings, after the row's compile worker compiled it within them. It
//! times each `vkCreate*Pipelines` (`budgets::CreationClock`: its wall time less its thread's wait
//! for a CPU; a kernel's, the runtime's own count of its pipeline creation), with the drivers'
//! shader disk caches off (`budgets::turn_driver_shader_caches_off`); a creation above 5 s is a
//! bug. A row's detail prints its own stage's module words, which are what the translation sweep
//! (`corpus-triage --audit translation`) counts for it, a render row's other stages' apart as
//! `companion_words`, then the pipeline's precision notes as `precision=[...]`. `--driver-caches-on` leaves the drivers' shader disk caches as the environment sets
//! them, so a creation may hit what an earlier process compiled: run twice, the second run times
//! the warm creation a program's later launches see, beside the cold one the ceiling times (the
//! summary's `driver_caches`). `--keep-modules DIR` writes each compiled row's stage modules,
@@ -74,15 +76,13 @@
//! reports a message about the device, before the loader reads it again (in `vkDestroyDevice` at
//! exit, where a run faulted after its summary before; `candidate::platform::loader_word`).
use metal2vulkan::bind::ImageblockSize;
use metal2vulkan::library::FunctionConstantValues;
use metal2vulkan::pipeline::PrecisionNote;
use metal2vulkan_validation::acceptance::dispatch::BinderAnswer;
use metal2vulkan_validation::acceptance::metal_report::MetalCompileFailure;
use metal2vulkan_validation::acceptance::row::UnmodelledKind;
use metal2vulkan_validation::acceptance::{
compile_draw_in_worker, compile_row_in_worker, Acceptance, AcceptanceError, Projection,
RowCompile, RowPipeline, RowStage,
RowCompile, RowPipeline, RowStage, RuntimeRow,
};
use metal2vulkan_validation::budgets::PIPELINE_CREATION_CEILING;
use metal2vulkan_validation::candidate::engine::graphics::RenderTemplate;
@@ -554,15 +554,12 @@ fn set_label(set: &Specialization) -> String {
/// module `corpus-triage --audit translation` compiles for the row and counts; then
/// `companion_words=M` when the pipeline has other stages (a fragment row's generated passthrough
/// vertex companion, a post-tessellation vertex row's synthesized stages), which the translation
/// sweep does not compile; then `imageblock=WxH` for a kernel with an explicit imageblock, the
/// representative extent its pipeline was created with (`acceptance::dispatch`): another extent is
/// another specialization, which can be refused where this one is created; then `precision=[...]`
/// when any stage of the pipeline carries a precision note.
/// sweep does not compile; then `precision=[...]` when any stage of the pipeline carries a
/// precision note.
#[derive(Clone, Debug, PartialEq, Eq)]
struct RowDetail {
own: u64,
companion: u64,
imageblock: Option<ImageblockSize>,
precision: Vec<PrecisionNote>,
}
@@ -571,10 +568,6 @@ impl RowDetail {
RowDetail {
own: pipeline.words(),
companion: pipeline.companion_words(),
imageblock: match pipeline {
RowPipeline::Compute { creation, .. } => creation.imageblock,
RowPipeline::Render { .. } => None,
},
precision: pipeline.precision_notes(),
}
}
@@ -586,9 +579,6 @@ impl std::fmt::Display for RowDetail {
if self.companion > 0 {
write!(f, " companion_words={}", self.companion)?;
}
if let Some(extent) = self.imageblock {
write!(f, " imageblock={}x{}", extent.width, extent.height)?;
}
if !self.precision.is_empty() {
write!(f, " precision={:?}", self.precision)?;
}
@@ -610,11 +600,11 @@ struct Tally {
unmodelled: usize,
/// The `UNMODELLED` rows by kind (`acceptance::row::UnmodelledKind`).
unmodelled_kinds: BTreeMap<UnmodelledKind, usize>,
/// Kernel rows the binder refused to bind for the representative dispatch with a typed
/// refusal the product documents (`BIND_REFUSED`).
bind_refused: usize,
/// Kernel rows the binder answered with any other error (`BIND_ERROR`), which fail the sweep.
bind_errors: usize,
/// Kernel rows the runtime refused with its typed error (`RUNTIME_REFUSED`).
runtime_refused: usize,
/// Kernel rows whose dispatch the runtime ran without effects, making no pipeline
/// (`NO_EFFECT`).
no_effect: usize,
stage_not_covered: usize,
no_bitcode: usize,
tooling: usize,
@@ -674,6 +664,14 @@ impl Tally {
self.invalid_usage += 1;
Ok(("INVALID_USAGE", messages.join(" | "), 0))
}
Ok(Acceptance::RuntimeRefused(why)) => {
self.runtime_refused += 1;
Ok(("RUNTIME_REFUSED", why, 0))
}
Ok(Acceptance::NoEffect) => {
self.no_effect += 1;
Ok(("NO_EFFECT", detail.to_string(), 0))
}
Err(AcceptanceError::Unmodelled(why)) => {
self.tooling += 1;
Ok(("TOOLING", why, 0))
@@ -688,20 +686,6 @@ impl Tally {
}
}
/// Count the binder's error for a kernel row's representative dispatch and return its
/// `(STATUS, detail, create_ms)`: a typed refusal the product documents is `BIND_REFUSED`,
/// which the sweep counts; any other binder error is `BIND_ERROR`, which fails it through
/// [`Tally::verdict`].
fn binder(&mut self, answer: BinderAnswer) -> (&'static str, String, u128) {
if answer.documented {
self.bind_refused += 1;
("BIND_REFUSED", answer.detail, 0)
} else {
self.bind_errors += 1;
("BIND_ERROR", answer.detail, 0)
}
}
/// The class column of a row whose result is `status` with `detail`: the Metal compile step
/// that failed, read from MoltenVK's report of a refused or invalid-usage row and counted, or
/// `-`.
@@ -744,28 +728,21 @@ impl Tally {
}
/// Whether the sweep passed: no refusal, no creation above the ceiling, no message from the
/// validation layer, no compile the worker boundary stopped, no binder error other than a
/// typed refusal the product documents, and no tooling error other than a modelled limit (of
/// the row's inputs or of the creation path).
/// validation layer, no compile the worker boundary stopped, and no tooling error other than
/// a modelled limit (of the row's inputs or of the creation path).
fn verdict(&self) -> Result<(), String> {
if self.refused
+ self.over_ceiling
+ self.invalid_usage
+ self.errors
+ self.worker_stopped
+ self.bind_errors
if self.refused + self.over_ceiling + self.invalid_usage + self.errors + self.worker_stopped
> 0
{
return Err(format!(
"{} pipelines refused, {} created above the {} s ceiling, {} reported by the \
validation layer, {} compiles stopped at the worker boundary, {} binder errors, \
and {} tooling errors",
validation layer, {} compiles stopped at the worker boundary, and {} tooling \
errors",
self.refused,
self.over_ceiling,
PIPELINE_CREATION_CEILING.as_secs(),
self.invalid_usage,
self.worker_stopped,
self.bind_errors,
self.errors
));
}
@@ -929,7 +906,7 @@ fn sweep_new(
.as_ref()
.map_or_else(|| "none".to_string(), |listed| listed.0.len().to_string());
eprintln!(
"corpus-pipeline-summary\tengine=new\tprofile={profile}\tprofiles_layer={}\tprojection={projection:?}\tdevice_type={}\trows={}\tcompiled_only={}\tcreated={}\trefused={}\tnot_enabled={}\tnot_compiled={}\tunmodelled={}\tunmodelled_kinds={unmodelled_kinds}\tbind_refused={}\tbind_errors={}\tstage_not_covered={}\tno_bitcode={}\ttooling={}\terrors={}\tcreation_over_ceiling={}\tinvalid_usage={}\tworker_stopped={}\tmetal_failures={metal_failures}\tpartition={partition}\tslowest_creation={slowest_key}\tslowest_creation_ms={slowest_ms}\tslowest_compile={slowest_compile_key}\tslowest_compile_ms={slowest_compile_ms}\tpeak_compile_rss={peak_rss_key}\tpeak_compile_rss_bytes={peak_rss}\tpeak_compile_allocator={peak_allocator_key}\tpeak_compile_allocator_bytes={peak_allocator}\tdriver_caches={}\tspecializations={specializations}\tdraws={draws}",
"corpus-pipeline-summary\tengine=new\tprofile={profile}\tprofiles_layer={}\tprojection={projection:?}\tdevice_type={}\trows={}\tcompiled_only={}\tcreated={}\trefused={}\tnot_enabled={}\tnot_compiled={}\tunmodelled={}\tunmodelled_kinds={unmodelled_kinds}\truntime_refused={}\tno_effect={}\tstage_not_covered={}\tno_bitcode={}\ttooling={}\terrors={}\tcreation_over_ceiling={}\tinvalid_usage={}\tworker_stopped={}\tmetal_failures={metal_failures}\tpartition={partition}\tslowest_creation={slowest_key}\tslowest_creation_ms={slowest_ms}\tslowest_compile={slowest_compile_key}\tslowest_compile_ms={slowest_compile_ms}\tpeak_compile_rss={peak_rss_key}\tpeak_compile_rss_bytes={peak_rss}\tpeak_compile_allocator={peak_allocator_key}\tpeak_compile_allocator_bytes={peak_allocator}\tdriver_caches={}\tspecializations={specializations}\tdraws={draws}",
options.profiles_layer.as_deref().unwrap_or("none"),
device.map_or("none", DeviceType::as_str),
tally.rows,
@@ -939,8 +916,8 @@ fn sweep_new(
tally.not_enabled,
tally.not_compiled,
tally.unmodelled,
tally.bind_refused,
tally.bind_errors,
tally.runtime_refused,
tally.no_effect,
tally.stage_not_covered,
tally.no_bitcode,
tally.tooling,
@@ -956,8 +933,9 @@ fn sweep_new(
tally.verdict()
}
/// Compile one row in a compile worker and create its pipeline: `(STATUS, detail, create_ms)`.
/// With `keep`, the compiled row's stage modules are written there first ([`keep_modules`]).
/// Compile one row in a compile worker and create its pipeline (a kernel row's, made through the
/// runtime from the row's AIR): `(STATUS, detail, create_ms)`. With `keep`, the compiled row's
/// stage modules are written there first ([`keep_modules`]).
fn attempt_row(
device: Option<DeviceType>,
worker: &CompileWorker,
@@ -968,18 +946,19 @@ fn attempt_row(
tally: &mut Tally,
) -> Result<(&'static str, String, u128), String> {
let key = row.key.as_str();
let (compiled, measured) = match &row.what {
let constants = match &row.what {
RowWork::Function {
input,
specialization,
} => {
specialization: Some(set),
..
} => set.values(),
_ => FunctionConstantValues::defaults(),
};
let (compiled, measured) = match &row.what {
RowWork::Function { input, .. } => {
let Ok(stage) = RowStage::parse(&row.stage) else {
tally.stage_not_covered += 1;
return Ok(("STAGE_NOT_COVERED", format!("stage {}", row.stage), 0));
};
let constants = specialization
.as_ref()
.map_or_else(FunctionConstantValues::defaults, Specialization::values);
compile_row_in_worker(
worker,
compiler,
@@ -1044,7 +1023,6 @@ fn attempt_row(
*tally.unmodelled_kinds.entry(why.kind).or_default() += 1;
return Ok(("UNMODELLED", why.to_string(), 0));
}
RowCompile::Binder(answer) => return Ok(tally.binder(answer)),
};
if let Some(dir) = keep {
keep_modules(dir, key, &pipeline)?;
@@ -1054,7 +1032,31 @@ fn attempt_row(
tally.compiled += 1;
return Ok(("COMPILED", detail.to_string(), 0));
};
let result = metal2vulkan_validation::candidate::create_acceptance_pipeline(device, &pipeline);
let result = match (&*pipeline, &row.what) {
(RowPipeline::Render { pipeline, .. }, _) => {
metal2vulkan_validation::candidate::create_acceptance_pipeline(device, pipeline)
}
(RowPipeline::Compute { .. }, RowWork::Function { input, .. }) => {
let bitcode = match input.source.bitcode() {
Ok(bitcode) => bitcode,
Err(error) => {
tally.errors += 1;
return Ok(("ERROR", format!("the row's bitcode: {error}"), 0));
}
};
let kernel = RuntimeRow {
bitcode: &bitcode,
entry: &input.entry,
constants: &constants,
};
metal2vulkan_validation::candidate::create_runtime_kernel(device, &kernel)
}
(RowPipeline::Compute { .. }, RowWork::Draw { .. }) => {
return Err(format!(
"{key}: a logged draw compiled to a compute pipeline"
));
}
};
tally.record(key, detail, result)
}
@@ -1166,20 +1168,17 @@ mod tests {
const DETAIL: RowDetail = RowDetail {
own: 7,
companion: 0,
imageblock: None,
precision: Vec::new(),
};
/// A row's detail prints its own stage's words, what the translation sweep counts for it, the
/// other stages' apart, and the representative imageblock extent a kernel with an explicit
/// imageblock was created with.
/// A row's detail prints its own stage's words, what the translation sweep counts for it, and
/// the other stages' apart.
#[test]
fn a_rows_detail_is_its_own_stage_words_its_companions_and_its_imageblock_extent() {
fn a_rows_detail_is_its_own_stage_words_and_its_companions() {
assert_eq!(DETAIL.to_string(), "words=7");
let fragment = RowDetail {
own: 1148,
companion: 276,
imageblock: None,
precision: Vec::new(),
};
assert_eq!(fragment.to_string(), "words=1148 companion_words=276");
@@ -1193,18 +1192,6 @@ mod tests {
.record("fragment", fragment.clone(), created())
.unwrap();
assert_eq!(detail, "words=1148 companion_words=276");
let imageblock = RowDetail {
own: 412,
companion: 0,
imageblock: Some(ImageblockSize::new(32, 1)),
precision: Vec::new(),
};
assert_eq!(imageblock.to_string(), "words=412 imageblock=32x1");
let (status, detail, _) = tally.record("imageblock", imageblock, created()).unwrap();
assert_eq!(
(status, detail.as_str()),
("OK", "words=412 imageblock=32x1")
);
// A pipeline whose stages carry precision notes names them.
let noted = RowDetail {
precision: vec![PrecisionNote::DeviceArithmetic],
@@ -1285,29 +1272,30 @@ mod tests {
.starts_with("line 1"));
}
/// The binder's typed refusal for a kernel row's representative dispatch is counted and passes;
/// any other binder error fails the sweep.
/// The runtime's typed refusal of a kernel row and a kernel row it makes no pipeline for are
/// counted and pass; the driver's refusal of the pipeline it asks for fails the sweep.
#[test]
fn a_documented_binder_refusal_is_counted_and_any_other_binder_error_fails_the_sweep() {
fn a_runtime_refusal_and_a_kernel_without_effects_are_counted_and_pass() {
let mut tally = Tally::default();
let (status, detail, _) = tally.binder(BinderAnswer {
documented: true,
detail: "plan for a threadgroup of 32: Unsupported(..)".into(),
});
assert_eq!(status, "BIND_REFUSED");
assert!(
detail.starts_with("plan for a threadgroup of 32"),
"{detail}"
);
assert_eq!((tally.bind_refused, tally.bind_errors), (1, 0));
let refusal = "unsupported: the state's imageblock length is not measured against Metal's";
let (status, detail, _) = tally
.record(
"gap",
DETAIL,
Ok(Acceptance::RuntimeRefused(refusal.into())),
)
.unwrap();
assert_eq!((status, detail.as_str()), ("RUNTIME_REFUSED", refusal));
let (status, detail, _) = tally
.record("still", DETAIL, Ok(Acceptance::NoEffect))
.unwrap();
assert_eq!((status, detail.as_str()), ("NO_EFFECT", "words=7"));
assert_eq!((tally.runtime_refused, tally.no_effect), (1, 1));
assert!(tally.verdict().is_ok());
let (status, _, _) = tally.binder(BinderAnswer {
documented: false,
detail: "instantiate a threadgroup of 32: Internal(..)".into(),
});
assert_eq!(status, "BIND_ERROR");
assert_eq!((tally.bind_refused, tally.bind_errors), (1, 1));
assert!(tally.verdict().unwrap_err().contains("1 binder errors"));
tally
.record("refused", DETAIL, Ok(Acceptance::Refused("no".into())))
.unwrap();
assert!(tally.verdict().unwrap_err().contains("1 pipelines refused"));
}
#[test]
@@ -21,15 +21,25 @@ pub mod exit_status {
pub const VENUE_MISMATCH: i32 = 7;
}
/// Create an engine pipeline on `device` from the binder layout its artifact carries, time
/// the creation, and destroy it. Nothing is bound or dispatched.
/// Create a render row's pipeline on `device` from the binder layout its artifact carries, time
/// the creation, and destroy it. Nothing is bound or drawn.
pub fn create_acceptance_pipeline(
device: DeviceType,
pipeline: &crate::acceptance::RowPipeline,
pipeline: &metal2vulkan::pipeline::RenderPipeline,
) -> Result<crate::acceptance::Acceptance, crate::acceptance::AcceptanceError> {
platform::create_acceptance_pipeline(device, pipeline)
}
/// Make a kernel row's pipeline state through the runtime on `device`, as a guest's kernel is
/// made, and encode one dispatch of one representative threadgroup of it, never committed, under
/// the validation layer: what the runtime and the driver answered.
pub fn create_runtime_kernel(
device: DeviceType,
row: &crate::acceptance::RuntimeRow<'_>,
) -> Result<crate::acceptance::Acceptance, crate::acceptance::AcceptanceError> {
platform::create_runtime_kernel(device, row)
}
/// Restrict every Vulkan context this process opens to committed device profile `stem` through
/// `VK_LAYER_KHRONOS_profiles` (a command's `--profiles-layer P`). Call it once, before any device
/// opens. Each restricted context checks that the device has the profile and reports exactly it
@@ -122,7 +132,16 @@ mod platform {
pub fn create_acceptance_pipeline(
_device: DeviceType,
_pipeline: &crate::acceptance::RowPipeline,
_pipeline: &metal2vulkan::pipeline::RenderPipeline,
) -> Result<crate::acceptance::Acceptance, crate::acceptance::AcceptanceError> {
Err(crate::acceptance::AcceptanceError::DeviceUnavailable(
"pipeline creation is supported only on Linux and macOS".into(),
))
}
pub fn create_runtime_kernel(
_device: DeviceType,
_row: &crate::acceptance::RuntimeRow<'_>,
) -> Result<crate::acceptance::Acceptance, crate::acceptance::AcceptanceError> {
Err(crate::acceptance::AcceptanceError::DeviceUnavailable(
"pipeline creation is supported only on Linux and macOS".into(),
@@ -14,6 +14,7 @@ mod plan_resources;
mod profiles;
mod render;
mod runtime;
mod runtime_acceptance;
mod runtime_bounds;
mod runtime_depth;
mod runtime_multisample;
@@ -29,6 +30,7 @@ pub use device::{capture_formats, echo_validation_messages, venue_check};
pub use profiles::{requested_restriction, restrict_devices_to};
pub use render::execute_engine_render;
pub use runtime::execute_runtime;
pub use runtime_acceptance::create_runtime_kernel;
pub use runtime_probe::probe_runtime;
pub use runtime_render::execute_runtime_render;
@@ -1,5 +1,5 @@
//! Driver acceptance (L4): create an engine pipeline from the binder layout its artifact
//! carries, time `vkCreate*Pipelines`, and destroy everything. Nothing is bound, recorded, or
//! Driver acceptance (L4) of a render row: create its pipeline from the binder layout its
//! artifact carries, time `vkCreateGraphicsPipelines`, and destroy everything. Nothing is bound, recorded, or
//! submitted, so no shader executes. The context runs under `VK_LAYER_KHRONOS_validation`; any
//! message it reports makes the row [`Acceptance::InvalidUsage`]. The layout half
//! ([`LayoutObjects`], [`unmet_requirements`]) is shared with the engine executors, and a
@@ -7,20 +7,16 @@
//! the render executor's own builder ([`super::graphics_pipeline`]): its render pass from the
//! graphics state (color, framebuffer-fetch, and depth/stencil attachments), its vertex input
//! (divisors, dynamic strides), and every dynamic state it declares, at each stage's default
//! specialization, the compiled topology, and Metal's default depth-stencil state. A compute
//! pipeline is created from the dispatch region the binder plans for the row's representative
//! dispatch (its specialization, stage flags, and required subgroup size), as the executors create
//! each region's pipeline, never at the stage's placeholder defaults.
//! specialization, the compiled topology, and Metal's default depth-stencil state. A kernel row
//! is made through the runtime instead (`runtime_acceptance`).
use super::device::{with_validated_context, VulkanContext};
use super::graphics_pipeline::{self, GraphicsError};
use crate::acceptance::{Acceptance, AcceptanceError, RowPipeline};
use crate::acceptance::{Acceptance, AcceptanceError};
use crate::gpu::DeviceType;
use ash::vk;
use metal2vulkan::bind::DispatchRegion;
use metal2vulkan::device::Requirements;
use metal2vulkan::pipeline::{PipelineLayout, StageModule};
use std::ffi::CString;
use metal2vulkan::pipeline::{PipelineLayout, RenderPipeline, StageModule};
/// The descriptor-set layouts (with their immutable samplers) and the pipeline layout of one
/// binder `PipelineLayout`, destroyed on every exit path, and what a pool that allocates one set
@@ -84,7 +80,7 @@ impl Drop for Objects<'_> {
/// through `with_validated_context`'s error.
pub fn create_acceptance_pipeline(
device: DeviceType,
pipeline: &RowPipeline,
pipeline: &RenderPipeline,
) -> Result<Acceptance, AcceptanceError> {
with_validated_context(device, |context| {
let created = create(context, pipeline);
@@ -127,13 +123,13 @@ pub(super) fn unmet_requirements(
missing
}
fn create(context: &VulkanContext, pipeline: &RowPipeline) -> Result<Acceptance, AcceptanceError> {
let stages = pipeline.stages();
let layout = match pipeline {
RowPipeline::Compute { pipeline, .. } => &pipeline.layout,
RowPipeline::Render { pipeline, .. } => &pipeline.layout,
};
let missing = unmet_requirements(context, pipeline.requirements());
fn create(
context: &VulkanContext,
pipeline: &RenderPipeline,
) -> Result<Acceptance, AcceptanceError> {
let stages = &pipeline.stages;
let layout = &pipeline.layout;
let missing = unmet_requirements(context, &pipeline.requirements);
if !missing.is_empty() {
return Ok(Acceptance::NotEnabled(missing));
}
@@ -161,188 +157,67 @@ fn create(context: &VulkanContext, pipeline: &RowPipeline) -> Result<Acceptance,
}
}
}
let entries = stages
.iter()
.map(|stage| {
CString::new(stage.entry_point.as_str())
.map_err(|_| AcceptanceError::Tooling("entry point name contains NUL".into()))
})
.collect::<Result<Vec<_>, _>>()?;
let created = stage_creations(pipeline);
let specializations: Vec<(Vec<vk::SpecializationMapEntry>, Vec<u8>)> = created
.iter()
.map(|stage| (stage.map.clone(), stage.data.clone()))
.collect();
let spec_infos: Vec<vk::SpecializationInfo<'_>> = specializations
.iter()
.map(|(map, data)| {
vk::SpecializationInfo::default()
.map_entries(map)
.data(data)
})
.collect();
let mut subgroup_sizes: Vec<vk::PipelineShaderStageRequiredSubgroupSizeCreateInfo<'_>> =
created
.iter()
.map(|stage| {
vk::PipelineShaderStageRequiredSubgroupSizeCreateInfo::default()
.required_subgroup_size(stage.required_subgroup_size.unwrap_or(0))
})
.collect();
let mut stage_infos = Vec::with_capacity(stages.len());
for ((((stage, module), entry), (spec, subgroup)), creation) in stages
.iter()
.zip(&objects.modules)
.zip(&entries)
.zip(spec_infos.iter().zip(subgroup_sizes.iter_mut()))
.zip(&created)
{
let mut info = vk::PipelineShaderStageCreateInfo::default()
.stage(stage.stage.into())
.module(*module)
.name(entry)
.flags(creation.flags);
if !creation.map.is_empty() {
info = info.specialization_info(spec);
}
if creation.required_subgroup_size.is_some() {
info = info.push_next(subgroup);
}
stage_infos.push(info);
}
let result = match pipeline {
RowPipeline::Compute { .. } => {
let info = vk::ComputePipelineCreateInfo::default()
.stage(stage_infos[0])
.layout(objects.layout.pipeline_layout);
let clock = crate::budgets::CreationClock::start();
// SAFETY: every handle in `info` is live; the result is destroyed with `objects`.
let created = unsafe {
context
.device
.create_compute_pipelines(vk::PipelineCache::null(), &[info], None)
};
(created.map_err(|(_, error)| error), clock.read())
}
RowPipeline::Render { pipeline: p, .. } => {
let unmodelled_or_refused = |error: GraphicsError| match error {
GraphicsError::Unmodelled(why) => Err(AcceptanceError::Unmodelled(why)),
GraphicsError::NotSupported(why) => Ok(Acceptance::NotEnabled(vec![why])),
GraphicsError::Refused(why) => Ok(Acceptance::Refused(why)),
};
if let Err(error) = graphics_pipeline::attachable_depth_stencil_format(
&context.instance,
context.physical,
&p.graphics,
) {
return unmodelled_or_refused(error);
}
objects.render_pass =
match graphics_pipeline::create_render_pass(&context.device, &p.graphics) {
Ok(render_pass) => render_pass,
Err(error) => return unmodelled_or_refused(error),
};
let created = graphics_pipeline::create_graphics_pipeline(
&context.device,
context.executes_moltenvk(),
p,
&graphics_pipeline::Consumer {
modules: &objects.modules,
specializations: &specializations,
layout: objects.layout.pipeline_layout,
render_pass: objects.render_pass,
topology: p.graphics.topology.into(),
// The class's list topology, which Metal never restarts.
primitive_restart: false,
depth_stencil: graphics_pipeline::metal_default_depth_stencil(),
// The encoder's defaults: no culling, clockwise front faces.
cull_mode: vk::CullModeFlags::NONE,
front_face: super::METAL_DEFAULT_FRONT_FACE,
},
);
return match created {
Ok((created, create)) => {
objects.pipeline = created;
Ok(Acceptance::Created { create })
}
Err(error) => unmodelled_or_refused(error),
};
}
let specializations: Vec<_> = stages.iter().map(default_specialization).collect();
let unmodelled_or_refused = |error: GraphicsError| match error {
GraphicsError::Unmodelled(why) => Err(AcceptanceError::Unmodelled(why)),
GraphicsError::NotSupported(why) => Ok(Acceptance::NotEnabled(vec![why])),
GraphicsError::Refused(why) => Ok(Acceptance::Refused(why)),
};
match result {
(Ok(pipelines), create) => {
objects.pipeline = pipelines.first().copied().unwrap_or_default();
if let Err(error) = graphics_pipeline::attachable_depth_stencil_format(
&context.instance,
context.physical,
&pipeline.graphics,
) {
return unmodelled_or_refused(error);
}
objects.render_pass =
match graphics_pipeline::create_render_pass(&context.device, &pipeline.graphics) {
Ok(render_pass) => render_pass,
Err(error) => return unmodelled_or_refused(error),
};
let created = graphics_pipeline::create_graphics_pipeline(
&context.device,
context.executes_moltenvk(),
pipeline,
&graphics_pipeline::Consumer {
modules: &objects.modules,
specializations: &specializations,
layout: objects.layout.pipeline_layout,
render_pass: objects.render_pass,
topology: pipeline.graphics.topology.into(),
// The class's list topology, which Metal never restarts.
primitive_restart: false,
depth_stencil: graphics_pipeline::metal_default_depth_stencil(),
// The encoder's defaults: no culling, clockwise front faces.
cull_mode: vk::CullModeFlags::NONE,
front_face: super::METAL_DEFAULT_FRONT_FACE,
},
);
match created {
Ok((created, create)) => {
objects.pipeline = created;
Ok(Acceptance::Created { create })
}
(Err(error), _) => Ok(Acceptance::Refused(format!("create pipeline: {error}"))),
Err(error) => unmodelled_or_refused(error),
}
}
/// How each stage of `pipeline` is created: a compute row's one stage from the region the binder
/// plans for its representative dispatch, as the executors create each region's pipeline, never at
/// the stage's placeholder defaults (with which a stage whose simd tier requires full subgroups has
/// a local size of 1, `VUID-VkPipelineShaderStageCreateInfo-flags-02759`); a render row's stages at
/// their defaults.
fn stage_creations(pipeline: &RowPipeline) -> Vec<StageCreation> {
match pipeline {
RowPipeline::Compute { creation, .. } => vec![StageCreation::of_region(&creation.region)],
RowPipeline::Render { .. } => pipeline
.stages()
.iter()
.map(StageCreation::defaults)
.collect(),
}
}
/// How one stage is created: its specialization map and data, its create flags, and the subgroup
/// size it requires.
struct StageCreation {
map: Vec<vk::SpecializationMapEntry>,
data: Vec<u8>,
flags: vk::PipelineShaderStageCreateFlags,
required_subgroup_size: Option<u32>,
}
impl StageCreation {
/// A compute stage as the binder's dispatch `region` creates it: the region's specialization
/// (the plan's constants, the local size, `MultiRegion`), stage flags, and required subgroup
/// size.
fn of_region(region: &DispatchRegion) -> StageCreation {
StageCreation {
map: region
.specialization
.entries
.iter()
.map(|&entry| entry.into())
.collect(),
data: region.specialization.data.clone(),
flags: region.stage_flags.into(),
required_subgroup_size: region.required_subgroup_size,
}
}
/// A render stage at its defaults: every constant at its default value, packed in id order,
/// with the stage's own flags and subgroup size.
fn defaults(stage: &StageModule) -> StageCreation {
let mut map = Vec::new();
let mut data = Vec::new();
for constant in &stage.specialization.constants {
let size = constant.size.min(8) as usize;
map.push(
vk::SpecializationMapEntry::default()
.constant_id(constant.id)
.offset(data.len() as u32)
.size(size),
);
data.extend_from_slice(&constant.default.to_le_bytes()[..size]);
}
StageCreation {
map,
data,
flags: stage.stage_flags.into(),
required_subgroup_size: stage.required_subgroup_size,
}
/// A render stage's specialization at its defaults: its map and data, every constant at its
/// default value, packed in id order.
fn default_specialization(stage: &StageModule) -> (Vec<vk::SpecializationMapEntry>, Vec<u8>) {
let mut map = Vec::new();
let mut data = Vec::new();
for constant in &stage.specialization.constants {
let size = constant.size.min(8) as usize;
map.push(
vk::SpecializationMapEntry::default()
.constant_id(constant.id)
.offset(data.len() as u32)
.size(size),
);
data.extend_from_slice(&constant.default.to_le_bytes()[..size]);
}
(map, data)
}
/// Why [`LayoutObjects::create`] made no layout.
@@ -499,8 +374,7 @@ fn create_layouts(objects: &mut LayoutObjects<'_>, layout: &PipelineLayout) -> R
#[cfg(test)]
mod tests {
use super::{pool_requirements, stage_creations, StageCreation};
use crate::acceptance::{compile_row, Projection, RowCompile, RowPipeline, RowStage};
use super::pool_requirements;
use crate::candidate::engine::tests::{assemble, counting_kernel};
use ash::vk;
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
@@ -609,96 +483,4 @@ mod tests {
assert!(!sizes.is_empty());
assert!(sizes.iter().all(|size| size.descriptor_count > 0));
}
/// A kernel row's one stage is created with exactly the specialization map and data, stage
/// flags, and required subgroup size of the region the binder plans for its representative
/// dispatch, which are not the stage's defaults: on `moltenvk-m3`, `simd_shuffle_k`'s simd tier
/// requires full subgroups, which its defaults' local size of 1 violates
/// (`VUID-VkPipelineShaderStageCreateInfo-flags-02759`), and `a4_imageblock_extent`'s region
/// also sets its imageblock's extent. Printed per profile: whether the tier requires full
/// subgroups.
#[test]
fn a_kernel_rows_stage_is_created_from_its_planned_region_not_its_defaults() {
let full = vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS;
for profile in ["moltenvk-m3", "lavapipe"] {
let device = crate::engine::load_device(profile).unwrap();
for (file, entry) in [
("simd_ops.ll", "simd_shuffle_k"),
("a4_imageblock_extent.ll", "a4_imageblock_extent"),
] {
let bitcode = match llvm_assemble(&engine_dir().join(file)) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {file}: {why}"),
};
let compiled = compile_row(
&bitcode,
entry,
RowStage::Kernel,
Projection::Derived,
&device,
None,
);
let RowCompile::Compiled(row) = compiled else {
panic!("{profile} {entry}: {compiled:?}");
};
let created = stage_creations(&row);
let RowPipeline::Compute { pipeline, creation } = &*row else {
panic!("{profile} {entry}: a kernel row is a compute pipeline");
};
let [stage] = created.as_slice() else {
panic!("{profile} {entry}: {} stages", created.len());
};
let region = &creation.region;
eprintln!(
"{profile} {entry}: flags {:#x}, required subgroup size {:?}",
stage.flags.as_raw(),
stage.required_subgroup_size
);
assert_eq!(
stage
.map
.iter()
.map(|entry| (entry.constant_id, entry.offset, entry.size))
.collect::<Vec<_>>(),
region
.specialization
.entries
.iter()
.map(|&entry| {
let entry: vk::SpecializationMapEntry = entry.into();
(entry.constant_id, entry.offset, entry.size)
})
.collect::<Vec<_>>(),
"{profile} {entry}"
);
assert!(!stage.map.is_empty(), "{profile} {entry}");
assert_eq!(stage.data, region.specialization.data, "{profile} {entry}");
assert_eq!(
stage.flags.as_raw(),
vk::PipelineShaderStageCreateFlags::from(region.stage_flags).as_raw(),
"{profile} {entry}"
);
assert_eq!(
stage.required_subgroup_size, region.required_subgroup_size,
"{profile} {entry}"
);
// The defaults leave the local size (and the imageblock's extent) at their
// placeholders, which the region specializes.
let defaults = StageCreation::defaults(&pipeline.stage);
assert_ne!(stage.data, defaults.data, "{profile} {entry}");
if (profile, entry) == ("moltenvk-m3", "simd_shuffle_k") {
assert!(stage.flags.contains(full), "{:#x}", stage.flags.as_raw());
assert!(
defaults.flags.contains(full),
"{:#x}",
defaults.flags.as_raw()
);
}
}
}
}
}
@@ -111,24 +111,15 @@ pub fn execute_runtime(
})
}
/// The attempt `on` makes, under the validation layer: one log per process, at one path, so the
/// layer writes this run's messages there whether it reads its variables at each instance or
/// once, a log of an earlier run gone first. Any message the layer logged fails the attempt.
/// The attempt `on` makes, under the validation layer ([`validated`]). Any message the layer
/// logged fails the attempt.
pub(super) fn under_validation(on: impl FnOnce() -> Result<RunAttempt, String>) -> RunAttempt {
let log = std::env::temp_dir().join(format!(
"metal2vulkan-validation-runtime-{}.log",
std::process::id()
));
let _ = std::fs::remove_file(&log);
validate_process(&log);
let attempt = match on() {
let (attempt, messages) = validated(|| match on() {
Ok(attempt) => attempt,
Err(error) => RunAttempt::of(Err(ExecutorError::Failed(error))),
};
let messages = std::fs::read_to_string(&log);
let _ = std::fs::remove_file(&log);
});
match messages {
Ok(messages) if !messages.trim().is_empty() => {
Some(messages) => {
let ran = match &attempt.result {
Ok(_) => String::new(),
Err(error) => format!(" (the run also failed: {error})"),
@@ -138,10 +129,27 @@ pub(super) fn under_validation(on: impl FnOnce() -> Result<RunAttempt, String>)
crate::engine::bounded_detail(&messages)
))))
}
_ => attempt,
None => attempt,
}
}
/// What `on` returns, run under the validation layer, and the messages the layer logged while it
/// ran, if any: one log per process, at one path, so the layer writes the run's messages there
/// whether it reads its variables at each instance or once, a log of an earlier run gone first.
pub(super) fn validated<T>(on: impl FnOnce() -> T) -> (T, Option<String>) {
let log = std::env::temp_dir().join(format!(
"metal2vulkan-validation-runtime-{}.log",
std::process::id()
));
let _ = std::fs::remove_file(&log);
validate_process(&log);
let value = on();
let messages = std::fs::read_to_string(&log);
let _ = std::fs::remove_file(&log);
let messages = messages.ok().filter(|messages| !messages.trim().is_empty());
(value, messages)
}
/// Enable the validation layer for this process's next instance, through the loader's and the
/// layer's variables (`docs/VALIDATION.md`), its messages logged to `log`: the loader and the
/// layer read them when an instance is made. A device worker makes one instance at a time, on
@@ -177,7 +185,7 @@ pub(super) fn attempt_on(
}
let layered = match runtime_restriction::layered(device_type, executor)? {
Ok(layered) => layered,
Err(refused) => return Ok(refused),
Err(refused) => return Ok(refused.attempt()),
};
let attempt = |device: &rt::Device, identity: &Identity, environment: &serde_json::Value| {
let result = run(device, identity, environment);
@@ -195,7 +203,7 @@ pub(super) fn attempt_on(
/// identity and environment a row of `executor` records of it, every object of it gone before
/// this returns, and the device torn down. `Err` where no device of the kind opens under the
/// layers.
fn opened<T>(
pub(super) fn opened<T>(
instance: &rt::Instance,
device_type: DeviceType,
executor: &'static str,
@@ -628,22 +636,35 @@ fn descriptor(
)))
}
/// The pipeline state `make` makes, within the per-attempt ceilings: its peak live allocations
/// within 500 MiB (an allocation past it ends the process), its wall time within 20 s. `make`
/// numbers the state's samplers with the function it is given: each constexpr sampler at an index
/// of the run's grant from its bottom ([`sampler_grant`]), one per state words, and a read's or a
/// write's at nothing.
/// The pipeline state `make` makes, within the per-attempt ceilings ([`within_ceilings`]), the
/// runtime's refusal of it as the executor's ([`runtime_error`]).
pub(super) fn made_within<T>(
make: impl FnOnce(
&mut dyn FnMut(&[NumberedSampler]) -> Result<Vec<u32>, rt::Error>,
) -> Result<T, rt::Error>,
) -> Result<T, ExecutorError> {
within_ceilings(make)
.map_err(ExecutorError::Failed)?
.map_err(|error| runtime_error("the pipeline's make", error))
}
/// What `make` answers, within the per-attempt ceilings: its peak live allocations within 500 MiB
/// (an allocation past it ends the process), its wall time within 20 s, either past it the outer
/// `Err`. `make` numbers the state's samplers with the function it is given: each constexpr
/// sampler at an index of the run's grant from its bottom ([`sampler_grant`]), one per state
/// words, and a read's or a write's at nothing; a sampler of another kind is the outer `Err`
/// once the make returns.
pub(super) fn within_ceilings<T>(
make: impl FnOnce(
&mut dyn FnMut(&[NumberedSampler]) -> Result<Vec<u32>, rt::Error>,
) -> Result<T, rt::Error>,
) -> Result<Result<T, rt::Error>, String> {
if !crate::worker::alloc::installed() {
return Err(ExecutorError::Failed(
return Err(
"the counting allocator is not installed: the pipeline's make cannot be held to its \
memory ceiling"
.into(),
));
);
}
let mut constexprs: BTreeMap<[u64; 2], u32> = BTreeMap::new();
let first = rt::IndexClass::Sampler.range().start;
@@ -668,21 +689,24 @@ pub(super) fn made_within<T>(
crate::worker::alloc::bounded(crate::worker::MEMORY_LIMIT_BYTES, || make(&mut numbered));
let took = started.elapsed();
if took > crate::worker::DEADLINE {
return Err(ExecutorError::Failed(format!(
return Err(format!(
"the pipeline's make took {} ms, past the {} s ceiling (peak live allocations {} \
bytes)",
took.as_millis(),
crate::worker::DEADLINE.as_secs(),
peak.unwrap_or(0)
)));
));
}
let made = made.map_err(|error| runtime_error("the pipeline's make", error))?;
let made = match made {
Ok(made) => made,
Err(error) => return Ok(Err(error)),
};
match unknown {
Some(sampler) => Err(ExecutorError::Failed(format!(
Some(sampler) => Err(format!(
"the pipeline numbers a sampler of a kind a run through the runtime does not know: \
{sampler}"
))),
None => Ok(made),
)),
None => Ok(Ok(made)),
}
}
@@ -0,0 +1,138 @@
//! Driver acceptance (L4) of a kernel row through the runtime, as a guest's kernel is made: the
//! row's AIR as a library, its function specialized with the row's function-constant values, one
//! `ComputePipelineState` on the sweep's device (restricted to the process's profile where it is,
//! `runtime_restriction`), and one dispatch of one representative threadgroup, encoded into a
//! command buffer that is never committed, so nothing executes.
//!
//! The representative threadgroup is the state's thread execution width of threads (32), or its
//! `maxTotalThreadsPerThreadgroup` where that is fewer. The runtime decides which of the state's
//! modules that threadgroup runs, as it does for a guest's dispatch, and the dispatch makes the
//! `VkPipeline` the driver is asked for: its creation is the runtime's count of it
//! (`Metrics::pipeline_creation_nanos`). A kernel that writes no memory records nothing and is made
//! no pipeline (`Metrics::dispatches_without_effects`): [`Acceptance::NoEffect`].
//!
//! The make is held to the per-attempt ceilings (`runtime::within_ceilings`), either past it a
//! tooling error. Each attempt opens its own device under `VK_LAYER_KHRONOS_validation`
//! (`runtime::validated`); any message the layer logs makes the row [`Acceptance::InvalidUsage`].
//! The runtime's typed refusal of the row on the device (the translator's, a known gap, a limit)
//! is [`Acceptance::RuntimeRefused`]; a Vulkan error of the make or the dispatch, the driver's,
//! [`Acceptance::Refused`].
use super::runtime::{self, sampler_grant};
use super::runtime_restriction;
use crate::acceptance::{Acceptance, AcceptanceError, RuntimeRow};
use crate::gpu::DeviceType;
use metal2vulkan::library::Library;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
use metal2vulkan_runtime as rt;
use std::time::Duration;
/// The executor a row's environment names.
const EXECUTOR: &str = "runtime-acceptance";
/// Make `row`'s pipeline state on the runtime's device of `device_type` and encode one dispatch of
/// it, as the module documentation says, and report what the runtime and the driver did. Only
/// opening the device (none of the kind, the hang tripwire, a restriction it cannot take) is
/// [`AcceptanceError::DeviceUnavailable`].
pub fn create_runtime_kernel(
device_type: DeviceType,
row: &RuntimeRow<'_>,
) -> Result<Acceptance, AcceptanceError> {
let (created, messages) = runtime::validated(|| attempt(device_type, row));
match (created, messages) {
(Ok(_), Some(messages)) => Ok(Acceptance::InvalidUsage(vec![
crate::engine::bounded_detail(&messages),
])),
(created, _) => created,
}
}
/// [`create_runtime_kernel`]'s attempt, under the validation layer.
fn attempt(device_type: DeviceType, row: &RuntimeRow<'_>) -> Result<Acceptance, AcceptanceError> {
let unavailable = AcceptanceError::DeviceUnavailable;
if device_type == DeviceType::Gpu {
crate::gpu::tripwire::refuse_if_tripped().map_err(unavailable)?;
}
let layered = match runtime_restriction::layered(device_type, EXECUTOR).map_err(unavailable)? {
Ok(layered) => layered,
Err(refused) => return Err(AcceptanceError::DeviceUnavailable(refused.to_string())),
};
let opened = layered.instance(|instance| {
runtime::opened(instance, device_type, EXECUTOR, &layered, |device, _, _| {
made(device, row)
})
});
opened.map_err(unavailable)?
}
/// `row`'s state made on `device`, and its dispatch encoded.
fn made(device: &rt::Device, row: &RuntimeRow<'_>) -> Result<Acceptance, AcceptanceError> {
let _grant =
sampler_grant(device).map_err(|error| AcceptanceError::Tooling(error.to_string()))?;
let function =
match Library::from_air(row.bitcode).and_then(|library| library.function(row.entry)) {
Ok(function) => function,
Err(error) => {
return Ok(Acceptance::RuntimeRefused(format!(
"the translator: {error}"
)))
}
};
let mut function = FunctionDescriptor::new(function).with_specialized(true);
function.constants = row.constants.clone();
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(function));
let before = device.counters().metrics();
let made = runtime::within_ceilings(|numbered| {
device.new_compute_pipeline_state(&descriptor, |samplers| numbered(samplers))
})
.map_err(AcceptanceError::Tooling)?;
let state = match made {
Ok(state) => state,
Err(error) => return answer(error),
};
let width = state
.thread_execution_width()
.min(state.max_total_threads_per_threadgroup())
.max(1);
if let Err(error) = dispatched(device, &state, [width, 1, 1]) {
return answer(error);
}
let after = device.counters().metrics();
if after.dispatches_without_effects > before.dispatches_without_effects {
return Ok(Acceptance::NoEffect);
}
let nanos = after
.pipeline_creation_nanos
.saturating_sub(before.pipeline_creation_nanos);
Ok(Acceptance::Created {
create: Duration::from_nanos(nanos),
})
}
/// One threadgroup of `threads_per_threadgroup` of `state` encoded into a command buffer of
/// `device` that is dropped uncommitted: the runtime gives back what it recorded, and nothing runs.
fn dispatched(
device: &rt::Device,
state: &rt::ComputePipelineState,
threads_per_threadgroup: [u32; 3],
) -> Result<(), rt::Error> {
let queue = device.new_command_queue(1)?;
let command_buffer = queue.command_buffer()?;
let mut encoder = command_buffer.compute_command_encoder(rt::DispatchType::Serial)?;
encoder.set_compute_pipeline_state(state)?;
encoder.dispatch_threadgroups([1, 1, 1], threads_per_threadgroup)?;
encoder.end_encoding();
Ok(())
}
/// The runtime's `error` for a row: a Vulkan error, the driver's refusal; the translator's
/// refusal, a known gap or a limit, the runtime's; any other a tooling error.
fn answer(error: rt::Error) -> Result<Acceptance, AcceptanceError> {
match error {
rt::Error::Vulkan { .. } => Ok(Acceptance::Refused(error.to_string())),
rt::Error::Translation { .. } | rt::Error::Unsupported(_) | rt::Error::Limit(_) => {
Ok(Acceptance::RuntimeRefused(error.to_string()))
}
error => Err(AcceptanceError::Tooling(error.to_string())),
}
}
@@ -110,12 +110,12 @@ impl Layered {
}
/// The layers of a run of `executor` on the device of `device_type` under this process's
/// restriction, read before the run: `Err` with the attempt's typed refusal where the device lacks
/// restriction, read before the run: `Err` with the restriction the device refuses where it lacks
/// a capability P states; a failure of a probe is the outer `Err`.
pub(super) fn layered(
device_type: DeviceType,
executor: &'static str,
) -> Result<Result<Layered, RunAttempt>, String> {
) -> Result<Result<Layered, Refused>, String> {
let Some(restriction) = profiles::current_restriction() else {
return Ok(Ok(Layered { restricted: None }));
};
@@ -145,7 +145,11 @@ pub(super) fn layered(
};
if !gaps.is_empty() {
let device = environment(&identity, &tools, executor, serde_json::Value::Null);
return Ok(Err(refusal(restriction, gaps, device)));
return Ok(Err(Refused {
restriction,
gaps,
device,
}));
}
let none = BTreeSet::new();
let presenting = ProfilesSettings::new(ProfilesLayer::Restrict(restriction, &none))?;
@@ -174,34 +178,53 @@ pub(super) fn layered(
}))
}
/// The typed refusal of a run restricted to `restriction` on a device that lacks `gaps`, recorded
/// with `device`, the environment a row on the device as it is records, and the restriction it
/// refused.
fn refusal(
restriction: &ProfileRestriction,
/// A restriction the device cannot take: P states `gaps`, capabilities the device as it is lacks.
pub(super) struct Refused {
restriction: &'static ProfileRestriction,
gaps: Vec<String>,
mut device: serde_json::Value,
) -> RunAttempt {
if let Some(environment) = device.as_object_mut() {
let layer = serde_json::json!({
"profile": restriction.stem,
"profile_name": restriction.profile_name,
"profile_sha256": restriction.sha256,
"refused": gaps,
});
environment.insert("profiles_layer".into(), layer);
}
RunAttempt {
result: Err(NotSupported::Restriction {
profile: restriction.stem.clone(),
/// The environment a row on the device as it is records.
device: serde_json::Value,
}
impl Refused {
/// The run's typed refusal, recorded with the device as it is and the restriction it refused.
pub(super) fn attempt(self) -> RunAttempt {
let Refused {
restriction,
gaps,
mut device,
} = self;
if let Some(environment) = device.as_object_mut() {
let layer = serde_json::json!({
"profile": restriction.stem,
"profile_name": restriction.profile_name,
"profile_sha256": restriction.sha256,
"refused": gaps,
});
environment.insert("profiles_layer".into(), layer);
}
.into()),
refused_on: Some(RefusedOn {
environment: device,
translator_fingerprint: runtime_fingerprint(),
artifact: None,
}),
RunAttempt {
result: Err(NotSupported::Restriction {
profile: restriction.stem.clone(),
gaps,
}
.into()),
refused_on: Some(RefusedOn {
environment: device,
translator_fingerprint: runtime_fingerprint(),
artifact: None,
}),
}
}
}
impl std::fmt::Display for Refused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let exceeds = RestrictionError::Exceeds {
profile: self.restriction.stem.clone(),
gaps: self.gaps.clone(),
};
write!(f, "{exceeds}")
}
}
@@ -74,7 +74,9 @@ fn a_restricted_run_on_a_device_without_the_profile_is_a_recorded_refusal() {
use crate::candidate::engine::{engine_slot, ENGINE_EXECUTOR_ABI};
use crate::refusal::{Refusal, RefusalClass, RefusalObservation};
let restriction = ProfileRestriction::committed("nvidia-pascal-linux").unwrap();
let restriction: &'static ProfileRestriction = Box::leak(Box::new(
ProfileRestriction::committed("nvidia-pascal-linux").unwrap(),
));
let gaps =
vec!["limits.max_compute_work_group_invocations 1536 beyond the device's 1024".into()];
let device = serde_json::json!({
@@ -84,7 +86,15 @@ fn a_restricted_run_on_a_device_without_the_profile_is_a_recorded_refusal() {
"version": "1.0.0"}],
"profiles_layer": null,
});
let attempt = refusal(&restriction, gaps.clone(), device);
let refused = Refused {
restriction,
gaps: gaps.clone(),
device,
};
assert!(refused
.to_string()
.contains("profile nvidia-pascal-linux states 1 capabilities the device lacks"));
let attempt = refused.attempt();
let not_supported = match attempt.result {
Err(ExecutorError::NotSupported(not_supported)) => not_supported,
other => panic!("{:?}", other.err()),
@@ -1,17 +1,20 @@
//! L4 driver acceptance on a device: the unsafe creation path of [`create_acceptance_pipeline`]
//! (set layouts, binding flags, specialization, subgroup size, render pass, graphics pipeline) runs
//! against the lane's Vulkan device. Nothing is bound or dispatched, so no shader executes.
//! against the lane's Vulkan device for a render row, and a kernel row is made through the runtime
//! ([`create_runtime_kernel`]). Nothing is bound or submitted, so no shader executes.
//! `G-linux`'s `m2v_cpu_icd` step runs it on lavapipe.
//!
//! Each row compiles for the opened device's own `Device` (its queried description restricted to
//! what the context enabled, `platform::opened_worker_device`), never for a committed profile
//! named after the lane, so a lane whose device differs from any committed description still
//! checks what it would create.
//! Each render row compiles for the opened device's own `Device` (its queried description
//! restricted to what the context enabled, `platform::opened_worker_device`), never for a committed
//! profile named after the lane, so a lane whose device differs from any committed description
//! still checks what it would create.
use super::*;
use crate::acceptance::{
compile_row_in_worker, retained, Acceptance, Projection, RowCompile, RowPipeline, RowStage,
RuntimeRow,
};
use metal2vulkan::library::FunctionConstantValues;
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
/// Compile `entry` of the owned fixture `file` as an L4 row under `projection` for the device the
@@ -37,10 +40,40 @@ fn compiled(file: &str, entry: &str, stage: RowStage, projection: Projection) ->
}
}
/// The driver created the pipeline within the ceiling, or the device lacks something it needs; a
/// refusal or a tooling error (including an unavailable device) is a failure.
/// The driver created the render pipeline within the ceiling, or the device lacks something it
/// needs; a refusal or a tooling error (including an unavailable device) is a failure.
fn assert_accepted(pipeline: &RowPipeline) {
match create_acceptance_pipeline(crate::gpu::TEST_DEVICE, pipeline) {
let RowPipeline::Render { pipeline, .. } = pipeline else {
panic!("a kernel row is made through the runtime");
};
accepted(create_acceptance_pipeline(
crate::gpu::TEST_DEVICE,
pipeline,
));
}
/// What the runtime answered for kernel row `entry` of the owned fixture `file`, made on the
/// lane's device as `corpus-pipeline` makes a kernel row, with no function-constant values. A
/// device lane has `llvm-as`, so a missing assembler fails the test.
fn made(file: &str, entry: &str) -> Acceptance {
let bitcode = llvm_assemble(&engine_dir().join(file))
.unwrap_or_else(|error| panic!("assemble {file}: {error:?}"));
let constants = FunctionConstantValues::defaults();
let row = RuntimeRow {
bitcode: &bitcode,
entry,
constants: &constants,
};
let made = create_runtime_kernel(crate::gpu::TEST_DEVICE, &row)
.unwrap_or_else(|error| panic!("{entry}: {error}"));
eprintln!("{entry}: {made:?}");
made
}
/// `acceptance` is a pipeline created within the ceiling, or a device that lacks something it
/// needs; anything else fails.
fn accepted(acceptance: Result<Acceptance, crate::acceptance::AcceptanceError>) {
match acceptance {
Ok(Acceptance::Created { create }) => {
assert!(
crate::budgets::creation_within_ceiling("the pipeline", create).is_ok(),
@@ -52,63 +85,49 @@ fn assert_accepted(pipeline: &RowPipeline) {
Ok(Acceptance::InvalidUsage(messages)) => {
panic!("the validation layer reported: {}", messages.join(" | "))
}
Ok(Acceptance::RuntimeRefused(why)) => panic!("the runtime refused the kernel: {why}"),
Ok(Acceptance::NoEffect) => panic!("the runtime made no pipeline"),
Err(error) => panic!("acceptance failed: {error}"),
}
}
/// A kernel row is made through the runtime, and the driver creates the pipeline its dispatch
/// runs on; a vertex function alone is created from the binder layout.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn compute_and_vertex_only_pipelines_are_created_from_the_binder_layout() {
let row = |file, entry, stage| compiled(file, entry, stage, Projection::Derived);
let compute = row("store_const.ll", "store_const", RowStage::Kernel);
assert!(matches!(compute, RowPipeline::Compute { .. }));
assert_accepted(&compute);
fn a_kernel_row_is_made_through_the_runtime_and_a_vertex_only_pipeline_is_created() {
accepted(Ok(made("store_const.ll", "store_const")));
let vertex = row("stage_io.ll", "stage_io_vertex_position", RowStage::Vertex);
let vertex = compiled(
"stage_io.ll",
"stage_io_vertex_position",
RowStage::Vertex,
Projection::Derived,
);
assert!(matches!(vertex, RowPipeline::Render { .. }));
assert_accepted(&vertex);
}
/// Create kernel row `entry` of the owned fixture `file` from the region the binder plans for its
/// representative dispatch, after printing the row's dispatch, its stage's flags and the region's,
/// the required subgroup size, and the imageblock extent: they show whether the lane's tier
/// requires full subgroups.
fn assert_created_from_its_region(file: &str, entry: &str) {
let pipeline = compiled(file, entry, RowStage::Kernel, Projection::Derived);
let RowPipeline::Compute {
pipeline: compute,
creation,
} = &pipeline
else {
panic!("{entry}: a kernel row is a compute pipeline");
};
eprintln!(
"{entry}: {:?}, stage flags {:?} (the region's {:?}), required subgroup size {:?}, \
imageblock {:?}",
creation.dispatch,
compute.stage.stage_flags,
creation.region.stage_flags,
creation.region.required_subgroup_size,
creation.imageblock
);
assert_accepted(&pipeline);
}
/// A kernel whose simd tier can require full subgroups is created from its region. The 897
/// A kernel whose simd tier can require full subgroups is made, its representative threadgroup
/// whole simdgroups of the state's thread execution width. The 897
/// `VUID-VkPipelineShaderStageCreateInfo-flags-02759` rows were such kernels created at their
/// stage's placeholder local size of 1.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn a_full_subgroup_kernel_row_is_created_from_its_region() {
assert_created_from_its_region("simd_ops.ll", "simd_shuffle_k");
fn a_full_subgroup_kernel_row_is_made_through_the_runtime() {
accepted(Ok(made("simd_ops.ll", "simd_shuffle_k")));
}
/// A kernel with an explicit imageblock is created from its region, whose specialization sets
/// the representative extent.
/// A kernel with an explicit imageblock is the runtime's typed refusal, as a guest's is: its
/// compute encoder does not set an imageblock's extent (`setImageblockWidth:height:`).
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn an_imageblock_kernel_row_is_created_from_its_region() {
assert_created_from_its_region("a4_imageblock_extent.ll", "a4_imageblock_extent");
fn an_imageblock_kernel_row_is_the_runtimes_refusal() {
let made = made("a4_imageblock_extent.ll", "a4_imageblock_extent");
assert!(
matches!(&made, Acceptance::RuntimeRefused(why) if why.contains("mageblock")),
"{made:?}"
);
}
/// A post-tessellation vertex function's row is a tessellation pipeline (the synthesized vertex
+9 -2
View File
@@ -411,8 +411,15 @@ cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
Other corpus tools:
- `corpus-pipeline --device-type cpu|gpu --profile P` asks a Vulkan driver to create each
translated pipeline, without dispatching anything (driver acceptance).
- `corpus-pipeline --device-type cpu|gpu --profile P` is driver acceptance (L4), on lavapipe and
the real cards. It compiles each row in a compile worker, then asks the device's driver for its
pipeline. A render row's pipeline is created from the binder layout its artifact carries, with
nothing drawn. A kernel row is made as a guest's kernel is, through the runtime: its
`ComputePipelineState` on the device, and one dispatch of one representative threadgroup (the
state's thread execution width of threads) encoded into a command buffer that is never
committed, so the driver is asked for the pipeline that dispatch runs on and nothing executes.
The runtime's typed refusal of a kernel row is `RUNTIME_REFUSED`, and a kernel that writes no
memory, which the runtime makes no pipeline for, is `NO_EFFECT`; both are counted.
- `--profiles-layer P` (on `corpus-vulkan` and `corpus-pipeline`) runs every context through
`VK_LAYER_KHRONOS_profiles` restricted to a committed profile, to test a profile on a device that
exceeds it.