Relocate a compiled function's module once a link, not once a pipeline

Content: the tree of `development` at c1cf1a09c9, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:21 +02:00
1 parent 586bf2ad59
commit 02534b2304
6 files changed
+374 -18

No files matched your search

+78 -4
View File
@@ -48,14 +48,88 @@ impl fmt::Debug for FunctionCompileKey {
/// A compiled function: opaque, `Send + Sync`, cheap to clone. Pass it to a pipeline descriptor as
/// `StageSource::Compiled` to link without decoding or lowering again.
///
/// A clone shares both the artifact and the relocation slot, so every pipeline a consumer's memo
/// hands this function to relocates against the same slot: a sweep of pipeline states over one
/// function relocates its module once rather than once a state.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CompiledFunction(Arc<FunctionArtifact>);
#[derive(Clone)]
pub struct CompiledFunction(Arc<FunctionArtifact>, Arc<LastRelocation>);
/// The last relocation of one compiled function's module, kept beside it: **one slot,
/// last-wins**.
///
/// Relocation writes only the literals the serializer reserved, so the final words are a pure
/// function of the module and the value link assigned to each reserved slot
/// (`pipeline::relocate`). A pipeline whose link assigns the same values therefore wants the same
/// words, and a sweep of pipeline states over one function pair -- a blend sweep, where the state
/// reaches no relocation slot -- assigns the same values on every creation. Without the slot each
/// creation clones and patches the whole module again and everything keyed on its content hashes
/// the result afresh, over words that are byte-identical to the previous creation's.
///
/// **The bound is the slot.** One entry per compiled function, replaced rather than accumulated,
/// so the extra retention is one relocated word array per live function: at most what the
/// function's own `RelocatableModule` already holds, and it cannot grow with the creations, the
/// pipelines, or the distinct links a run makes. A run that varies something a relocation slot
/// does carry never hits, and still holds one entry. The slot dies with the function, so nothing
/// evicts it.
#[derive(Default)]
pub(crate) struct LastRelocation(std::sync::Mutex<Option<Relocated>>);
/// One relocation: what link assigned, and the words that came out.
struct Relocated {
/// The value link assigned to each of the module's relocation slots, in `relocs` order: the
/// whole of what the words depend on besides the module itself.
assigned: Vec<u32>,
words: Arc<[u32]>,
}
impl LastRelocation {
/// The words of the relocation that assigned `assigned`, if that is the one the slot holds.
pub(crate) fn words_for(&self, assigned: &[u32]) -> Option<Arc<[u32]>> {
let slot = self.0.lock().unwrap_or_else(|e| e.into_inner());
let kept = slot.as_ref()?;
(kept.assigned == assigned).then(|| Arc::clone(&kept.words))
}
/// Keep `words` as the relocation that assigned `assigned`, replacing what the slot held.
pub(crate) fn keep(&self, assigned: Vec<u32>, words: &Arc<[u32]>) {
let mut slot = self.0.lock().unwrap_or_else(|e| e.into_inner());
*slot = Some(Relocated {
assigned,
words: Arc::clone(words),
});
}
}
/// A clone of a compiled function shares its slot, so the `Debug`, equality and hashing of a
/// compiled function are its artifact's alone: the slot is a memo of a value the artifact and the
/// link already determine, never a fact about the function.
impl fmt::Debug for CompiledFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("CompiledFunction").field(&self.0).finish()
}
}
impl PartialEq for CompiledFunction {
fn eq(&self, other: &CompiledFunction) -> bool {
self.0 == other.0
}
}
impl Eq for CompiledFunction {}
impl CompiledFunction {
/// Wrap a finished per-function compile (`pipeline::compile`, or a cache load).
/// Wrap a finished per-function compile (`pipeline::compile`, or a cache load), with an empty
/// relocation slot.
pub(crate) fn new(artifact: Arc<FunctionArtifact>) -> CompiledFunction {
CompiledFunction(artifact)
CompiledFunction(artifact, Arc::new(LastRelocation::default()))
}
/// The function's relocation slot ([`LastRelocation`]), which `pipeline::relocate` reads and
/// fills.
pub(crate) fn last_relocation(&self) -> &LastRelocation {
&self.1
}
/// The key the function was compiled under.
+12 -12
View File
@@ -55,7 +55,6 @@ use crate::pipeline::link::mesh::synthesized_stage as mesh_vertex_stage;
use crate::pipeline::link::tessellation::{note_evaluation_stage, synthesized_stages};
use crate::pipeline::link::{link, LinkInputs, Linked, RenderLinkInputs};
use crate::pipeline::lower_inputs::LoweringInputs;
use crate::pipeline::relocate::relocate;
use crate::pipeline::stage_io::{IoRole, StageBuiltin, StageInFetch};
use crate::pipeline::sym::{Stage, VaryingKey};
use crate::spirv::serialize::ENTRY_NAME;
@@ -604,9 +603,9 @@ impl Device {
}
let artifacts: Vec<&FunctionArtifact> = compiled.iter().map(|c| c.artifact()).collect();
let mut linked = link(&artifacts, &LinkInputs::mesh(d), p)?;
let mut stages = Vec::with_capacity(artifacts.len());
for (i, a) in artifacts.iter().enumerate() {
stages.push(stage_module(a, &linked, i)?);
let mut stages = Vec::with_capacity(compiled.len());
for (i, c) in compiled.iter().enumerate() {
stages.push(stage_module(c, &linked, i)?);
}
note_sample_position(d.into(), &artifacts, &mut stages);
let keys: Vec<FunctionCompileKey> = artifacts.iter().map(|a| a.key).collect();
@@ -733,7 +732,7 @@ impl Device {
check_stage_in(a, d)?;
check_call_stack(a, d.max_call_stack_depth)?;
let linked = link(&[a], &LinkInputs::compute(), p)?;
let stage = stage_module(a, &linked, 0)?;
let stage = stage_module(&kernel, &linked, 0)?;
let profile = self.profile_fingerprint();
let key = pipeline_key(b"compute", &profile, &[a.key], &compute_fields(d));
let metal_info = self.metal_info(
@@ -778,7 +777,7 @@ impl Device {
check_tile_threadgroup(a, d)?;
check_call_stack(a, d.max_call_stack_depth)?;
let linked = link(&[a], &LinkInputs::compute(), p)?;
let stage = stage_module(a, &linked, 0)?;
let stage = stage_module(&kernel, &linked, 0)?;
let profile = self.profile_fingerprint();
let key = pipeline_key(b"tile", &profile, &[a.key], &tile_fields(d));
let max_threads = d
@@ -909,9 +908,9 @@ impl Device {
&LinkInputs::render_variant(d, v, group.clone()),
p,
)?;
let mut stages = Vec::with_capacity(artifacts.len());
for (i, a) in artifacts.iter().enumerate() {
stages.push(stage_module(a, &linked, i)?);
let mut stages = Vec::with_capacity(compiled.len());
for (i, c) in compiled.iter().enumerate() {
stages.push(stage_module(c, &linked, i)?);
}
note_sample_position(pass(), &artifacts, &mut stages);
let keys: Vec<FunctionCompileKey> = artifacts.iter().map(|a| a.key).collect();
@@ -1566,8 +1565,9 @@ fn render_fields(d: &RenderPipelineDescriptor) -> String {
}
/// Stage `i` of a linked pipeline as its final module.
fn stage_module(a: &FunctionArtifact, linked: &Linked, i: usize) -> Result<StageModule, Error> {
let words = relocate(a, linked)?;
fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result<StageModule, Error> {
let a = c.artifact();
let words = crate::pipeline::relocate::relocated(c, linked)?;
let specialization = linked
.specialization
.get(i)
@@ -1604,7 +1604,7 @@ fn stage_module(a: &FunctionArtifact, linked: &Linked, i: usize) -> Result<Stage
Ok(StageModule {
stage: a.interface.vk_stage(),
entry_point: ENTRY_NAME.to_owned(),
spirv: words.into(),
spirv: words,
specialization,
required_subgroup_size: a.subgroup.size,
stage_flags,
+56 -1
View File
@@ -4,9 +4,17 @@
//! `Location`/`Component`, `SpecId`); a symbol the table does not assign is a `BuildError`
//! (`Internal`). The words of a module with its relocation slots zeroed are therefore the same
//! for every link.
//!
//! That invariant is what [`relocated`] rests on: the final words are a pure function of the
//! module and the value link assigned to each reserved slot, so two links that assign the same
//! values want the same words, and a compiled function's relocation slot
//! ([`LastRelocation`](crate::library::compiled::LastRelocation)) can answer the second of them
//! without touching the words at all.
use std::sync::Arc;
use crate::error::Error;
use crate::library::FunctionArtifact;
use crate::library::{CompiledFunction, FunctionArtifact};
use crate::spirv::serialize::SymbolTable;
/// The final SPIR-V words of `a` under link table `link` (a `LinkTable` or the `Linked` result of
@@ -14,3 +22,50 @@ use crate::spirv::serialize::SymbolTable;
pub fn relocate(a: &FunctionArtifact, link: &impl SymbolTable) -> Result<Vec<u32>, Error> {
Ok(crate::spirv::serialize::relocate(&a.module, link)?)
}
/// The final SPIR-V words of `c`'s function under link table `link`: the words of `c`'s last
/// relocation where `link` assigns its slots the same values, else relocated now and kept as
/// `c`'s last.
///
/// What link assigned is read first, which costs one pass over the module's relocation list and
/// none over its words; a hit therefore neither clones the module nor rewrites a literal, and
/// gives back the very `Arc` the earlier pipeline's stage holds. A symbol `link` does not assign
/// is left to [`relocate`] to refuse, so a missing symbol is the same error from either path.
pub fn relocated(c: &CompiledFunction, link: &impl SymbolTable) -> Result<Arc<[u32]>, Error> {
let a = c.artifact();
let assigned: Option<Vec<u32>> = a
.module
.relocs
.iter()
.map(|(sym, _)| link.resolve(sym))
.collect();
// A symbol the table does not assign: no key, and `relocate` names it.
let Some(assigned) = assigned else {
return Ok(relocate(a, link)?.into());
};
if let Some(words) = c.last_relocation().words_for(&assigned) {
return Ok(words);
}
note_relocated();
let words: Arc<[u32]> = relocate(a, link)?.into();
c.last_relocation().keep(assigned, &words);
Ok(words)
}
/// The relocations this process performed through [`relocated`], which
/// `tests::relocated_once`'s count reads: a run of sibling pipeline creations over one function
/// must add none to what its first creation relocated.
#[cfg(test)]
static RELOCATED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// [`RELOCATED`].
#[cfg(test)]
pub(crate) fn relocations_done() -> u64 {
RELOCATED.load(std::sync::atomic::Ordering::Relaxed)
}
/// Count a relocation the slot could not answer.
fn note_relocated() {
#[cfg(test)]
RELOCATED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
+1
View File
@@ -185,6 +185,7 @@ mod golden_hashes;
mod owned_divisions;
mod profile_fingerprint_derived;
mod public_fixtures_engine;
mod relocated_once;
mod stage_in_unread_key;
mod stage_input_siblings;
mod tessellator;
@@ -0,0 +1,223 @@
//! A run of sibling pipeline creations over one compiled function **relocates its module once**,
//! not once each (`pipeline::relocate::relocated`).
//!
//! # What this guards
//!
//! Relocation writes only the literals the serializer reserved, so a stage's final words are a
//! pure function of its module and the value link assigned to each reserved slot. A sweep of
//! pipeline states over one function pair -- a blend sweep, where no state reaches a reserved
//! slot -- therefore wants the same words on every creation, and measured on an M3 Max every
//! creation built them again: a fresh `Arc<[u32]>` of identical words per creation, which
//! everything keyed on a module's content then hashed and encoded afresh. The clone is one pass
//! over the words and the hashes are more, so the cost of a creation rose with the size of a
//! module nothing about the creation changed.
//!
//! The words now come from the function's relocation slot, which the first creation filled.
//!
//! # Why this is a count
//!
//! How many times a run relocates is a fact of where the words come from, not of the host: it
//! holds under any load and needs no quiet machine. It is held in **both** directions. Over the
//! count is a creation that relocates again; under it is a run that relocates nothing at all,
//! which would mean the words came from somewhere other than the module -- so the first creation
//! is required to relocate exactly once a stage, which is what keeps the siblings' zero from
//! being a vacuous zero.
//!
//! [`a_differing_link_gets_its_own_words`] is the half a count catches on the low side, and the
//! one that matters for correctness rather than speed: a memo on a value that is supposed to vary
//! must still vary. Two links that assign a module's slots different values must get different
//! words, and the slot must never answer one link with another's. It also asserts what makes the
//! fast path sound at all -- that the words the slot gives are byte-identical to relocating
//! again -- so the invariant `relocate.rs` states is checked rather than trusted.
use std::sync::Arc;
use crate::budget::Budget;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::library::{CompiledFunction, Library};
use crate::metal::{BlendFactor, BlendOperation, PixelFormat};
use crate::pipeline::relocate::{relocate, relocated, relocations_done};
use crate::pipeline::sym::Symbol;
use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError};
use crate::pipeline::{
ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageEntries,
StageSource,
};
/// The fixture and the vertex-and-fragment pair the sweeps below make pipelines of.
const FIXTURE: &str = "ubo_bind_offsets";
const VERTEX: &str = "ubo_offsets_vertex";
const FRAGMENT: &str = "ubo_offsets_fragment";
/// The sibling creations the run makes after the first.
const RUN: u64 = 16;
/// Blend factors no two of which make one pipeline state, and none of which reaches a relocation
/// slot: each sibling is its own descriptor over the same two modules.
const FACTORS: [BlendFactor; 8] = [
BlendFactor::Zero,
BlendFactor::One,
BlendFactor::SourceColor,
BlendFactor::OneMinusSourceColor,
BlendFactor::SourceAlpha,
BlendFactor::OneMinusSourceAlpha,
BlendFactor::DestinationColor,
BlendFactor::DestinationAlpha,
];
/// A device of the committed `moltenvk-m3` profile.
fn device() -> Device {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles/moltenvk-m3.json");
let text = std::fs::read_to_string(&path).expect("committed profile");
let description = DeviceDescription::from_khronos_json(&text, None).expect("description");
Device::new(description, DevicePolicy::default()).expect("device")
}
/// The fixture's library, or `None` where `llvm-as` is absent.
fn library() -> Option<Library> {
match llvm_assemble(&engine_dir().join(format!("{FIXTURE}.ll"))) {
Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the fixture parses")),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {FIXTURE}.ll: {why}"),
}
}
/// The pair compiled once, as a consumer's memo holds it across a sweep's creations.
fn pair(device: &Device, library: &Library) -> (CompiledFunction, CompiledFunction) {
let vertex = FunctionDescriptor::new(library.function(VERTEX).expect("the vertex function"));
let fragment =
FunctionDescriptor::new(library.function(FRAGMENT).expect("the fragment function"));
let budget = Budget::standard();
let mut base = RenderPipelineDescriptor::new(StageSource::Function(vertex.clone()));
base.fragment = Some(StageSource::Function(fragment.clone()));
base.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
let keys = device
.render_variant_key(
&base,
&crate::cache::VariantKey::new(),
&budget,
&StageEntries::new(),
)
.expect("the pair's keys");
let compile = |f: &FunctionDescriptor, inputs| {
device
.compile_function(f, inputs, &budget)
.expect("the stage compiles")
};
(
compile(&vertex, keys.vertex_inputs.as_ref().expect("vertex inputs")),
compile(
&fragment,
keys.fragment_inputs.as_ref().expect("fragment inputs"),
),
)
}
/// `RUN` sibling render pipeline creations over one compiled pair relocate **nothing**: the
/// first creation's two relocations are the ones every sibling's stages take.
#[test]
fn a_run_of_sibling_creations_relocates_once_a_stage() {
let Some(library) = library() else { return };
let device = device();
let (vertex, fragment) = pair(&device, &library);
let budget = Budget::standard();
let sibling = |i: u64| {
let mut d = RenderPipelineDescriptor::new(StageSource::Compiled(vertex.clone()));
d.fragment = Some(StageSource::Compiled(fragment.clone()));
let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm);
color.blending_enabled = true;
color.source_rgb_blend_factor = FACTORS[(i % 8) as usize];
color.destination_rgb_blend_factor = FACTORS[(i / 8 % 8) as usize];
color.rgb_blend_operation = BlendOperation::Add;
d.color_attachments[0] = Some(color);
d
};
// The first creation is the one that relocates: two stages, two relocations, which is what
// keeps the siblings' zero from being a zero that measures nothing.
let before = relocations_done();
let first = device
.compile_render_pipeline(&sibling(0), &budget)
.expect("the first creation");
let relocated_first = relocations_done() - before;
assert_eq!(
relocated_first, 2,
"the first creation of a two-stage pipeline must relocate each stage exactly once, not \
{relocated_first} times: a first creation that relocates nothing would make the \
siblings' zero below vacuous"
);
let before = relocations_done();
let mut kept = Vec::with_capacity(RUN as usize);
for i in 0..RUN {
kept.push(
device
.compile_render_pipeline(&sibling(1 + i), &budget)
.expect("a sibling creation"),
);
}
let again = relocations_done() - before;
assert_eq!(
again, 0,
"{RUN} sibling creations over one compiled pair must relocate none and relocated \
{again}: their blend states reach no relocation slot, so every stage's words are the \
first creation's"
);
// The words are not merely equal: they are the first creation's own, so nothing keyed on a
// module's content has anything new to hash.
for (stage, first_stage) in kept[0].stages.iter().zip(&first.stages) {
assert!(
Arc::ptr_eq(&stage.spirv, &first_stage.spirv),
"a sibling's stage must carry the first creation's words themselves"
);
}
}
/// Two links that assign a module's relocation slots different values get **different words**,
/// and neither is ever answered with the other's: the slot keys on what link assigned.
#[test]
fn a_differing_link_gets_its_own_words() {
let Some(library) = library() else { return };
let device = device();
let (vertex, _fragment) = pair(&device, &library);
let artifact = vertex.artifact();
assert!(
!artifact.module.relocs.is_empty(),
"the fixture's vertex module must have a relocation slot for this test to key on anything"
);
let (table, _) = crate::pipeline::testing::link_standalone(artifact, device.profile())
.expect("the function links alone");
// A second link that assigns one slot another value: a binding one higher, as a pipeline of
// other stages numbers it.
let moved = artifact.module.relocs[0].0.clone();
let shifted = |sym: &Symbol| {
let assigned = crate::spirv::serialize::SymbolTable::resolve(&table, sym)?;
Some(assigned + u32::from(*sym == moved))
};
let plain = relocated(&vertex, &table).expect("the plain link relocates");
let other = relocated(&vertex, &shifted).expect("the shifted link relocates");
assert_ne!(
&plain[..],
&other[..],
"a link that assigns a relocation slot another value must get other words, else the slot \
answered one link with another's"
);
// Back to the plain link, whose words the slot no longer holds: it must relocate rather than
// hand back the shifted link's, and what it gives must be byte-identical to relocating the
// module again, which is the invariant the fast path rests on.
let plain_again = relocated(&vertex, &table).expect("the plain link relocates again");
assert_eq!(
&plain_again[..],
&plain[..],
"the plain link's words must not change because another link was relocated between"
);
let fresh = relocate(artifact, &table).expect("relocating the module again");
assert_eq!(
&plain_again[..],
&fresh[..],
"the words the slot gives must be the words relocating the module again gives: only the \
reserved literals differ between links, so a memo keyed on them is exact or it is wrong"
);
}
+4 -1
View File
@@ -9636,7 +9636,7 @@ struct metal2vulkan::error::InputError #[derive(Clone, Debug, PartialEq, Eq)] #[
struct metal2vulkan::error::InternalError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct InternalError
struct metal2vulkan::error::Location #[derive(Clone, PartialEq, Eq, Hash)] pub struct Location
struct metal2vulkan::error::Unsupported #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Unsupported
struct metal2vulkan::library::CompiledFunction #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct CompiledFunction(Arc<FunctionArtifact>)
struct metal2vulkan::library::CompiledFunction #[derive(Clone)] #[non_exhaustive] pub struct CompiledFunction(Arc<FunctionArtifact>, Arc<LastRelocation>)
struct metal2vulkan::library::DynamicLibrary #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DynamicLibrary
struct metal2vulkan::library::Function #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Function
struct metal2vulkan::library::FunctionCompileKey #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct FunctionCompileKey(pub Hash256)
@@ -9948,6 +9948,9 @@ trait-impl metal2vulkan::error::VerifyError impl From<Violation> impl From<Viola
trait-impl metal2vulkan::error::VerifyError impl From<crate::air::error::Error> impl From<crate::air::error::Error> for VerifyError
trait-impl metal2vulkan::error::VerifyError impl fmt::Display impl fmt::Display for VerifyError
trait-impl metal2vulkan::error::VerifyError impl std::error::Error impl std::error::Error for VerifyError
trait-impl metal2vulkan::library::CompiledFunction impl Eq impl Eq for CompiledFunction
trait-impl metal2vulkan::library::CompiledFunction impl PartialEq impl PartialEq for CompiledFunction
trait-impl metal2vulkan::library::CompiledFunction impl fmt::Debug impl fmt::Debug for CompiledFunction
trait-impl metal2vulkan::library::FunctionCompileKey impl fmt::Debug impl fmt::Debug for FunctionCompileKey
trait-impl metal2vulkan::metal::TextureSwizzleChannels impl Default impl Default for TextureSwizzleChannels
trait-impl metal2vulkan::metal::sampler::AddressModeMap impl Default impl Default for AddressModeMap
Can't render this file because it is too large.