translator: the from_queries path keys a render descriptor by fixed-width words (queried_render_descriptor_key)

The new runtime keeps its map of contents under the key of a render descriptor, and a seen
render state cost 2.4 us (harness m3-max-44304, create_render_state p50 at aacdf481ce) against a
compute state's 0.8: render_descriptor_key took 2.27 us of it (bench m3-max-44376 at 7c9918994d,
32.8k instructions against compute_pipeline_key's 7.2k), most in writing the descriptor's fields
in their Debug form (0.41 us for the eight colour attachments alone).

Device::queried_render_descriptor_key keys the same fields as render_descriptor_key, each stage by
its compile key under the default inputs, the profile and SEMANTICS_VERSION, but writes every other
field as fixed-width little-endian words, tags and counts before optional and repeated parts,
under its own domain. Every field of the descriptor and of each struct it holds is destructured,
so a new field does not compile until the key writes it. metal2vulkan-rt keys render contents on
it. render_descriptor_key, the old runtime's (which keeps answers in its cache directory under
its values), is not touched and goes at the cutover.

Tests: the old key of one known descriptor is pinned to its value at 7c9918994d
(9d941806..., read by the bench m3-max-44376); the new key differs from the descriptor's for a
change in each field group and on another profile, and the old key tells each apart too.

Verified: cargo fmt; api_signatures blessed. Lint, the bench and the harness follow as potluck
jobs.
This commit is contained in:
Anees Iqbal committed 2026-11-17 21:50:59 -08:00
1 parent d3adc366cf
commit 1d460b2efd
7 files changed
+558 -7

No files matched your search

+1 -1
View File
@@ -894,7 +894,7 @@ a miss. With no directory, nothing is kept on disk, and each `VkPipeline` is mad
compute state. A refusal of the translator is `Error::Translation`.
- What a state compiles is its content, never the state: its descriptor, with its functions'
constant values and linked functions, and every field (the translator's
`Device::render_descriptor_key`). Every state of one content shares one compiled content: its
`Device::queried_render_descriptor_key`). Every state of one content shares one compiled content: its
translation, its shader modules and their `VkPipeline`s, and its precision notes. Render
contents and compute kernels share the device's one map of the last 1,024 contents used, so a
state of a content it holds costs the key, which reads no function, and a lookup.
+1 -1
View File
@@ -22,7 +22,7 @@ pub(crate) const KERNEL_ENTRIES: usize = 1024;
/// (`Device::compute_pipeline_key`: the kernel's AIR and entry, its constant values, linked
/// functions and dynamic libraries, its lowering inputs, the descriptor's fields that change the
/// compile, the device's profile and the translator's semantics version; or
/// `Device::render_descriptor_key`, every field of a render pipeline descriptor with its
/// `Device::queried_render_descriptor_key`, every field of a render pipeline descriptor with its
/// functions keyed as a kernel is; neither key decodes a function), and a compute descriptor's
/// `requiredThreadsPerThreadgroup`, which the state answers as its `maxTotalThreadsPerThreadgroup`
/// and the translator's key leaves out (`None` for a render pipeline).
+2 -2
View File
@@ -2,7 +2,7 @@
//! modules, and its `VkPipeline`s, one for each topology class drawn.
//!
//! What a state compiles is its content, never the state: the translator's key of its descriptor
//! (`Device::render_descriptor_key`: every field of the descriptor, each function by its AIR,
//! (`Device::queried_render_descriptor_key`: every field of the descriptor, each function by its AIR,
//! entry, constant values, linked functions and dynamic libraries, with the device's profile and
//! the translator's semantics version), which reads no function, as a compute state's key reads
//! none. Every state of one content shares one [`RenderCompiled`]: the translation, its shader
@@ -155,7 +155,7 @@ impl crate::Device {
refuse(descriptor)?;
let core = self.core();
let key = KernelKey {
pipeline: core.translator.render_descriptor_key(descriptor),
pipeline: core.translator.queried_render_descriptor_key(descriptor),
required: None,
};
let compiled = match core.kernels.find_render(&key) {
@@ -38,7 +38,8 @@ use crate::pipeline::artifact::{
RenderPipeline, RuntimeDependency, StageModule,
};
use crate::pipeline::compile::key::{
function_key, mesh_descriptor_key, pipeline_key, render_descriptor_key,
function_key, mesh_descriptor_key, pipeline_key, queried_render_descriptor_key,
render_descriptor_key,
};
use crate::pipeline::compile::{
color_group, compile_stage, compile_stage_from, dynamic_order, guarded, linked_keys,
@@ -149,6 +150,33 @@ impl Device {
render_descriptor_key(&self.profile_fingerprint(), d, stage)
}
/// The key of render pipeline descriptor `d` on this device for the runtime on
/// [`Device::from_queries`]: every field of `d`, each `Function` stage by its
/// [`Device::function_compile_key`] under the default lowering inputs, each `Compiled` stage
/// by its key, with this device's profile fingerprint and
/// [`SEMANTICS_VERSION`](crate::cache::SEMANTICS_VERSION), as
/// [`Device::render_descriptor_key`] keys it, the fields written as fixed-width words rather
/// than in their `Debug` form, so a seen descriptor's key costs no formatting. Two descriptors
/// have one key exactly where `render_descriptor_key` gives them one, so everything a creation
/// asks of `d` before its compile is a function of this key too. The two keys' values differ:
/// `render_descriptor_key` is the old runtime's, which keeps answers under its values, and goes
/// at the cutover. The crate keeps no cache.
pub fn queried_render_descriptor_key(
&self,
d: &RenderPipelineDescriptor,
) -> crate::cache::PipelineKey {
let stage = |s: &StageSource| match s {
StageSource::Function(f) => (
0,
*self
.function_compile_key(f, &LoweringInputs::default())
.digest(),
),
StageSource::Compiled(c) => (1, *c.key().digest()),
};
queried_render_descriptor_key(&self.profile_fingerprint(), d, stage)
}
/// The key of mesh render pipeline descriptor `d` on this device, without decoding, as
/// [`Device::render_descriptor_key`] keys a render descriptor: a digest of every field of `d`,
/// each `Function` stage by its [`Device::function_compile_key`] under the default lowering
+242 -2
View File
@@ -25,8 +25,9 @@ use crate::cache::{Hash256, PipelineKey, SEMANTICS_VERSION};
use crate::library::{FunctionCompileKey, FunctionConstantValues};
use crate::lower::select::LowerInputs;
use crate::pipeline::descriptor::{
LinkedList, MeshPipelineDescriptor, PrivateRenderState, RenderPipelineDescriptor,
StageInputDescriptor, StageSource, TessellationDescriptor,
ColorAttachmentDescriptor, LinkedList, MeshPipelineDescriptor, PrivateRenderState,
RenderPipelineDescriptor, StageInputDescriptor, StageSource, TessellationDescriptor,
VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor,
};
/// What a compile key records of one linked function: the list it is in, its name, the
@@ -788,3 +789,242 @@ pub(crate) fn render_descriptor_key(
}
PipelineKey::new(h.finish())
}
/// The key of render pipeline descriptor `d` for the profile of fingerprint `profile`, on
/// `Device::from_queries`' path (`Device::queried_render_descriptor_key`): each stage by `stage`'s
/// kind and digest, then every other field of `d` as fixed-width little-endian words in a fixed
/// order, each optional or repeated part after its tag or count, so no two descriptors write the
/// same words. Every field of `d` and of each struct it holds is named here, so that a field added
/// to any of them does not compile until the key writes it. The private state's one float is
/// written by its bits, so `-0.0` and each NaN payload are told apart.
pub(crate) fn queried_render_descriptor_key(
profile: &Hash256,
d: &RenderPipelineDescriptor,
stage: impl Fn(&StageSource) -> (u64, Hash256),
) -> PipelineKey {
let RenderPipelineDescriptor {
vertex,
fragment,
vertex_descriptor,
color_attachments,
depth_format,
stencil_format,
raster_sample_count,
alpha_to_coverage,
alpha_to_one,
rasterization_enabled,
input_primitive_topology,
max_vertex_amplification_count,
tessellation,
support_indirect_command_buffers,
max_vertex_call_stack_depth,
max_fragment_call_stack_depth,
support_adding_vertex_binary_functions,
support_adding_fragment_binary_functions,
vertex_buffers,
fragment_buffers,
texture_write_rounding_mode,
private,
} = d;
let PrivateRenderState {
sample_mask,
sample_coverage,
sample_coverage_invert,
alpha_test_enabled,
alpha_test_function,
logic_operation_enabled,
logic_operation,
clip_distance_enable_mask,
point_smooth_enabled,
point_coord_lower_left,
point_size_output_vs,
two_side_enabled,
vertex_depth_compare_clamp_mask,
fragment_depth_compare_clamp_mask,
depth_stencil_write_disabled,
needs_custom_border_color_samplers,
vertex_amplification_mode,
explicit_visibility_group_id,
open_gl_mode_enabled,
} = private;
let mut h = KeyHasher::new(b"metal2vulkan/queried-render-descriptor-key/v1");
h.bytes(profile);
let (kind, digest) = stage(vertex);
h.u64(kind).bytes(&digest);
match fragment {
Some(fragment) => {
let (kind, digest) = stage(fragment);
h.u64(kind).bytes(&digest);
}
None => {
h.u64(u64::MAX);
}
}
// The fields' words, hashed as one field.
let mut w = Words(Vec::with_capacity(384));
match vertex_descriptor {
None => {
w.u32(0);
}
Some(VertexDescriptor {
layouts,
attributes,
}) => {
w.u32(1).count(layouts.len());
for (
&buffer,
VertexBufferLayoutDescriptor {
stride,
step_function,
step_rate,
},
) in layouts
{
// The dynamic stride (`None`) apart from every stride.
w.u32(buffer)
.u64(stride.map_or(u64::MAX, u64::from))
.u32(step_function.as_raw())
.u32(*step_rate);
}
w.count(attributes.len());
for (
&index,
VertexAttributeDescriptor {
format,
offset,
buffer_index,
},
) in attributes
{
w.u32(index)
.u32(format.as_raw())
.u32(*offset)
.u32(*buffer_index);
}
}
}
for color in color_attachments {
match color {
None => {
w.u32(0);
}
Some(ColorAttachmentDescriptor {
pixel_format,
blending_enabled,
source_rgb_blend_factor,
destination_rgb_blend_factor,
rgb_blend_operation,
source_alpha_blend_factor,
destination_alpha_blend_factor,
alpha_blend_operation,
write_mask,
}) => {
w.u32(1)
.u32(pixel_format.as_raw())
.flag(*blending_enabled)
.u32(source_rgb_blend_factor.as_raw())
.u32(destination_rgb_blend_factor.as_raw())
.u32(rgb_blend_operation.as_raw())
.u32(source_alpha_blend_factor.as_raw())
.u32(destination_alpha_blend_factor.as_raw())
.u32(alpha_blend_operation.as_raw())
.u32(write_mask.as_raw());
}
}
}
// An absent format apart from every format, `Invalid` included.
let format = |f: &Option<crate::metal::PixelFormat>| f.map_or(u64::MAX, |f| f.as_raw().into());
w.u64(format(depth_format))
.u64(format(stencil_format))
.u32(*raster_sample_count)
.flag(*alpha_to_coverage)
.flag(*alpha_to_one)
.flag(*rasterization_enabled)
.u32(input_primitive_topology.as_raw())
.u32(*max_vertex_amplification_count);
match tessellation {
None => {
w.u32(0);
}
Some(TessellationDescriptor {
max_tessellation_factor,
partition_mode,
factor_format,
factor_step_function,
output_winding_order,
control_point_index_type,
factor_scale_enabled,
}) => {
w.u32(1)
.u32(*max_tessellation_factor)
.u32(partition_mode.as_raw())
.u32(factor_format.as_raw())
.u32(factor_step_function.as_raw())
.u32(output_winding_order.as_raw())
.u32(control_point_index_type.as_raw())
.flag(*factor_scale_enabled);
}
}
w.flag(*support_indirect_command_buffers)
.u32(*max_vertex_call_stack_depth)
.u32(*max_fragment_call_stack_depth)
.flag(*support_adding_vertex_binary_functions)
.flag(*support_adding_fragment_binary_functions);
for buffers in [vertex_buffers, fragment_buffers] {
w.count(buffers.len());
for (&index, mutability) in buffers {
w.u32(index).u32(mutability.as_raw());
}
}
// Metal's raw value of each mode.
let rounding = match texture_write_rounding_mode {
crate::metal::TextureWriteRoundingMode::TowardZero => 0,
crate::metal::TextureWriteRoundingMode::NearestEven => 2,
};
w.u32(rounding)
.u64(*sample_mask)
.u32(sample_coverage.to_bits())
.flag(*sample_coverage_invert)
.flag(*alpha_test_enabled)
.u64(*alpha_test_function)
.flag(*logic_operation_enabled)
.u64(*logic_operation)
.u32((*clip_distance_enable_mask).into())
.flag(*point_smooth_enabled)
.flag(*point_coord_lower_left)
.flag(*point_size_output_vs)
.flag(*two_side_enabled)
.u32(*vertex_depth_compare_clamp_mask)
.u32(*fragment_depth_compare_clamp_mask)
.flag(*depth_stencil_write_disabled)
.flag(*needs_custom_border_color_samplers)
.u64(*vertex_amplification_mode)
.u32(*explicit_visibility_group_id)
.flag(*open_gl_mode_enabled);
h.bytes(&w.0);
PipelineKey::new(h.finish())
}
/// Fixed-width little-endian words, gathered to be hashed as one field.
struct Words(Vec<u8>);
impl Words {
fn u32(&mut self, v: u32) -> &mut Self {
self.0.extend_from_slice(&v.to_le_bytes());
self
}
fn u64(&mut self, v: u64) -> &mut Self {
self.0.extend_from_slice(&v.to_le_bytes());
self
}
fn flag(&mut self, v: bool) -> &mut Self {
self.u32(v.into())
}
/// A count, before the parts it counts.
fn count(&mut self, n: usize) -> &mut Self {
self.u64(n as u64)
}
}
@@ -1243,6 +1243,288 @@ fn one_entry_set_specializes_a_sweeps_stages_once() {
assert_eq!(apart, 16, "two stages specialized for each of the eight");
}
/// The old runtime's render descriptor key keeps its value: one known descriptor's key, pinned.
/// The old runtime keeps answers under it in its cache directory, so a change of value is a
/// change to the old runtime.
#[test]
fn the_old_render_descriptor_key_keeps_its_value() {
let Some(bc) = fixture("stage_io") else {
return;
};
let lib = Library::from_air(&bc).expect("library");
let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(
lib.function("stage_io_vertex_position").expect("vertex"),
)));
d.fragment = Some(StageSource::Function(FunctionDescriptor::new(
lib.function("stage_io_fragment_primitive")
.expect("fragment"),
)));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(
metal::PixelFormat::RGBA8Unorm,
));
let key = device("moltenvk-m3").render_descriptor_key(&d);
let hex: String = key.digest().iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex, "9d941806be7907dabf5a876a17e746faa567bcb748bdd6cb14d624bde714ba27",
"the old runtime's key of the descriptor"
);
}
/// The key on `Device::from_queries`' path is the same for an equal descriptor and on another
/// device of the same profile, and differs from the descriptor's where one field group of it
/// changes: the stages, the vertex descriptor, a colour attachment's every field, the depth and
/// stencil formats, the sample and rasterization state, the topology class and amplification,
/// tessellation, indirect command buffers, the call-stack depths, binary functions, buffer
/// mutability, the rounding mode, each private field group, and the profile; and the old
/// runtime's key tells each change apart too.
#[test]
fn a_queried_render_descriptor_key_covers_each_field_group() {
let Some(bc) = fixture("stage_io") else {
return;
};
let lib = Library::from_air(&bc).expect("library");
let vertex = lib.function("stage_io_vertex_position").expect("vertex");
let fragment = lib
.function("stage_io_fragment_primitive")
.expect("fragment");
let dev = device("moltenvk-m3");
let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(
vertex.clone(),
)));
d.fragment = Some(StageSource::Function(FunctionDescriptor::new(
fragment.clone(),
)));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(
metal::PixelFormat::RGBA8Unorm,
));
let key = dev.queried_render_descriptor_key(&d);
assert_eq!(dev.queried_render_descriptor_key(&d.clone()), key);
assert_eq!(device("moltenvk-m3").queried_render_descriptor_key(&d), key);
assert_ne!(
device("lunarg-desktop-baseline-2023").queried_render_descriptor_key(&d),
key,
"the profile"
);
assert_ne!(
dev.render_descriptor_key(&d),
key,
"the old runtime's values"
);
let with_layout = |e: &mut RenderPipelineDescriptor, stride| {
let mut v = VertexDescriptor::new();
v.layouts
.insert(0, VertexBufferLayoutDescriptor::new(stride));
v.attributes.insert(
0,
VertexAttributeDescriptor::new(metal::VertexFormat::Float4, 0, 0),
);
e.vertex_descriptor = Some(v);
};
let color = |e: &RenderPipelineDescriptor| e.color_attachments[0].expect("the attachment");
type Change<'a> = Box<dyn Fn(&mut RenderPipelineDescriptor) + 'a>;
let changes: Vec<(&str, Change<'_>)> = vec![
("no fragment", Box::new(|e| e.fragment = None)),
(
"the fragment's function",
Box::new(|e| {
e.fragment = Some(StageSource::Function(FunctionDescriptor::new(
vertex.clone(),
)));
}),
),
(
"constants",
Box::new(|e| {
if let StageSource::Function(f) = &mut e.vertex {
f.constants = has_tint(true);
}
}),
),
(
"a vertex descriptor",
Box::new(|e| with_layout(e, Some(16))),
),
("another stride", Box::new(|e| with_layout(e, Some(32)))),
("the dynamic stride", Box::new(|e| with_layout(e, None))),
(
"a step function",
Box::new(|e| {
with_layout(e, Some(16));
if let Some(v) = &mut e.vertex_descriptor {
if let Some(l) = v.layouts.get_mut(&0) {
l.step_function = metal::VertexStepFunction::PerInstance;
}
}
}),
),
(
"an attribute's offset",
Box::new(|e| {
with_layout(e, Some(16));
if let Some(v) = &mut e.vertex_descriptor {
if let Some(a) = v.attributes.get_mut(&0) {
a.offset = 4;
}
}
}),
),
(
"a color format",
Box::new(|e| {
e.color_attachments[0] = Some(ColorAttachmentDescriptor::new(
metal::PixelFormat::BGRA8Unorm,
));
}),
),
(
"a second attachment",
Box::new(|e| {
e.color_attachments[1] = Some(color(e));
}),
),
(
"blending",
Box::new(|e| {
let mut c = color(e);
c.blending_enabled = true;
e.color_attachments[0] = Some(c);
}),
),
(
"a blend factor",
Box::new(|e| {
let mut c = color(e);
c.destination_alpha_blend_factor = metal::BlendFactor::One;
e.color_attachments[0] = Some(c);
}),
),
(
"a blend operation",
Box::new(|e| {
let mut c = color(e);
c.alpha_blend_operation = metal::BlendOperation::Max;
e.color_attachments[0] = Some(c);
}),
),
(
"a write mask",
Box::new(|e| {
let mut c = color(e);
c.write_mask = metal::ColorWriteMask::RED;
e.color_attachments[0] = Some(c);
}),
),
(
"depth",
Box::new(|e| e.depth_format = Some(metal::PixelFormat::Depth32Float)),
),
(
"stencil",
Box::new(|e| e.stencil_format = Some(metal::PixelFormat::Stencil8)),
),
("samples", Box::new(|e| e.raster_sample_count = 4)),
(
"alpha to coverage",
Box::new(|e| e.alpha_to_coverage = true),
),
("alpha to one", Box::new(|e| e.alpha_to_one = true)),
(
"rasterization",
Box::new(|e| e.rasterization_enabled = false),
),
(
"the topology class",
Box::new(|e| e.input_primitive_topology = metal::PrimitiveTopologyClass::Line),
),
(
"amplification",
Box::new(|e| e.max_vertex_amplification_count = 2),
),
(
"tessellation",
Box::new(|e| e.tessellation = Some(TessellationDescriptor::default())),
),
(
"indirect command buffers",
Box::new(|e| e.support_indirect_command_buffers = true),
),
(
"a call-stack depth",
Box::new(|e| e.max_fragment_call_stack_depth = 2),
),
(
"binary functions",
Box::new(|e| e.support_adding_vertex_binary_functions = true),
),
(
"a buffer's mutability",
Box::new(|e| {
e.fragment_buffers.insert(0, metal::Mutability::Immutable);
}),
),
(
"the rounding mode",
Box::new(|e| {
e.texture_write_rounding_mode = metal::TextureWriteRoundingMode::NearestEven
}),
),
("the sample mask", Box::new(|e| e.private.sample_mask = 1)),
(
"coverage 0.0",
Box::new(|e| e.private.sample_coverage = 0.0),
),
(
"coverage -0.0",
Box::new(|e| e.private.sample_coverage = -0.0),
),
(
"the alpha test",
Box::new(|e| e.private.alpha_test_function = 3),
),
(
"the logic operation",
Box::new(|e| e.private.logic_operation = 5),
),
(
"a clip distance",
Box::new(|e| e.private.clip_distance_enable_mask = 1),
),
(
"a private flag",
Box::new(|e| e.private.two_side_enabled = true),
),
(
"a clamp mask",
Box::new(|e| e.private.fragment_depth_compare_clamp_mask = 1),
),
(
"the amplification mode",
Box::new(|e| e.private.vertex_amplification_mode = 1),
),
(
"a visibility group",
Box::new(|e| e.private.explicit_visibility_group_id = 0),
),
(
"OpenGL mode",
Box::new(|e| e.private.open_gl_mode_enabled = true),
),
];
let mut seen = vec![key];
for (what, change) in &changes {
let mut e = d.clone();
change(&mut e);
let k = dev.queried_render_descriptor_key(&e);
assert!(!seen.contains(&k), "{what} changes the key");
assert_ne!(
dev.render_descriptor_key(&e),
dev.render_descriptor_key(&d),
"{what}: the old key tells it apart too"
);
seen.push(k);
}
}
/// A render descriptor's key is the same for an equal descriptor and on another device of the
/// same profile, and differs where a field, a stage, a private field, or the profile does: a
/// consumer keeping answers under it never takes another descriptor's.
@@ -10861,6 +10861,7 @@ method metal2vulkan::device::Device::new pub fn new(desc: DeviceDescription, pol
method metal2vulkan::device::Device::policy pub fn policy(&self) -> &DevicePolicy
method metal2vulkan::device::Device::profile pub fn profile(&self) -> &DeviceProfile
method metal2vulkan::device::Device::profile_fingerprint pub fn profile_fingerprint(&self) -> crate::cache::Hash256
method metal2vulkan::device::Device::queried_render_descriptor_key pub fn queried_render_descriptor_key(&self, d: &RenderPipelineDescriptor) -> crate::cache::PipelineKey
method metal2vulkan::device::Device::render_descriptor_key pub fn render_descriptor_key(&self, d: &RenderPipelineDescriptor) -> crate::cache::PipelineKey
method metal2vulkan::device::Device::render_pipeline_key pub fn render_pipeline_key(&self, d: &RenderPipelineDescriptor, b: &Budget) -> Result<RenderPipelineKeys, Error>
method metal2vulkan::device::Device::render_variant_key pub fn render_variant_key(&self, d: &RenderPipelineDescriptor, v: &VariantKey, b: &Budget, entries: &StageEntries) -> Result<RenderPipelineKeys, Error>
Can't render this file because it is too large.