diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 6fb837d9b..5970cf3ea 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2906,9 +2906,9 @@ or does not check is rebuilt from the generations' names, with young counted ful ### Kernels past the stage bound A driver's compiler takes memory that grows faster than the stage, in the process that creates the -pipeline. The translator states each module's entry weight (`ModuleStats::entry_weight`: the -entry's instructions, each call counted as its callee's body), and the stage bound is -`COMPILED_STAGE_WEIGHT`, 39,014: the heaviest kernel measured to compile in its creating process +pipeline. The translator states each module's weight (`ModuleStats::entry_weight`: the entry's +instructions, each call counted as its callee's body and each subgroup instruction as 64), and the +stage bound is `COMPILED_STAGE_WEIGHT`, 39,014: the heaviest kernel measured to compile in its creating process within 512 MiB of that process's resident growth on every driver measured. Made cold (no pipeline cache, the driver's shader cache off) and alone in a process of its own, a real program's kernel of that weight grew the process by 350 MiB in 6.8 s on ANV (Mesa 26.2.6, the Iris Xe of RPL-P; @@ -2917,10 +2917,18 @@ m3-max-66050) and 80 MiB in 0.55 s on RADV (Mesa 26.2.6, a Radeon 780M; job m3-m it, on the same Iris Xe, an older build's kernels of entry weights 73,814, 75,886 and 99,109 took peak resident sets of 1.76, 2.24 and 3.65 GiB in 45 s, 47 s and 132 s (job m3-max-26147). No Vulkan query states how large a stage a device's compiler takes, so the bound is one for every -device; it rises when a heavier kernel is measured to compile within 512 MiB. A kernel past the -bound is never compiled in the process that runs the program: each of its -`VkPipeline`s is compiled in a helper process the consumer starts, caps and times, and is created -here from that compile's cache data alone. +device; it rises when a heavier kernel is measured to compile within 512 MiB. A subgroup +instruction counts as 64 because a driver's compile grows with one many times faster than with any +other instruction: a kernel of entry weight 24,814 holding 3,772 subgroup instructions passed +6 GiB compiling on an RTX 3090 (NVIDIA 620.70.06; job m3-max-67936), where the kernel of 39,014 +above grew the process by 148 MiB. A kernel past the bound is never compiled in the process that +runs the program: each of its `VkPipeline`s is compiled in a helper process the consumer starts, +caps and times, and is created here from that compile's cache data alone. + +A kernel past the bound only because it emulates its SIMD groups in place of the device's widest +subgroup mode is planned again keeping that mode pinned: the re-plan takes the pinned module where +it weighs less than the emulated one by the stage weight; otherwise the emulated one goes on. The +one taken compiles in the process where it is under the bound, and in the helper where it is not. Render stages have a bound of their own, 99,109, as no helper compiles a render stage: a render pipeline with a stage past it is refused (Known gaps of render pipeline states), and one at or diff --git a/crates/metal2vulkan-validation/fixtures/public/stage_bound/stage_bound_matrix.metal b/crates/metal2vulkan-validation/fixtures/public/stage_bound/stage_bound_matrix.metal index 18cdc023d..0029390e5 100644 --- a/crates/metal2vulkan-validation/fixtures/public/stage_bound/stage_bound_matrix.metal +++ b/crates/metal2vulkan-validation/fixtures/public/stage_bound/stage_bound_matrix.metal @@ -6,7 +6,8 @@ // loop each thread leaves after its own count of iterations, reading another thread's word of its // simdgroup and writing its own with no barrier between: a lockstep pair in divergent flow. Emulated // simdgroups put it past the stage bound; a device that keeps its widest subgroup mode pinned -// writes it under the bound. +// writes it under the bound by its instructions alone, and past it, heavier than the emulated +// module, by the stage weight, which counts each subgroup instruction of its multiply-adds as 64. #include using namespace metal; diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 831720e92..751b076ad 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2273; +pub const SEMANTICS_VERSION: u32 = 2274; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/simd/matrix.rs b/crates/metal2vulkan/src/lower/simd/matrix.rs index 45049f84b..22625e96f 100644 --- a/crates/metal2vulkan/src/lower/simd/matrix.rs +++ b/crates/metal2vulkan/src/lower/simd/matrix.rs @@ -36,7 +36,11 @@ //! lane owning `(row, k)` and its `b` cells from the lane owning `(k, col)` with absolute //! shuffles inside its own simdgroup (in a simdgroup only partly taking part, which MSL leaves //! undefined, no read leaves the lanes that take part: `tile_mad`), and accumulates with `Fma` -//! in increasing `k` (the `agx2` schedule, shared with [`super::agx`]). Every operand format is +//! in increasing `k` (the `agx2` schedule, shared with [`super::agx`]). On a subgroup the reads +//! are paired and the steps are a loop: one shuffle of a `vec2` carries a step's two `b` cells, +//! one carries the `a` cells of steps `2m` and `2m + 1` (one lane owns both), and the `dim / 2` +//! step pairs are the trips of a loop, so a driver compiles each shuffle once per multiply-add +//! (its compile's memory grows with every subgroup instruction). Every operand format is //! converted exactly to `f32` first (`half` and `bfloat` are held widened; 8-bit floats decode //! exactly). When every format is `half` each step rounds to `half` (the `f16matmad` form); //! otherwise the sum accumulates in `f32` and rounds once to the result format. @@ -72,13 +76,14 @@ use crate::memory::leaf::{k32, Leaf, Path}; use crate::memory::provenance::Reach; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::sym::Stage; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; use crate::spirv::ids::Value as SValue; -use crate::spirv::ir::{BinOp, GlslOp}; +use crate::spirv::ir::{BinOp, GlslOp, MemAccess, Unrolling}; use super::check_operands; -use super::group::{bin_k, lane, Lane}; +use super::group::{bin_k, lane, shuffle, Lane, Live}; /// The lanes of an 8x8 matrix value. const LANES: u32 = 64; @@ -600,7 +605,8 @@ pub(super) struct TileMad { /// on a subgroup, where the multiply-add is [`TileMad::divergent`], through the ballot of the /// lanes executing it. MSL makes a multiply-add outside uniform control flow within the /// simdgroup undefined (section 2.4), so the product is promised only where the whole simdgroup -/// takes part. +/// takes part. On a subgroup the steps are [`paired_steps`]; the emulated tier's exchange reads +/// each cell alone, the steps written out. pub(super) fn tile_mad( fb: &mut FunctionBuilder<'_>, ln: &Lane, @@ -618,20 +624,29 @@ pub(super) fn tile_mad( let (ka, kb) = kept_bits(dim); let a_key = bin_k(fb, BinOp::BitwiseAnd, own, ka)?; let b_key = bin_k(fb, BinOp::BitwiseAnd, own, kb)?; + if ln.emu.is_none() { + let live = if divergent { + Some(ln.live_lanes(fb)?) + } else { + None + }; + let cells = Cells { + a_key, + b_key, + live, + a: pair(fb, a)?, + b: pair(fb, b)?, + }; + return paired_steps(fb, ln, how, &cells, acc); + } // Values 0 and 1 are the `a` cells, 2 and 3 the `b` cells. let ex = ln.exchange(fb, &[a[0], a[1], b[0], b[1]])?; - let live = match (divergent, &ln.emu) { - (true, None) => Some(ln.live_lanes(fb)?), - _ => None, - }; for k in 0..dim { let (va, vb) = owner_bits(dim, k); let ao = bin_k(fb, BinOp::BitwiseOr, a_key, va)?; let ao = ln.absolute(fb, ao)?; - let ao = ln.cell_source(fb, live, ao)?; let bo = bin_k(fb, BinOp::BitwiseOr, b_key, vb)?; let bo = ln.absolute(fb, bo)?; - let bo = ln.cell_source(fb, live, bo)?; let av = ln.read(fb, &ex, (k & 1) as usize, ao)?; for (j, slot) in acc.iter_mut().enumerate() { let bv = ln.read(fb, &ex, 2 + j, bo)?; @@ -643,6 +658,141 @@ pub(super) fn tile_mad( Ok(acc) } +/// The calling lane's owner keys ([`kept_bits`]), the lanes taking part where the multiply-add is +/// [`TileMad::divergent`], and the calling lane's `a` and `b` cells, each pair a `vec2`, of a +/// multiply-add on a subgroup. +#[derive(Clone, Copy)] +struct Cells { + a_key: SValue, + b_key: SValue, + live: Option, + a: SValue, + b: SValue, +} + +/// The `vec2` of cells `x`. +fn pair(fb: &mut FunctionBuilder<'_>, x: [SValue; 2]) -> BResult { + let f = fb.value_ty(x[0])?; + let v2 = fb.vec_of(f, 2)?; + fb.composite_construct(v2, &x) +} + +/// The `a` cells of steps `2m` and `2m + 1` (`va` their owner's bits, [`owner_bits`], which keeps +/// bit 0 of the step out of the `a` owner), as the `vec2` of the owner's two cells. +fn a_pair(fb: &mut FunctionBuilder<'_>, ln: &Lane, cells: &Cells, va: SValue) -> BResult { + let ao = fb.binary(BinOp::BitwiseOr, cells.a_key, va)?; + let ao = ln.absolute(fb, ao)?; + let ao = ln.cell_source(fb, cells.live, ao)?; + shuffle(fb, cells.a, ao) +} + +/// One step on `acc`: `av` its `a` cell, `vb` its `b` owner's bits, the step's two `b` cells read +/// as one `vec2`. +fn step( + fb: &mut FunctionBuilder<'_>, + ln: &Lane, + how: &TileMad, + cells: &Cells, + vb: SValue, + av: SValue, + acc: &mut [SValue; 2], +) -> BResult<()> { + let bo = fb.binary(BinOp::BitwiseOr, cells.b_key, vb)?; + let bo = ln.absolute(fb, bo)?; + let bo = ln.cell_source(fb, cells.live, bo)?; + let b2 = shuffle(fb, cells.b, bo)?; + for (j, slot) in acc.iter_mut().enumerate() { + let bv = fb.composite_extract(b2, &[j as u32])?; + let r = fb.glsl(GlslOp::Fma, &[av, bv, *slot])?; + *slot = narrow::round(fb, how.step, r)?; + } + Ok(()) +} + +/// [`owner_bits`] of the step `k` a loop's trip computes. +fn owner_bits_of(fb: &mut FunctionBuilder<'_>, dim: u32, k: SValue) -> BResult<(SValue, SValue)> { + if dim == 4 { + let a = bin_k(fb, BinOp::ShiftRightLogical, k, 1)?; + let a = bin_k(fb, BinOp::BitwiseAnd, a, 1)?; + let b = bin_k(fb, BinOp::ShiftLeftLogical, k, 1)?; + Ok((a, b)) + } else { + let a_hi = bin_k(fb, BinOp::BitwiseAnd, k, 4)?; + let a_hi = bin_k(fb, BinOp::ShiftLeftLogical, a_hi, 1)?; + let a_lo = bin_k(fb, BinOp::ShiftRightLogical, k, 1)?; + let a_lo = bin_k(fb, BinOp::BitwiseAnd, a_lo, 1)?; + let a = fb.binary(BinOp::BitwiseOr, a_hi, a_lo)?; + let b_lo = bin_k(fb, BinOp::BitwiseAnd, k, 3)?; + let b_lo = bin_k(fb, BinOp::ShiftLeftLogical, b_lo, 1)?; + let b_hi = bin_k(fb, BinOp::BitwiseAnd, k, 4)?; + let b_hi = bin_k(fb, BinOp::ShiftLeftLogical, b_hi, 2)?; + let b = fb.binary(BinOp::BitwiseOr, b_lo, b_hi)?; + Ok((a, b)) + } +} + +/// The steps of a multiply-add on a subgroup: a loop (`DontUnroll`, as `spirv::roll` writes one) +/// of `dim / 2` trips, trip `m` taking steps `2m` and `2m + 1`, the sums carried in `Function` +/// variables. Each step reads the cells the written-out steps read and accumulates them in the +/// same order. +fn paired_steps( + fb: &mut FunctionBuilder<'_>, + ln: &Lane, + how: &TileMad, + cells: &Cells, + acc: [SValue; 2], +) -> BResult<[SValue; 2]> { + let f = fb.value_ty(acc[0])?; + let u = fb.uint_ty(32)?; + let mut sums = [acc[0]; 2]; + for (v, x) in sums.iter_mut().zip(acc) { + let var = fb.local_var(f, None)?; + let p = fb.var_ptr(var)?; + fb.store(p, x, MemAccess::default())?; + *v = p; + } + let iv = fb.local_var(u, None)?; + let ip = fb.var_ptr(iv)?; + let zero = super::group::k(fb, 0)?; + fb.store(ip, zero, MemAccess::default())?; + let trips = how.dim / 2; + let body: LoopFn<'_, ()> = Box::new(move |fb, cx, lc| { + let i = fb.load(ip, MemAccess::default())?; + let done = bin_k(fb, BinOp::UGreaterThanEqual, i, trips)?; + let exit: ArmFn<'_, ()> = Box::new(move |fb, _| { + lc.break_(fb)?; + Ok(ArmEnd::Exits) + }); + fb.if_(cx, done, exit, None)?; + let next = bin_k(fb, BinOp::IAdd, i, 1)?; + fb.store(ip, next, MemAccess::default())?; + let mut acc = [ + fb.load(sums[0], MemAccess::default())?, + fb.load(sums[1], MemAccess::default())?, + ]; + let k0 = bin_k(fb, BinOp::ShiftLeftLogical, i, 1)?; + let (va, vb0) = owner_bits_of(fb, how.dim, k0)?; + let av2 = a_pair(fb, ln, cells, va)?; + let av = fb.composite_extract(av2, &[0])?; + step(fb, ln, how, cells, vb0, av, &mut acc)?; + let k1 = bin_k(fb, BinOp::BitwiseOr, k0, 1)?; + let (_, vb1) = owner_bits_of(fb, how.dim, k1)?; + let av = fb.composite_extract(av2, &[1])?; + step(fb, ln, how, cells, vb1, av, &mut acc)?; + fb.store(sums[0], acc[0], MemAccess::default())?; + fb.store(sums[1], acc[1], MemAccess::default()) + }); + let spec = LoopSpec { + exit_sel: None, + unrolling: Unrolling::DontUnroll, + }; + fb.loop_(&mut (), spec, body)?; + Ok([ + fb.load(sums[0], MemAccess::default())?, + fb.load(sums[1], MemAccess::default())?, + ]) +} + /// Emit strategy `s` of call `at` and bind its result. pub(super) fn emit( cx: &mut EmitCx<'_>, diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 66e8a988b..febd255e5 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -325,8 +325,9 @@ pub struct ModuleStats { /// name as reading or computing alone (an interlock, a ray query) makes it not inert. #[cfg_attr(feature = "serde", serde(default))] pub inert: bool, - /// The entry's weight: its instructions with each call counted as its callee's body, as a - /// driver inlines every call, after the repeated regions are rolled. A stage that weighs more + /// The entry's weight as the stage bound weighs it: its instructions with each call counted + /// as its callee's body, as a driver inlines every call, and each subgroup instruction as 64 + /// instructions, after the repeated regions are rolled. A stage that weighs more /// than [`COMPILED_STAGE_WEIGHT`](crate::pipeline::COMPILED_STAGE_WEIGHT) is one whose /// creation may take the host's memory: `metal2vulkan-runtime` compiles it only in a helper /// process the consumer caps. 0 for a stage the link makes itself. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 31b7f6d8a..f3246e5e6 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -1838,6 +1838,25 @@ pub(crate) fn compile_bitcode_bounded( }) } +/// One plan of `bitcode`'s entry with default lowering inputs, keeping the widest mode's pin or +/// weighing it as `widest` says, and its module emitted and weighed as the stage bound makes each +/// plan it compares (`stage_bound`), with that weight. +#[cfg(test)] +pub(crate) fn emit_bitcode_as( + bitcode: &[u8], + entry: EntryRef<'_>, + p: &DeviceProfile, + widest: crate::lower::simd::WidestPin, + m: &mut Meter, +) -> Result<(Plan, TypedModule, u64), Error> { + guarded(|| { + let consts = FunctionConstantValues::defaults(); + let inputs = LowerInputs::new(); + let r = Request::bitcode(bitcode, entry, &consts, &[], &inputs); + stage_bound::emit_as(&r, p, widest, m) + }) +} + /// Stage `fd` compiled with default lowering inputs as [`compile_stage`] compiles it, or as /// [`compile_stage_from`] compiles it reading `entries` where given, under the stage bounds /// `bounds` in place of [`StageBounds::MEASURED`]: so a test reaches each bound with a small diff --git a/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs b/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs index 2da572a88..92460c167 100644 --- a/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs +++ b/crates/metal2vulkan/src/pipeline/compile/stage_bound.rs @@ -5,16 +5,19 @@ //! the pipeline, so one heavy creation may take the host's memory. No Vulkan query states how large //! a stage a device's compiler takes, so the bound is one for every device. //! -//! Every module's entry is weighed (`spirv::roll::entry_weight`: the entry's instructions with each -//! call counted as its callee's body, as the driver inlines every call) after the repeated regions -//! are rolled, and the weight is the module's ([`ModuleStats::entry_weight`]). A kernel past the -//! bound that took the `Emulated` simdgroup tier only in place of the `Direct` tier's pin to the -//! device's widest mode (`lower::simd::widest_pin`) is planned again keeping the pin -//! (`lower::simd::WidestPin::Kept`), its emulated module dropped and what its plan and emission +//! Every module's entry is weighed after the repeated regions are rolled +//! (`spirv::roll::bound_weight`: the entry's instructions with each call counted as its callee's +//! body, as the driver inlines every call, and each subgroup instruction counted as +//! `spirv::roll::SUBGROUP_WEIGHT` instructions), and the weight is the module's +//! ([`ModuleStats::entry_weight`]). A kernel past the bound that took the `Emulated` simdgroup tier +//! only in place of the `Direct` tier's pin to the device's widest mode (`lower::simd::widest_pin`) +//! is planned again keeping the pin (`lower::simd::WidestPin::Kept`), and both modules are held: +//! the re-plan takes the pinned module where it weighs less than the emulated one by the stage +//! weight; otherwise the emulated one goes on. The other plan and module are dropped and what they //! hold of the ledger released. Only the selection is made again: the entry is decoded, //! specialized, ordered and analyzed once, so the kernel is charged what any compile of it is -//! charged, whichever path reached it (`super::Analyzed`). Every other module past the bound, a -//! kernel planned again that still is among them, is made as it weighs: whoever creates its +//! charged, whichever path reached it (`super::Analyzed`). Every other module past the bound, and +//! the one a re-plan takes where it still is among them, is made as it weighs: whoever creates its //! pipeline reads the weight against [`COMPILED_STAGE_WEIGHT`] (`metal2vulkan-runtime` compiles //! such a kernel only in a helper process the consumer caps). //! @@ -32,15 +35,20 @@ //! 424,132 passed its 3 GiB cap (job m3-max-65807). No margin is taken below it: it rises when a //! heavier kernel is measured to compile within 512 MiB. It is the kernels' bound: //! `metal2vulkan-runtime` refuses a render stage only past a bound of its own, as no helper -//! compiles a render stage (its README, "Kernels past the stage bound"). +//! compiles a render stage (its README, "Kernels past the stage bound"). The helper's kernels of +//! 121,523 to 424,132 hold no subgroup instruction as the RTX 3090's and the Iris Xe's profiles +//! lower them, so each weighs the same with or without `spirv::roll::SUBGROUP_WEIGHT` (jobs +//! m3-max-68033 and m3-max-68034). //! //! [`ModuleStats::entry_weight`]: crate::pipeline::ModuleStats::entry_weight -use super::{analyze_one, Planned, Request}; +use super::{analyze_one, Analyzed, Planned, Request}; use crate::budget::Meter; use crate::device::DeviceProfile; use crate::error::Error; +use crate::library::KernelFacts; use crate::lower::emit::Emitted; +use crate::lower::select::Plan; use crate::lower::simd::WidestPin; /// The heaviest entry weight ([`ModuleStats::entry_weight`]) of a kernel measured to compile within @@ -50,7 +58,7 @@ use crate::lower::simd::WidestPin; /// [`ModuleStats::entry_weight`]: crate::pipeline::ModuleStats::entry_weight pub const COMPILED_STAGE_WEIGHT: u64 = 39_014; -/// The entry weight past which a kernel is planned again keeping its pin: the compiled one in +/// The weight past which a kernel is planned again keeping its pin: the compiled one in /// production ([`StageBounds::MEASURED`]), another in a test, so it reaches the bound with a small /// module. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -66,9 +74,9 @@ impl StageBounds { }; } -/// `r`'s function planned and emitted with its repeated regions rolled, with its entry weight: -/// planned again keeping the widest mode's pin where only that pin's emulation passed `bounds` -/// (the module docs). +/// `r`'s function planned and emitted with its repeated regions rolled, with its bound weight: +/// where only the widest mode's pin's emulation passed `bounds`, planned again keeping the pin and +/// the lighter of the two modules taken (the module docs). pub(super) fn emit( r: &Request<'_>, p: &DeviceProfile, @@ -76,34 +84,95 @@ pub(super) fn emit( m: &mut Meter, ) -> Result<(Planned, Emitted, u64), Error> { let analyzed = analyze_one(r, p, m)?; - let mut widest = WidestPin::Weighed; - loop { - let before = m.ledger(); - let (plan, kernel) = analyzed.select(p, widest, m)?; - let mut emitted = m.weighted(crate::pipeline::compile::weights::EMIT, |m| { - crate::lower::emit::emit_module(&analyzed.spec, &plan, m) - })?; - // Every driver compiles each repeated region of the entry again; above the measured size, - // repeated regions are written once, as a loop. - m.weighted(crate::pipeline::compile::weights::ROLL, |m| { - crate::spirv::roll::roll_entry(&mut emitted.module, m) - })?; - // A load of a uniform view that every trip of its loop reads alike leaves the loop. - m.weighted(crate::pipeline::compile::weights::HOIST, |m| { - crate::spirv::hoist::hoist_uniform_loads(&mut emitted.module, m) - })?; - // A structurizer variable whose value no later trip of a loop reads is ended at each - // trip's top, so the driver carries none of it around the loop. - crate::spirv::carry::end_dead_carries(&mut emitted.module, m)?; - let weight = crate::spirv::roll::entry_weight(&emitted.module, m)?; - if weight <= bounds.compiled || widest == WidestPin::Kept || !plan.families.simd.widest_pin - { - return Ok((analyzed.planned(plan, kernel), emitted, weight)); - } - // The emulated plan and module go, and with them what they hold of the ledger. - drop((plan, emitted)); - let held = m.ledger().saturating_sub(before); - m.release(usize::try_from(held).unwrap_or(usize::MAX)); - widest = WidestPin::Kept; + let weighed = made(&analyzed, p, WidestPin::Weighed, m)?; + if weighed.weight <= bounds.compiled || !weighed.plan.families.simd.widest_pin { + return Ok(weighed.planned(analyzed)); + } + // Past the bound only as the pin's emulation: the plan keeping the pin, both held. + let emulated = weighed; + let pinned = made(&analyzed, p, WidestPin::Kept, m)?; + let (on, off) = if pinned.weight < emulated.weight { + (pinned, emulated) + } else { + (emulated, pinned) + }; + // The other plan and module go, and with them what they hold of the ledger. + let held = off.held; + drop(off); + m.release(usize::try_from(held).unwrap_or(usize::MAX)); + Ok(on.planned(analyzed)) +} + +/// `r`'s function planned keeping the widest mode's pin or weighing it as `widest` says, emitted as +/// [`emit`] makes each plan it compares, with its module's bound weight. +#[cfg(test)] +pub(super) fn emit_as( + r: &Request<'_>, + p: &DeviceProfile, + widest: WidestPin, + m: &mut Meter, +) -> Result<(Plan, crate::spirv::ir::TypedModule, u64), Error> { + let analyzed = analyze_one(r, p, m)?; + let Made { + plan, + emitted, + weight, + .. + } = made(&analyzed, p, widest, m)?; + Ok((plan, emitted.module, weight)) +} + +/// One plan of an analyzed kernel, its module, the module's bound weight, and what the plan and +/// module hold of the ledger. +struct Made { + plan: Plan, + kernel: KernelFacts, + emitted: Emitted, + weight: u64, + held: u64, +} + +impl Made { + fn planned(self, analyzed: Analyzed) -> (Planned, Emitted, u64) { + ( + analyzed.planned(self.plan, self.kernel), + self.emitted, + self.weight, + ) } } + +/// `analyzed` planned keeping the widest mode's pin or weighing it as `widest` says, emitted with +/// its repeated regions rolled, and weighed. +fn made( + analyzed: &Analyzed, + p: &DeviceProfile, + widest: WidestPin, + m: &mut Meter, +) -> Result { + let before = m.ledger(); + let (plan, kernel) = analyzed.select(p, widest, m)?; + let mut emitted = m.weighted(crate::pipeline::compile::weights::EMIT, |m| { + crate::lower::emit::emit_module(&analyzed.spec, &plan, m) + })?; + // Every driver compiles each repeated region of the entry again; above the measured size, + // repeated regions are written once, as a loop. + m.weighted(crate::pipeline::compile::weights::ROLL, |m| { + crate::spirv::roll::roll_entry(&mut emitted.module, m) + })?; + // A load of a uniform view that every trip of its loop reads alike leaves the loop. + m.weighted(crate::pipeline::compile::weights::HOIST, |m| { + crate::spirv::hoist::hoist_uniform_loads(&mut emitted.module, m) + })?; + // A structurizer variable whose value no later trip of a loop reads is ended at each + // trip's top, so the driver carries none of it around the loop. + crate::spirv::carry::end_dead_carries(&mut emitted.module, m)?; + let weight = crate::spirv::roll::bound_weight(&emitted.module, m)?; + Ok(Made { + plan, + kernel, + emitted, + weight, + held: m.ledger().saturating_sub(before), + }) +} diff --git a/crates/metal2vulkan/src/spirv/roll/mod.rs b/crates/metal2vulkan/src/spirv/roll/mod.rs index 69d889f84..216d2ecaf 100644 --- a/crates/metal2vulkan/src/spirv/roll/mod.rs +++ b/crates/metal2vulkan/src/spirv/roll/mod.rs @@ -228,12 +228,26 @@ impl KeyCache { /// phis, and its instructions, a call counting as its callee's whole body (SPIRV-Cross writes /// every function inlined at each call). pub fn entry_weight(m: &TypedModule, meter: &mut Meter) -> Result { - let w = weights(m, meter)?; + let w = weights(m, 1, meter)?; Ok(w.get(m.entry.func.index()).copied().unwrap_or(0)) } -/// [`entry_weight`] of every function. -fn weights(m: &TypedModule, meter: &mut Meter) -> Result, Error> { +/// What the stage bound weighs `m`'s entry at: [`entry_weight`] with each subgroup instruction +/// (`OpGroupNonUniform*`) counted as [`SUBGROUP_WEIGHT`] instructions. The two weights answer two +/// questions: [`entry_weight`] what a driver compiles, which decides where the roll writes a +/// region once, and this one what a driver's compile takes, which grows with every subgroup +/// instruction many times faster than with any other. +pub fn bound_weight(m: &TypedModule, meter: &mut Meter) -> Result { + let w = weights(m, SUBGROUP_WEIGHT, meter)?; + Ok(w.get(m.entry.func.index()).copied().unwrap_or(0)) +} + +/// The instructions one subgroup instruction counts as in [`bound_weight`]. +pub const SUBGROUP_WEIGHT: u64 = 64; + +/// The weight of every function: [`entry_weight`]'s, with each subgroup instruction counted as +/// `group` instructions. +fn weights(m: &TypedModule, group: u64, meter: &mut Meter) -> Result, Error> { let n = m.functions.len(); let mut w = vec![0u64; n]; // 0: not reached, 1: callees pending, 2: weighed. @@ -274,7 +288,11 @@ fn weights(m: &TypedModule, meter: &mut Meter) -> Result, Error> { .saturating_add(1) .saturating_add(block.phis.len() as u64); for node in &block.insts { - total = total.saturating_add(inst_weight(node, &w)); + let one = match node.inst { + Inst::Group { .. } => group, + _ => inst_weight(node, &w), + }; + total = total.saturating_add(one); } } if let Some(x) = w.get_mut(f) { @@ -745,7 +763,7 @@ fn find( meter: &mut Meter, ledger: &mut usize, ) -> Result, Error> { - let w = weights(m, meter)?; + let w = weights(m, 1, meter)?; // The entry and every function it calls, heaviest first: a stage's code may sit in a // function its entry calls (a fragment function's in the routine its entry point calls // between reading its inputs and writing its outputs). diff --git a/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs b/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs index b7210df43..0d6a517d5 100644 --- a/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs +++ b/crates/metal2vulkan/src/tests/engine_simd_lockstep.rs @@ -2326,25 +2326,26 @@ fn a_pressured_kernel_takes_the_emulated_tier_in_place_of_the_widest_mode() { } /// Every stage is weighed against the compiled bound (here bounds the test sets), whatever the -/// driver: the pressured kernel of +/// driver, by the stage weight (`spirv::roll::bound_weight`): the pressured kernel of /// `a_pressured_kernel_takes_the_emulated_tier_in_place_of_the_widest_mode`, whose emulated module -/// passes the bound, is planned again keeping the `Direct` tier's pin to 32 lanes, its answers -/// Metal's; under a bound its `Direct` module passes too, it is made as it weighs, its stats naming -/// its entry weight (`ModuleStats::entry_weight`), for the runtime to compile apart. +/// passes the bound, is planned again, and its module keeping the `Direct` tier's pin to 32 lanes, +/// which weighs less, is taken, its answers Metal's; under a bound its `Direct` module passes too, +/// it is made as it weighs, its stats naming its weight (`ModuleStats::entry_weight`), for the +/// runtime to compile apart. #[test] fn every_stage_from_queries_keeps_the_widest_pin_or_states_its_weight() { use crate::device::Device; use crate::lower::simd::{WIDEST_PIN, WIDEST_PIN_FLOOR, WIDEST_PIN_WORDS}; use crate::pipeline::compile::{compile_bitcode_bounded, StageBounds}; use crate::pipeline::testing::meter; - use crate::spirv::roll::entry_weight; + use crate::spirv::roll::bound_weight; let half = |t: u32| if t & 31 < 16 { t ^ 1 } else { t }; let fan = Padding::Fan((WIDEST_PIN_FLOOR / 2 + 16).max(WIDEST_PIN_WORDS as usize + 8)); let Some(bc) = assemble("device_half", &device_half_padded(fan, None)) else { return; }; let entry = EntryRef::Name("device_half"); - let weight = |module: &TypedModule| entry_weight(module, &mut meter()).expect("weight"); + let weight = |module: &TypedModule| bound_weight(module, &mut meter()).expect("weight"); let want: Vec = (0..64).map(half).collect(); let desc = crate::pipeline::testing::description("intel-irisxe-rplp-anv").unwrap(); let queries = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap(); @@ -2391,7 +2392,7 @@ fn a_kernel_past_the_stage_bound_gets_one_answer_through_either_path() { }; use crate::pipeline::testing::meter; use crate::pipeline::FunctionDescriptor; - use crate::spirv::roll::entry_weight; + use crate::spirv::roll::bound_weight; let fan = Padding::Fan((WIDEST_PIN_FLOOR / 2 + 16).max(WIDEST_PIN_WORDS as usize + 8)); let Some(bc) = assemble("device_half", &device_half_padded(fan, None)) else { return; @@ -2412,7 +2413,7 @@ fn a_kernel_past_the_stage_bound_gets_one_answer_through_either_path() { at(cap), ); let (_, _, module) = compiled.expect("compiled"); - entry_weight(&module, &mut meter()).expect("weight") + bound_weight(&module, &mut meter()).expect("weight") }; let emulated = weight(u64::MAX); let pinned = weight(emulated - 1); @@ -2470,17 +2471,24 @@ fn a_kernel_past_the_stage_bound_gets_one_answer_through_either_path() { /// measured stage bounds (`StageBounds::MEASURED`). On the Iris Xe under the identity domains, /// whose subgroup size range offers the widest mode's pin and which has maximal reconvergence, the /// kernel emulates its simdgroups, a module past the compiled bound, and is planned again keeping -/// the pin, a module under it. The same description without maximal reconvergence emulates its simdgroups for the -/// lockstep pair, so it has no pin to keep: it is made as it weighs, past the bound, its stats -/// naming the emulated module's weight, under any driver (Intel's Windows driver too). +/// the pin. The pinned module weighs less by the entry weight (`spirv::roll::entry_weight`), under +/// the bound, and more by the stage weight (`spirv::roll::bound_weight`), its multiply-adds' +/// subgroup instructions counted as `spirv::roll::SUBGROUP_WEIGHT` each: the re-plan takes the +/// lighter by the stage weight, the emulated module, made as it weighs, its stats naming its +/// weight (where the pin was taken whatever it weighed, this fails). The same description without +/// maximal reconvergence emulates its simdgroups for the lockstep pair, so it has no pin to keep: +/// it is made as it weighs, past the bound, its stats naming the emulated module's weight, under +/// any driver (Intel's Windows driver too). #[test] -fn the_stage_bound_fixture_keeps_the_pin_or_states_its_weight() { +fn the_stage_bound_fixture_takes_the_lighter_module_or_states_its_weight() { use crate::device::profile::DeviceProfile; use crate::device::{Device, DeviceDescription}; - use crate::lower::simd::WIDEST_PIN; - use crate::pipeline::compile::{compile_bitcode_bounded, compile_bitcode_kept, StageBounds}; + use crate::lower::simd::{WidestPin, WIDEST_PIN}; + use crate::pipeline::compile::{ + compile_bitcode_bounded, compile_bitcode_kept, emit_bitcode_as, StageBounds, + }; use crate::pipeline::testing::meter; - use crate::spirv::roll::entry_weight; + use crate::spirv::roll::{bound_weight, entry_weight}; let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../metal2vulkan-validation/fixtures/public/stage_bound"); let bc = match llvm_assemble(&dir.join("stage_bound_matrix.ll")) { @@ -2492,7 +2500,8 @@ fn the_stage_bound_fixture_keeps_the_pin_or_states_its_weight() { Err(AssembleError::Rejected(e)) => panic!("llvm-as rejected the fixture: {e}"), }; let entry = EntryRef::Name("stage_bound_matrix"); - let weight = |module: &TypedModule| entry_weight(module, &mut meter()).expect("weight"); + let weight = |module: &TypedModule| bound_weight(module, &mut meter()).expect("weight"); + let entry_only = |module: &TypedModule| entry_weight(module, &mut meter()).expect("weight"); let bound = StageBounds::MEASURED.compiled; let unbounded = StageBounds { compiled: u64::MAX }; let inputs = LowerInputs::new(); @@ -2513,14 +2522,30 @@ fn the_stage_bound_fixture_keeps_the_pin_or_states_its_weight() { let compiled = compile_bitcode_bounded(&bc, entry, p, &mut meter(), unbounded); let (_, plan, module) = compiled.expect("emulated"); assert_eq!((plan.simd.1, uses(&plan, WIDEST_PIN)), (Tier::Emulated, 1)); - let emulated = weight(&module); - assert!(emulated > bound, "emulated {emulated}"); - // Under the measured bounds: planned again keeping the pin, under the bound. - let (_, plan, module) = kept(p).expect("planned again"); + let emulated = (entry_only(&module), weight(&module)); + assert!(emulated.1 > bound, "emulated {emulated:?}"); + // The plan keeping the pin: under the bound by the entry weight, heavier than the + // emulated module by the stage weight. + let pinned = emit_bitcode_as(&bc, entry, p, WidestPin::Kept, &mut meter()); + let (plan, module, stated) = pinned.expect("pinned"); assert_eq!((plan.simd.1, uses(&plan, WIDEST_PIN)), (Tier::Direct, 0)); assert_eq!(plan.subgroup.size, Some(32)); - let pinned = weight(&module); - assert!(pinned <= bound, "pinned {pinned}"); + let pinned = (entry_only(&module), weight(&module)); + assert_eq!(stated, pinned.1); + assert!( + pinned.0 <= bound, + "pinned {pinned:?}, emulated {emulated:?}" + ); + assert!( + pinned.1 > emulated.1, + "pinned {pinned:?}, emulated {emulated:?}" + ); + // Under the measured bounds: planned again, and the lighter, the emulated module, made as + // it weighs. + let (function, plan, module) = kept(p).expect("planned again"); + assert_eq!((plan.simd.1, uses(&plan, WIDEST_PIN)), (Tier::Emulated, 1)); + assert_eq!((entry_only(&module), weight(&module)), emulated); + assert_eq!(function.module_stats().entry_weight, emulated.1); } // Without maximal reconvergence: emulated for the lockstep pair, with no pin to keep. let cleared = text.replace( diff --git a/crates/metal2vulkan/src/tests/engine_simd_partly_live.rs b/crates/metal2vulkan/src/tests/engine_simd_partly_live.rs index 15c63bfe0..51e1fb2b3 100644 --- a/crates/metal2vulkan/src/tests/engine_simd_partly_live.rs +++ b/crates/metal2vulkan/src/tests/engine_simd_partly_live.rs @@ -710,8 +710,9 @@ fn opcodes(words: &[u32], op: crate::spv::Op) -> usize { /// On the subgroup tiers only a multiply-add in a block the uniformity analysis cannot prove /// uniform takes the live-lane form: `dsm_half_live_loaded`'s two are planned divergent, raise the -/// class with `Ballot`, and emit one ballot each and two bit extracts per step (the `a` and the `b` -/// owner); `dsm_uniform`'s two keep their plain shuffles. +/// class with `Ballot`, and emit one ballot each and, in the loop of their step pairs, three bit +/// extracts (the `a` pair's owner and each step's `b` owner); `dsm_uniform`'s two keep their plain +/// shuffles. #[test] fn only_divergent_multiply_adds_ballot_their_lanes() { let (Some(divergent), Some(uniform)) = @@ -731,7 +732,7 @@ fn only_divergent_multiply_adds_ballot_their_lanes() { ); assert_eq!( opcodes(&words, crate::spv::Op::GroupNonUniformBallotBitExtract), - 2 * 2 * 8, + 2 * 3, "{stem}" ); let (plan, _, words) = on_tier(&uniform, "dsm_uniform", &p, tier); diff --git a/docs/API.md b/docs/API.md index 690a64a53..a0c34c2b0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -523,15 +523,19 @@ assert!(stats.reachable_blocks <= stats.blocks); a program far larger than its own blocks; the two read alike in `blocks` alone. Lowering emits such functions itself: the handle-table search (unrolled branch-free steps) and the root-table search (a loop), each emitted once and called at every access. -- `entry_weight` is what a driver compiles once it has inlined every call: the entry's - instructions with each call counted as its callee's body, after repeated regions are rolled - into loops. A kernel past `pipeline::COMPILED_STAGE_WEIGHT` (39,014, the heaviest kernel +- `entry_weight` is what the stage bound weighs: what a driver compiles once it has inlined every + call, the entry's instructions with each call counted as its callee's body, after repeated + regions are rolled into loops, with each subgroup instruction counted as 64 instructions, as a + driver's compile grows with one many times faster than with any other instruction. A kernel + past `pipeline::COMPILED_STAGE_WEIGHT` (39,014, the heaviest kernel measured to compile within 512 MiB of its creating process's resident growth on every driver measured) is one whose creation may take the host's memory: the translator makes it all the same, and `metal2vulkan-runtime` compiles such a kernel only in a helper process the consumer caps (its README, "Kernels past the stage bound", which gives the figures and the render stages' own bound). A kernel past the bound only because it emulates its SIMD groups is planned - again keeping the device's widest subgroup mode pinned, where that plan is lighter. + again keeping the device's widest subgroup mode pinned: the re-plan takes the pinned module + where it weighs less than the emulated one by the stage weight; otherwise the emulated one goes + on. - Compare one module against the next of the same shader, not one shader against another. Measured cost per block differed several-fold between a synthetic module and a real workload, so a per-block figure taken from one shader predicts nothing for the next; `instructions` is the