SEMANTICS 2121 / RUNTIME 2331: A kernel's unit-axes variant, taken once made, never waited for
A kernel's unit-axes variant: the translator and the binding plan
In a threadgroup of one thread along an axis (Metal's threads_per_threadgroup 1
there), every thread's thread_position_in_threadgroup on that axis is 0 and its
thread_position_in_grid is its threadgroup's position, partial threadgroups
included. A kernel whose emulated simdgroups are walked predicated only because
such a position steers a synchronization (a simdgroup sum in a loop whose trip
count reads gid.y, the shape of a depthwise convolution dispatched in 8x1x16
threadgroups) pays the predicated walk's live flags and votes for nothing.
- lower::simd::uniform tracks per-lane masks for vectors of up to 8 lanes, and
takes the lanes of thread_position_in_threadgroup and thread_position_in_grid
on the unit axes LoweringInputs::unit_axes names as uniform.
- A kernel walked predicated (divergent::barriers, workgroup::check) states
RuntimeFact::UnitAxes { axes: 0, relief }: bit m-1 for each mask m of axes
under which fewer of its synchronizing blocks stay divergent (one analysis
for all three axes, then the six others only where that one relieves).
- VariantKey::unit_axes compiles the variant; its module states
UnitAxes { axes, relief: 0 }.
- BindingPlan::unit_axes_variant offers the variant to a dispatch whose
threadgroups have one thread along relieving axes, where the plan's own
variant runs it; the variant's plan sends any other dispatch back
(dispatch_variant, NeedsVariant).
SEMANTICS_VERSION 2121: a predicated kernel's artifact states a new fact.
No new Degradation kind.
Test: engine_simd_unit_axes (lavapipe's profile, CPU interpreter, 8/16/32
lanes): predicated without the variant, unpredicated with it, Metal's words
in both; the variant traps at two threads along y (Vulkan's barrier rule), unit
x relieves nothing, and a kernel steered by x is offered no variant for unit y.
The runtime takes a kernel's unit-axes variant once it is made, never waiting
A direct dispatch whose plan offers the unit-axes variant
(BindingPlan::unit_axes_variant) takes it only where its translation is
done and each of its regions' VkPipelines is made (pipeline/unit_axes.rs).
Otherwise it settles on its plain variant, which gives the same answers,
and the variant is begun: its translation as a piece on the pipeline pool,
kept by the state (piece_holds.rs), at the first such dispatch; its objects
and pipeline notices on the program's thread at the next (no piece announces
a notice), with its regions' makings handed to the pool as any dispatch's
are. Nothing waits for the translation or a making. A dispatch planned
meanwhile is kept neither in the state's latest plans nor in its encoder's
memo, so a later one asks again. A refused translation or a failed making is
remembered, the plain variant then running those dispatches; the state tracks
at most VARIANTS such variants at once, and they live among its VARIANTS
others.
The dispatch that begins it is recorded for a later process's warm pass,
which compiles the variant and makes its regions beside the plain variant's.
The one-row and emulated-simdgroups variants are still compiled on the
encoding thread when a dispatch first asks (ComputePipelineState::settle ->
variant -> Variant::compile); this path does not follow them.
WorkCounts: unit_axes_variants_begun, unit_axes_dispatches,
unit_axes_meanwhile. No new Degradation kind. docs/API.md section 3 and the
bind module's docs state the rule and the variant; api_signatures.tsv
blessed.
Test: tests::unit_axes (m2v_gpu / m2v_cpu_icd): a 16-thread threadgroup
kernel whose simdgroup sum sits in a loop steered by gid.y; 4x2x2 never begins
the variant; 8x1x2 begins it once, runs on the plain variant meanwhile, then
settles on it, Metal's words every time.
A unit-axes variant's objects are made under its state's lock of begun variants
Two dispatches of one state could both find a translated variant gone from
the begun set while the first made its objects, and the second begin its
translation again. The first now makes them under the lock, as variant()
compiles under the lock of the state's variants.
Public: RuntimeFact::UnitAxes { axes, relief }, VariantKey.unit_axes,
LoweringInputs.unit_axes, BindingPlan::unit_axes_variant; WorkCounts
unit_axes_variants_begun, unit_axes_dispatches, unit_axes_meanwhile. No new
Degradation kind.
Verified: job 31119 at 58f7ef3c21: workspace clippy under --cfg m2v_gpu,
metal2vulkan with no feature and each feature alone, rustdoc -D warnings.
Job 31118: metal2vulkan + runtime suites 5187/5188; the one failure is the
golden hash table (24 cells of rfs_async_copy_{1,2,4}, the expected
SEMANTICS change), re-blessed on development. Job 31098 at c7f44ff865: the
engine test tests::engine_simd_unit_axes and the runtime test
tests::unit_axes on lavapipe. Iris compile-only replay of a guest's records
(31117): one depthwise state takes the variant (driver estimate 2.47M ->
0.57M cycles, spills 179:340 -> 0); the GPU-time A/B is pending.
This commit is contained in:
1 parent
11663c0238
commit
3625b90721
31 files changed
+1563
-81
No files matched your search
@@ -88,7 +88,7 @@ use super::indirect_execute::{self, Execute, ExecutionRange};
|
||||
use super::live_bind::ValueKinds;
|
||||
use super::pending_dispatch::{PendingDispatch, Recording};
|
||||
use super::pipeline::{
|
||||
flat_dispatch, BufferForms, ComputePipelineState, Planned, RawPipeline, RegionKey,
|
||||
flat_dispatch, BufferForms, ComputePipelineState, Direct, Planned, RawPipeline, RegionKey,
|
||||
RegionPipeline, Variant, VariantObjects,
|
||||
};
|
||||
use super::predication::{self, Captures, Event};
|
||||
@@ -2100,19 +2100,26 @@ fn whole_grid(dispatch: &Dispatch) -> bool {
|
||||
/// `shape`: its flat variant where it takes one ([`flat_direct`]), else its partial-threadgroups
|
||||
/// variant where it takes one ([`partial_direct`]), else `ComputePipelineState::settle`'s. A program's dispatch plans so ([`plan_now`]), and so does a
|
||||
/// warm pass's dispatch of a record (`pipeline/dispatch_record.rs`), so both ask for the same
|
||||
/// variant and its regions' keys.
|
||||
/// variant and its regions' keys. A program's dispatch, of the bind state and bound formats
|
||||
/// `bound`, in the bound form, then takes that variant's unit-axes variant where its plan offers
|
||||
/// one and it is made (`ComputePipelineState::unit_axes`); a warm pass makes that one beside it.
|
||||
pub(crate) fn settle_direct(
|
||||
pipeline: &ComputePipelineState,
|
||||
shape: &BindShape,
|
||||
dispatch: &Dispatch,
|
||||
forms: BufferForms,
|
||||
) -> Result<(Arc<Variant>, Arc<BindingPlan>), Error> {
|
||||
if let Some(flat) = flat_direct(pipeline, shape, dispatch, forms)? {
|
||||
return Ok(flat);
|
||||
}
|
||||
match partial_direct(pipeline, shape, dispatch, forms)? {
|
||||
Some(partial) => Ok(partial),
|
||||
None => pipeline.settle(shape, dispatch, forms),
|
||||
bound: Option<(&BindState, BoundFormats<'_>)>,
|
||||
) -> Result<Direct, Error> {
|
||||
let settled = match flat_direct(pipeline, shape, dispatch, forms)? {
|
||||
Some(flat) => flat,
|
||||
None => match partial_direct(pipeline, shape, dispatch, forms)? {
|
||||
Some(partial) => partial,
|
||||
None => pipeline.settle(shape, dispatch, forms)?,
|
||||
},
|
||||
};
|
||||
match (bound, forms) {
|
||||
(Some(bound), BufferForms::Bound) => pipeline.unit_axes(settled, (shape, dispatch), bound),
|
||||
_ => Ok(Direct::of(settled)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2174,7 +2181,8 @@ fn settle_dispatch<'a>(
|
||||
Some(last) => (last, true, None),
|
||||
None => {
|
||||
let shape = Arc::new(state.shape());
|
||||
match plan_now(pipeline, tables.forms, shape, (direct, gpu))? {
|
||||
let bound = (&state, tables);
|
||||
match plan_now(pipeline, tables.forms, shape, (direct, gpu), bound)? {
|
||||
Some((planned, flat)) => (planned, false, flat),
|
||||
None => return Ok(None),
|
||||
}
|
||||
@@ -2232,10 +2240,13 @@ fn settle_live<'a>(
|
||||
direct.and_then(|dispatch| pipeline.planned_for(&shape, &dispatch, tables.forms));
|
||||
let (planned, as_before, flat) = match last {
|
||||
Some(last) => (last, true, None),
|
||||
None => match plan_now(pipeline, tables.forms, shape, (direct, gpu))? {
|
||||
Some((planned, flat)) => (planned, false, flat),
|
||||
None => return Ok(None),
|
||||
},
|
||||
None => {
|
||||
let bound = (&live.state, tables);
|
||||
match plan_now(pipeline, tables.forms, shape, (direct, gpu), bound)? {
|
||||
Some((planned, flat)) => (planned, false, flat),
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
};
|
||||
let set = planned.variant.pipeline().layout.sets.get(1);
|
||||
if heap_sets::fit_samplers(set, &mut argument_samplers, &mut unlisted) {
|
||||
@@ -2255,24 +2266,32 @@ fn settle_live<'a>(
|
||||
}
|
||||
|
||||
/// What a dispatch of a bind state of `shape` in `forms` plans now, of `direct` group counts or of
|
||||
/// a flat indirect call (`gpu`): the direct dispatch's flat variant where it takes one, else
|
||||
/// `ComputePipelineState::settle`'s; the indirect one's flat or folded variant, with its preprocess
|
||||
/// description, or `None` where neither takes it, which then takes its host step.
|
||||
/// a flat indirect call (`gpu`): the direct dispatch's variant as [`settle_direct`] settles it for
|
||||
/// the bind state `bound`'s, binding what `bound`'s tables bind; the indirect one's flat or folded
|
||||
/// variant, with its preprocess description, or `None` where neither takes it, which then takes
|
||||
/// its host step.
|
||||
fn plan_now<'a>(
|
||||
pipeline: &ComputePipelineState,
|
||||
forms: BufferForms,
|
||||
shape: Arc<BindShape>,
|
||||
(direct, gpu): (Option<Dispatch>, Option<FlatCall<'a>>),
|
||||
(state, tables): (&BindState, &DispatchTables<'_>),
|
||||
) -> Result<Option<(Arc<Planned>, Flat<'a>)>, Error> {
|
||||
match (direct, gpu) {
|
||||
(Some(dispatch), _) => {
|
||||
let (variant, plan) = settle_direct(pipeline, &shape, &dispatch, forms)?;
|
||||
// What the dispatch binds, as its specialized notices name it.
|
||||
let stages = [(Stage::Kernel, tables.table)];
|
||||
let bound = binding::Tables::new(&stages).with_residency(tables.residency);
|
||||
let formats: BoundFormats<'_> = &|slot| bound.bound_format(slot);
|
||||
let settled =
|
||||
settle_direct(pipeline, &shape, &dispatch, forms, Some((state, formats)))?;
|
||||
let planned = Planned {
|
||||
shape,
|
||||
dispatch,
|
||||
forms,
|
||||
variant,
|
||||
plan,
|
||||
variant: settled.variant,
|
||||
plan: settled.plan,
|
||||
meanwhile: settled.meanwhile,
|
||||
made: OnceLock::new(),
|
||||
twins: binding::TwinProofs::default(),
|
||||
};
|
||||
@@ -2288,6 +2307,7 @@ fn plan_now<'a>(
|
||||
forms,
|
||||
variant,
|
||||
plan,
|
||||
meanwhile: false,
|
||||
made: OnceLock::new(),
|
||||
twins: binding::TwinProofs::default(),
|
||||
};
|
||||
@@ -2298,8 +2318,8 @@ fn plan_now<'a>(
|
||||
}
|
||||
|
||||
/// Count a direct dispatch that took what its pipeline state planned before (`as_before`), or
|
||||
/// keep what one planned now for the next; a flat dispatch's variant and plan are the flat path's,
|
||||
/// none a direct one takes.
|
||||
/// keep what one planned now for the next, but where it is for now alone (`Planned::meanwhile`);
|
||||
/// a flat dispatch's variant and plan are the flat path's, none a direct one takes.
|
||||
fn planned_as_before(
|
||||
pipeline: &ComputePipelineState,
|
||||
planned: &Arc<Planned>,
|
||||
@@ -2310,8 +2330,8 @@ fn planned_as_before(
|
||||
(true, _) => (pipeline.generation().shared().counts)
|
||||
.thread()
|
||||
.dispatch_planned_as_before(),
|
||||
(false, Some(_)) => pipeline.keep_planned(Arc::clone(planned)),
|
||||
(false, None) => {}
|
||||
(false, Some(_)) if !planned.meanwhile => pipeline.keep_planned(Arc::clone(planned)),
|
||||
(false, _) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2596,7 +2616,8 @@ fn record(
|
||||
live.let_go();
|
||||
return Ok(false);
|
||||
};
|
||||
match memo {
|
||||
// What a dispatch settled for now alone is no entry's (`Planned::meanwhile`).
|
||||
match memo.filter(|_| !settled.planned.meanwhile) {
|
||||
Some(_) => live.memo.keep(tables, (moved, changed), settled),
|
||||
None => {
|
||||
live.let_go();
|
||||
|
||||
@@ -294,6 +294,7 @@ impl Program {
|
||||
base,
|
||||
stand_in: self.stand_in,
|
||||
others: Mutex::new(Lru::counted(VARIANTS)),
|
||||
unit_axes: Arc::default(),
|
||||
flat_refused: AtomicBool::new(false),
|
||||
call_flat_refused: AtomicBool::new(false),
|
||||
replay_refused: AtomicBool::new(false),
|
||||
|
||||
@@ -102,6 +102,8 @@ pub(crate) enum RegionHeld {
|
||||
Making(Arc<Variant>, RegionKey, Box<Ticket<RegionKey, RawPipeline>>),
|
||||
/// What a making gives back once settled, held until let go of: its variant.
|
||||
Made { _variant: Arc<Variant> },
|
||||
/// A unit-axes variant's translation (`unit_axes.rs`), and what it gives back.
|
||||
Compile(Box<super::unit_axes::CompilePiece>),
|
||||
}
|
||||
|
||||
impl RegionKey {
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
//! requires none makes each region's pipeline at its first dispatch, and the creation's record
|
||||
//! makes none of them on a later warm pass.
|
||||
//! - **A record per new dispatch.** Where the device hands records over, a state's direct dispatch
|
||||
//! (`dispatchThreadgroups:` or `dispatchThreads:`) whose regions' pipelines were not all made
|
||||
//! hands the hook one more record ([`ComputePipelineState::record_dispatch`]): the creation's
|
||||
//! (`dispatchThreadgroups:` or `dispatchThreads:`) whose regions' pipelines were not all made,
|
||||
//! or that began its kernel's unit-axes variant (`unit_axes.rs`), hands the hook one more record ([`ComputePipelineState::record_dispatch`]): the creation's
|
||||
//! descriptor, as its own record holds it, and the dispatch ([`RecordedDispatch`]: its
|
||||
//! threadgroup, its grid's ragged edge where it is a `dispatchThreads:`, and the encoder's
|
||||
//! threadgroup memory lengths). Each such dispatch once per state, at most
|
||||
@@ -22,7 +22,8 @@
|
||||
//! the program's direct dispatch does (`compute::settle_direct`: a ragged grid's flat variant
|
||||
//! where it takes one, else its partial-threadgroups variant where it takes that, as a large
|
||||
//! kernel's whole grid does too, compiled where it is not the base), and makes each region's
|
||||
//! `VkPipeline`
|
||||
//! `VkPipeline`, and those of the unit-axes variant the program's dispatch takes once it is
|
||||
//! made where the plan offers one (`unit_axes.rs`), compiled there,
|
||||
//! on the pass's thread, below every other making: its translation lands in the shader cache and
|
||||
//! its driver data in its record, under the names a later dispatch of the same shape asks for. A
|
||||
//! dispatch whose bindings specialize its regions otherwise (a bound texture's format the
|
||||
@@ -30,10 +31,11 @@
|
||||
//! own as before.
|
||||
|
||||
use super::dispatch_making::predicted_bindings;
|
||||
use super::{BufferForms, ComputePipelineState, RegionKey};
|
||||
use super::{BufferForms, ComputePipelineState, RegionKey, Variant};
|
||||
use crate::device::lock;
|
||||
use crate::warm::codec::RecordedDispatch;
|
||||
use metal2vulkan::bind::{BindState, Dispatch};
|
||||
use crate::Device;
|
||||
use metal2vulkan::bind::{BindState, BindingPlan, Dispatch};
|
||||
use metal2vulkan::pipeline::{ComputePipelineDescriptor, Stage};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Mutex;
|
||||
@@ -99,6 +101,24 @@ fn recorded(dispatch: &Dispatch, state: &BindState) -> Option<RecordedDispatch>
|
||||
})
|
||||
}
|
||||
|
||||
/// Make, on this thread, the `VkPipeline` of each region of `dispatch` over `state` on `variant`
|
||||
/// as `plan` instantiates it: how many were made, none where the plan refuses the dispatch.
|
||||
fn warm_regions(
|
||||
device: &Device,
|
||||
(variant, plan): (&Variant, &BindingPlan),
|
||||
state: &BindState,
|
||||
dispatch: &Dispatch,
|
||||
) -> u64 {
|
||||
let Ok(mut commands) = plan.instantiate_dispatch(state, dispatch) else {
|
||||
return 0;
|
||||
};
|
||||
variant.keyed_regions(device, &mut commands);
|
||||
let made = (commands.regions.iter())
|
||||
.filter(|region| variant.make_region(&RegionKey::of(region)).is_ok())
|
||||
.count();
|
||||
made as u64
|
||||
}
|
||||
|
||||
/// The Metal dispatch `recorded` stands for: one threadgroup, or its grid.
|
||||
fn dispatch_of(recorded: &RecordedDispatch) -> Dispatch {
|
||||
let threads_per_group = recorded.threads_per_group;
|
||||
@@ -116,7 +136,8 @@ fn dispatch_of(recorded: &RecordedDispatch) -> Dispatch {
|
||||
|
||||
impl ComputePipelineState {
|
||||
/// Hand the device's record hook the record of `dispatch`, a direct dispatch of this state
|
||||
/// over `state` whose regions' pipelines were not all made, where the state records its
|
||||
/// over `state` whose regions' pipelines were not all made, or that began its kernel's
|
||||
/// unit-axes variant (`unit_axes.rs`), where the state records its
|
||||
/// dispatches and has not recorded this one, nor [`DISPATCH_RECORDS`] others (the module
|
||||
/// docs).
|
||||
pub(crate) fn record_dispatch(&self, dispatch: &Dispatch, state: &BindState) {
|
||||
@@ -152,17 +173,16 @@ impl ComputePipelineState {
|
||||
.threadgroup_lengths;
|
||||
lengths.extend(recorded.threadgroup_lengths.iter().copied());
|
||||
let shape = state.shape();
|
||||
let settled = crate::compute::settle_direct(self, &shape, &dispatch, BufferForms::Bound);
|
||||
let Ok((variant, plan)) = settled else {
|
||||
let settled =
|
||||
crate::compute::settle_direct(self, &shape, &dispatch, BufferForms::Bound, None);
|
||||
let Ok(settled) = settled else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(mut commands) = plan.instantiate_dispatch(&state, &dispatch) else {
|
||||
return 0;
|
||||
};
|
||||
variant.keyed_regions(device, &mut commands);
|
||||
let made = (commands.regions.iter())
|
||||
.filter(|region| variant.make_region(&RegionKey::of(region)).is_ok())
|
||||
.count();
|
||||
made as u64
|
||||
let mut made = warm_regions(device, (&settled.variant, &settled.plan), &state, &dispatch);
|
||||
// The unit-axes variant a program's dispatch of it takes once made (`unit_axes.rs`).
|
||||
if let Some(unit) = self.warm_unit_axes(&settled.plan, &shape, &dispatch) {
|
||||
made += warm_regions(device, (&unit.0, &unit.1), &state, &dispatch);
|
||||
}
|
||||
made
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,7 @@ pub(crate) use sources::render_artifacts_encoded;
|
||||
pub(super) mod stand_in;
|
||||
mod texture_access;
|
||||
mod tile;
|
||||
mod unit_axes;
|
||||
mod unrasterized;
|
||||
mod unspecialized;
|
||||
|
||||
@@ -107,6 +108,7 @@ pub(super) use render::{reads_views_at_bind, residual_form};
|
||||
pub(super) use render::{GraphicsState, Kind as RenderStateKind, StateShared as RenderShared};
|
||||
pub(super) use render::{ProgramName, Settled};
|
||||
pub(super) use tile::TileState;
|
||||
pub(super) use unit_axes::Direct;
|
||||
|
||||
use super::binary_archive;
|
||||
use super::device::carry::{CallHold, LetGo, PartsCalls};
|
||||
@@ -397,6 +399,9 @@ pub(super) struct Program {
|
||||
stand_in: bool,
|
||||
/// The other variants dispatches needed.
|
||||
others: Mutex<Lru<VariantKey, Arc<Variant>>>,
|
||||
/// The unit-axes variants its dispatches began and that are not among `others` yet
|
||||
/// (`unit_axes.rs`).
|
||||
unit_axes: unit_axes::Aheads,
|
||||
/// The compile layer refused the kernel a flat variant ([`ComputePipelineState::settle_flat`]),
|
||||
/// so its indirect dispatches take the host step.
|
||||
flat_refused: AtomicBool,
|
||||
@@ -463,6 +468,9 @@ pub(crate) struct Planned {
|
||||
pub(crate) forms: BufferForms,
|
||||
pub(crate) variant: Arc<Variant>,
|
||||
pub(crate) plan: Arc<BindingPlan>,
|
||||
/// `variant` is the plain variant for now alone, its unit-axes variant being made meanwhile
|
||||
/// (`unit_axes.rs`): no later dispatch takes this.
|
||||
pub(crate) meanwhile: bool,
|
||||
/// Each region's key and its made `VkPipeline`, where all were found made, each its key's own
|
||||
/// (none a residual form's, `dispatch_making.rs`).
|
||||
pub(crate) made: OnceLock<(Vec<RegionKey>, Vec<Arc<RawPipeline>>)>,
|
||||
@@ -1047,6 +1055,7 @@ impl ComputePipelineState {
|
||||
base,
|
||||
stand_in,
|
||||
others: Mutex::new(Lru::counted(VARIANTS)),
|
||||
unit_axes: Arc::default(),
|
||||
flat_refused: AtomicBool::new(false),
|
||||
call_flat_refused: AtomicBool::new(false),
|
||||
replay_refused: AtomicBool::new(false),
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! A kernel's unit-axes variant (`VariantKey::unit_axes`), made on the device's pool ahead of the
|
||||
//! dispatches that take it.
|
||||
//!
|
||||
//! - **What it is.** A kernel whose emulated simdgroups are walked predicated, where its threads'
|
||||
//! positions along some axes alone steer a synchronization (`RuntimeFact::UnitAxes`), runs a
|
||||
//! dispatch of threadgroups of one thread along such axes on a variant that takes those
|
||||
//! positions as uniform, as Metal's contract makes them there (`threads_per_threadgroup` 1:
|
||||
//! every thread's `thread_position_in_threadgroup` is 0 and its `thread_position_in_grid` its
|
||||
//! threadgroup's position, partial threadgroups included). Its walk drops the live flags,
|
||||
//! demotions and loop votes those blocks took; it gives the plain variant's answers. The plan
|
||||
//! offers it (`BindingPlan::unit_axes_variant`).
|
||||
//! - **Never on the exec path.** A dispatch takes the variant only where its translation is
|
||||
//! done and each of its regions' `VkPipeline`s is made ([`ComputePipelineState::unit_axes`]).
|
||||
//! Otherwise it settles on its plain variant (`WorkCounts::unit_axes_meanwhile`), and the
|
||||
//! variant is begun on the pool: its translation, a piece of its own kept by the state
|
||||
//! (`piece_holds.rs`), at the first such dispatch (`WorkCounts::unit_axes_variants_begun`, its
|
||||
//! dispatch recorded for a later process's warm pass, `dispatch_record.rs`); at the next, on
|
||||
//! the program's thread, its objects (shader module and layouts, as any variant's) with its
|
||||
//! pipeline's notices, since no piece announces any (`degradation.rs`), and its regions'
|
||||
//! makings, handed to the pool as any dispatch's are (`dispatch_making.rs`), their notices
|
||||
//! announced there, naming what it binds. Nothing waits for the translation or a making. What a
|
||||
//! dispatch planned meanwhile is kept neither by the state's latest plans nor by its encoder's
|
||||
//! memo, so the next dispatch of its inputs asks again, and takes the variant once it is made
|
||||
//! (`WorkCounts::unit_axes_dispatches`).
|
||||
//! - **Bounded.** A variant per plain variant and mask of unit axes that relieves it: at most
|
||||
//! seven, one per threadgroup shape's axes in practice. They live among the state's other
|
||||
//! variants, at most `VARIANTS`, the least recently used going first; the state tracks at most
|
||||
//! `VARIANTS` of them being made or refused at once, and a dispatch whose variant finds that
|
||||
//! full keeps its plain variant. A translation the compile layer refuses and a making that
|
||||
//! fails are remembered: the plain variant runs those dispatches, as it did before.
|
||||
|
||||
use super::dispatch_making::{RegionHeld, RegionPipeline};
|
||||
use super::making::Pending;
|
||||
use super::memo::Remembered;
|
||||
use super::objects::RawPipeline;
|
||||
use super::sources::Sources;
|
||||
use super::{ComputePipelineState, Kernel, Variant, VARIANTS};
|
||||
use crate::degradation::BoundFormats;
|
||||
use crate::device::lock;
|
||||
use crate::error::{internal, Error};
|
||||
use crate::Device;
|
||||
use metal2vulkan::bind::{BindShape, BindState, BindingPlan, Dispatch};
|
||||
use metal2vulkan::cache::VariantKey;
|
||||
use metal2vulkan::pipeline::{ComputePipeline, FunctionDescriptor};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// What a state knows of a unit-axes variant it began and does not hold among its variants yet.
|
||||
pub(super) enum Ahead {
|
||||
/// Its translation is on the pool.
|
||||
Compiling,
|
||||
/// Its translation is done, by the piece that put it here: its pipeline, or the live variant
|
||||
/// of it the device's memo knew.
|
||||
Compiled(Remembered<ComputePipeline, Variant>),
|
||||
/// Its regions' `VkPipeline`s are being made, for the dispatch that began them.
|
||||
Making(Vec<Pending<RawPipeline>>),
|
||||
/// The compile layer refused it, or a making failed.
|
||||
Refused,
|
||||
}
|
||||
|
||||
/// A state's unit-axes variants begun, by key: shared with the translation's piece, which hands
|
||||
/// its variant over here.
|
||||
pub(super) type Aheads = Arc<Mutex<HashMap<VariantKey, Ahead>>>;
|
||||
|
||||
/// What a unit-axes variant's translation on the pool needs: kept by the state
|
||||
/// (`piece_holds.rs`), so the pool's thread never holds the device.
|
||||
pub(crate) struct CompilePiece {
|
||||
device: Device,
|
||||
function: FunctionDescriptor,
|
||||
descriptor: Kernel,
|
||||
key: VariantKey,
|
||||
aheads: Aheads,
|
||||
}
|
||||
|
||||
/// What a direct dispatch settled (`compute::settle_direct`): the variant it runs on and its plan
|
||||
/// for its bind state's shape; and whether that is its plain variant for now alone, its unit-axes
|
||||
/// variant being made meanwhile, so no later dispatch takes what it planned.
|
||||
pub(crate) struct Direct {
|
||||
pub(crate) variant: Arc<Variant>,
|
||||
pub(crate) plan: Arc<BindingPlan>,
|
||||
pub(crate) meanwhile: bool,
|
||||
}
|
||||
|
||||
impl Direct {
|
||||
/// `variant` and its `plan`, settled for good.
|
||||
pub(crate) fn of((variant, plan): (Arc<Variant>, Arc<BindingPlan>)) -> Direct {
|
||||
Direct {
|
||||
variant,
|
||||
plan,
|
||||
meanwhile: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a dispatch does about a unit-axes variant (`ComputePipelineState::ahead_of`).
|
||||
enum Step {
|
||||
/// Keeps its plain variant: the variant is refused, or the state tracks as many as it may.
|
||||
Plain,
|
||||
/// Keeps its plain variant while the variant is being made.
|
||||
Meanwhile,
|
||||
/// Takes the variant where its regions' `VkPipeline`s are made.
|
||||
Compiled(Arc<Variant>),
|
||||
/// Keeps its plain variant and begins the variant's translation.
|
||||
Begin,
|
||||
}
|
||||
|
||||
/// Whether every one of `pending`'s makings succeeded (`Some(true)`), one failed (`Some(false)`),
|
||||
/// or one is still being made (`None`).
|
||||
fn made(pending: &[Pending<RawPipeline>]) -> Option<bool> {
|
||||
let mut all = Some(true);
|
||||
for making in pending {
|
||||
match making.outcome() {
|
||||
Some(Ok(_)) => {}
|
||||
Some(Err(_)) => return Some(false),
|
||||
None => all = None,
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
impl ComputePipelineState {
|
||||
/// The variant a direct dispatch of `dispatch` over `state`, of shape `shape`, that binds
|
||||
/// `formats`, runs on, `settled` (its variant and plan) otherwise: its unit-axes variant
|
||||
/// where `settled`'s plan offers one (`BindingPlan::unit_axes_variant`) and it is made, its
|
||||
/// translation and each of its regions' `VkPipeline`s (the module docs); else `settled`,
|
||||
/// for now alone where the variant is being made, which this dispatch may begin.
|
||||
pub(crate) fn unit_axes(
|
||||
&self,
|
||||
settled: (Arc<Variant>, Arc<BindingPlan>),
|
||||
(shape, dispatch): (&BindShape, &Dispatch),
|
||||
(state, formats): (&BindState, BoundFormats<'_>),
|
||||
) -> Result<Direct, Error> {
|
||||
let Some(key) = settled.1.unit_axes_variant(dispatch).map_err(Error::Bind)? else {
|
||||
return Ok(Direct::of(settled));
|
||||
};
|
||||
let device = &self.0.device;
|
||||
let counts = &device.shared().counts;
|
||||
let meanwhile = |(variant, plan): (Arc<Variant>, Arc<BindingPlan>)| {
|
||||
counts.unit_axes_meanwhile();
|
||||
Ok(Direct {
|
||||
variant,
|
||||
plan,
|
||||
meanwhile: true,
|
||||
})
|
||||
};
|
||||
let variant = match self.ahead_of(&key) {
|
||||
Step::Plain => return Ok(Direct::of(settled)),
|
||||
Step::Meanwhile => return meanwhile(settled),
|
||||
Step::Begin => {
|
||||
self.begin_unit_axes(key);
|
||||
counts.unit_axes_variant_begun();
|
||||
self.record_dispatch(dispatch, state);
|
||||
return meanwhile(settled);
|
||||
}
|
||||
Step::Compiled(variant) => variant,
|
||||
};
|
||||
let plan = variant.plan(device, shape)?;
|
||||
if plan.dispatch_variant(dispatch).map_err(Error::Bind)? != key {
|
||||
return Err(internal(
|
||||
"the plan of a unit-axes variant asks for another variant",
|
||||
));
|
||||
}
|
||||
// A dispatch the variant's plan refuses meets the plain variant's own refusal.
|
||||
let Ok(mut commands) = plan.instantiate_dispatch(state, dispatch) else {
|
||||
return Ok(Direct::of(settled));
|
||||
};
|
||||
variant.keyed_regions(device, &mut commands);
|
||||
let pending: Vec<_> = (commands.regions.iter())
|
||||
.filter_map(
|
||||
|region| match self.begin_region_pipeline(&variant, region, formats) {
|
||||
RegionPipeline::Made(_) => None,
|
||||
RegionPipeline::Making(pending) => Some(pending),
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
if pending.is_empty() {
|
||||
counts.unit_axes_dispatch();
|
||||
return Ok(Direct {
|
||||
variant,
|
||||
plan,
|
||||
meanwhile: false,
|
||||
});
|
||||
}
|
||||
let mut aheads = lock(&self.0.unit_axes);
|
||||
if aheads.len() >= VARIANTS {
|
||||
return Ok(Direct::of(settled));
|
||||
}
|
||||
aheads.insert(key, Ahead::Making(pending));
|
||||
drop(aheads);
|
||||
meanwhile(settled)
|
||||
}
|
||||
|
||||
/// What a dispatch whose plan offers the unit-axes variant of `key` does about it (the
|
||||
/// module docs): a variant the piece translated is made here, on the program's thread, and
|
||||
/// joins the state's variants.
|
||||
fn ahead_of(&self, key: &VariantKey) -> Step {
|
||||
let mut aheads = lock(&self.0.unit_axes);
|
||||
let compiled = match aheads.get(key) {
|
||||
Some(Ahead::Compiling) => return Step::Meanwhile,
|
||||
Some(Ahead::Refused) => return Step::Plain,
|
||||
Some(Ahead::Making(pending)) => match made(pending) {
|
||||
None => return Step::Meanwhile,
|
||||
Some(false) => {
|
||||
aheads.insert(key.clone(), Ahead::Refused);
|
||||
return Step::Plain;
|
||||
}
|
||||
Some(true) => {
|
||||
aheads.remove(key);
|
||||
None
|
||||
}
|
||||
},
|
||||
Some(Ahead::Compiled(_)) => match aheads.remove(key) {
|
||||
Some(Ahead::Compiled(found)) => Some(found),
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
// Made under the lock, so no other dispatch begins it again meanwhile.
|
||||
if let Some(found) = compiled {
|
||||
return match Variant::of(&self.0.device, key.clone(), found, &self.0.function) {
|
||||
Ok(variant) => {
|
||||
lock(&self.0.others).insert(key.clone(), Arc::clone(&variant), 1);
|
||||
Step::Compiled(variant)
|
||||
}
|
||||
Err(_) => {
|
||||
aheads.insert(key.clone(), Ahead::Refused);
|
||||
Step::Plain
|
||||
}
|
||||
};
|
||||
}
|
||||
if let Some(found) = lock(&self.0.others).get(key) {
|
||||
return Step::Compiled(Arc::clone(found));
|
||||
}
|
||||
if aheads.len() >= VARIANTS {
|
||||
return Step::Plain;
|
||||
}
|
||||
aheads.insert(key.clone(), Ahead::Compiling);
|
||||
Step::Begin
|
||||
}
|
||||
|
||||
/// Hand the translation of the unit-axes variant of `key` to the device's pool, kept by the
|
||||
/// state: what it compiles, or its refusal, goes to the state's [`Aheads`]. The translation
|
||||
/// announces nothing; the variant's objects and notices wait for the next dispatch
|
||||
/// ([`ahead_of`](Self::ahead_of)).
|
||||
fn begin_unit_axes(&self, key: VariantKey) {
|
||||
let piece = CompilePiece {
|
||||
device: self.0.device.clone(),
|
||||
function: self.0.function.clone(),
|
||||
descriptor: self.0.descriptor.clone(),
|
||||
key,
|
||||
aheads: Arc::clone(&self.0.unit_axes),
|
||||
};
|
||||
let keeping = (self.0.program().pieces).keep(RegionHeld::Compile(Box::new(piece)));
|
||||
let pool = &self.0.device.shared().pipeline_pool;
|
||||
drop(pool.run(Box::new(move || {
|
||||
// Where the state let go meanwhile, the piece stops.
|
||||
let Some((lease, held)) = keeping.start() else {
|
||||
return;
|
||||
};
|
||||
let piece = match held {
|
||||
RegionHeld::Compile(piece) => piece,
|
||||
other => return lease.give_back(other, None),
|
||||
};
|
||||
let ahead = {
|
||||
let _noted = super::NoteEntries(&piece.device);
|
||||
let sources = Sources::later(&piece.device);
|
||||
match Variant::compiled(&sources, &piece.function, &piece.descriptor, &piece.key) {
|
||||
Ok((found, _)) => Ahead::Compiled(found),
|
||||
Err(_) => Ahead::Refused,
|
||||
}
|
||||
};
|
||||
lock(&piece.aheads).insert(piece.key.clone(), ahead);
|
||||
lease.give_back(RegionHeld::Compile(piece), None);
|
||||
})));
|
||||
}
|
||||
|
||||
/// On a warm pass's thread, the unit-axes variant `plan` offers a dispatch of `dispatch` of a
|
||||
/// bind state of shape `shape`, compiled where it is not among the state's variants, and its
|
||||
/// plan for `shape`: `None` where `plan` offers none, or the compile layer refuses it
|
||||
/// (`dispatch_record.rs`).
|
||||
pub(super) fn warm_unit_axes(
|
||||
&self,
|
||||
plan: &BindingPlan,
|
||||
shape: &BindShape,
|
||||
dispatch: &Dispatch,
|
||||
) -> Option<(Arc<Variant>, Arc<BindingPlan>)> {
|
||||
let key = plan.unit_axes_variant(dispatch).ok()??;
|
||||
let variant = self.variant(&key).ok()?;
|
||||
let plan = variant.plan(&self.0.device, shape).ok()?;
|
||||
Some((variant, plan))
|
||||
}
|
||||
}
|
||||
@@ -812,6 +812,8 @@ mod unchanged_truth_copies;
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod uniform_bind_offsets;
|
||||
mod unique_identifier;
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod unit_axes;
|
||||
#[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
|
||||
mod unmap_order;
|
||||
mod unshared_hold;
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! A kernel's unit-axes variant (`pipeline/unit_axes.rs`) on the device the cfg selects.
|
||||
//!
|
||||
//! The kernel sums its simdgroup in a loop whose trip count reads `thread_position_in_grid.y`
|
||||
//! (`(gid.y & 3) + 1` iterations of `simd_sum(t + i)`, `t` its thread index in its threadgroup),
|
||||
//! dispatched in threadgroups of 16 threads: not whole 32-lane simdgroups, so its simdgroups are
|
||||
//! emulated on every device, and walked predicated, since the loop's trip count is per thread to
|
||||
//! the translator. In threadgroups of 8 x 1 x 2, one thread along `y`, every thread of a
|
||||
//! threadgroup takes the same trip count, which the variant compiles in.
|
||||
|
||||
use super::blit_holds::{device, Scratch, WAIT};
|
||||
use crate::{
|
||||
Buffer, CommandBufferStatus, ComputePipelineState, Device, PipelineOptions, ResourceOptions,
|
||||
Size, WorkCounts,
|
||||
};
|
||||
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
|
||||
use std::time::Instant;
|
||||
|
||||
/// The threads of a threadgroup, and the threadgroups of a dispatch, along `y`.
|
||||
const THREADS: u32 = 16;
|
||||
const ROWS: u64 = 4;
|
||||
/// The words the output holds: a row of [`THREADS`] per grid position along `y`, at most two
|
||||
/// threads along `y` a threadgroup.
|
||||
const WORDS: usize = (THREADS as usize) * 2 * ROWS as usize;
|
||||
/// The most dispatches it takes the variant to be made and taken: the one that begins its
|
||||
/// translation, the one that begins its region's making, the one that takes it, and one more.
|
||||
const TRIES: usize = 4;
|
||||
|
||||
/// `kernel void unit_axes_y(device uint *out [[buffer(0)]], uint3 gid [[thread_position_in_grid]],
|
||||
/// uint t [[thread_index_in_threadgroup]])` (the module docs), storing at `gid.y * 16 + t`.
|
||||
const KERNEL: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
|
||||
target triple = "air64_v28-apple-macosx26.0.0"
|
||||
|
||||
define void @unit_axes_y(ptr addrspace(1) %out, <3 x i32> %gid, i32 %t) #0 {
|
||||
entry:
|
||||
%g = extractelement <3 x i32> %gid, i64 1
|
||||
%k = and i32 %g, 3
|
||||
%trip = add i32 %k, 1
|
||||
br label %loop
|
||||
loop:
|
||||
%i = phi i32 [ 0, %entry ], [ %i1, %loop ]
|
||||
%acc = phi i32 [ 0, %entry ], [ %acc1, %loop ]
|
||||
%v = add i32 %t, %i
|
||||
%s = tail call i32 @air.simd_sum.u.i32(i32 %v)
|
||||
%acc1 = add i32 %acc, %s
|
||||
%i1 = add i32 %i, 1
|
||||
%more = icmp ult i32 %i1, %trip
|
||||
br i1 %more, label %loop, label %done
|
||||
done:
|
||||
%row = mul i32 %g, 16
|
||||
%at32 = add i32 %row, %t
|
||||
%at = zext i32 %at32 to i64
|
||||
%p = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %at
|
||||
store i32 %acc1, ptr addrspace(1) %p, align 4
|
||||
ret void
|
||||
}
|
||||
|
||||
declare i32 @air.simd_sum.u.i32(i32) #1
|
||||
|
||||
attributes #0 = { convergent mustprogress nounwind willreturn }
|
||||
attributes #1 = { convergent mustprogress nounwind willreturn memory(none) }
|
||||
|
||||
!air.kernel = !{!0}
|
||||
!air.version = !{!6}
|
||||
!air.language_version = !{!7}
|
||||
|
||||
!0 = !{ptr @unit_axes_y, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3, !4, !5}
|
||||
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}
|
||||
!4 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint3", !"air.arg_name", !"gid"}
|
||||
!5 = !{i32 2, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}
|
||||
!6 = !{i32 2, i32 8, i32 0}
|
||||
!7 = !{!"Metal", i32 4, i32 0, i32 0}
|
||||
"#;
|
||||
|
||||
/// The kernel's compute state on `device`.
|
||||
fn state(device: &Device) -> ComputePipelineState {
|
||||
let air = metal2vulkan_devtools::llvm_assemble_text(KERNEL).unwrap();
|
||||
let library = metal2vulkan::library::Library::from_air(&air).unwrap();
|
||||
let function = device
|
||||
.new_library_with_compile_library(library)
|
||||
.new_function_with_name("unit_axes_y")
|
||||
.unwrap();
|
||||
let descriptor =
|
||||
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
|
||||
device
|
||||
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The output's words after a dispatch of [`ROWS`] threadgroups of `group` along `y`, the
|
||||
/// output filled with ones before it.
|
||||
fn run(device: &Device, state: &ComputePipelineState, group: [u64; 3]) -> Vec<u32> {
|
||||
let out = device
|
||||
.new_buffer_with_bytes(&[0xff; 4 * WORDS], ResourceOptions::shared())
|
||||
.unwrap();
|
||||
let queue = device.new_command_queue().unwrap();
|
||||
let command_buffer = queue.command_buffer().unwrap();
|
||||
let mut encoder = command_buffer.compute_command_encoder().unwrap();
|
||||
encoder.set_compute_pipeline_state(state).unwrap();
|
||||
encoder.set_buffer(Some(&out), 0, 0).unwrap();
|
||||
encoder
|
||||
.dispatch_threadgroups(
|
||||
Size::new(1, ROWS, 1),
|
||||
Size::new(group[0], group[1], group[2]),
|
||||
)
|
||||
.unwrap();
|
||||
encoder.end_encoding().unwrap();
|
||||
command_buffer.commit().unwrap();
|
||||
command_buffer.wait_until_completed_for(WAIT).unwrap();
|
||||
assert_eq!(
|
||||
(command_buffer.status(), command_buffer.error()),
|
||||
(CommandBufferStatus::Completed, None)
|
||||
);
|
||||
words(&out)
|
||||
}
|
||||
|
||||
fn words(buffer: &Buffer) -> Vec<u32> {
|
||||
let contents = buffer.contents().unwrap();
|
||||
// SAFETY: the buffer's bytes, which a completed command buffer wrote.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), 4 * WORDS) };
|
||||
(bytes.as_chunks::<4>().0.iter())
|
||||
.map(|&word| u32::from_le_bytes(word))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Metal's words for [`ROWS`] threadgroups of `group` along `y`: thread `t` of grid row `y`
|
||||
/// runs `(y & 3) + 1` iterations, each adding the sum of `t' + i` over the threads `t'` of its
|
||||
/// threadgroup (one simdgroup) still in the loop, stored at `16 y + t`; every other word ones.
|
||||
fn expected(group: [u64; 3]) -> Vec<u32> {
|
||||
let [x, y, _] = group.map(|n| n as u32);
|
||||
let trip = |w: u32, t: u32| ((w * y + (t / x) % y) & 3) + 1;
|
||||
let mut words = vec![u32::MAX; WORDS];
|
||||
for w in 0..ROWS as u32 {
|
||||
for t in 0..THREADS {
|
||||
let acc = (0..trip(w, t))
|
||||
.map(|i| {
|
||||
(0..THREADS)
|
||||
.filter(|&u| trip(w, u) > i)
|
||||
.map(|u| u + i)
|
||||
.sum::<u32>()
|
||||
})
|
||||
.sum();
|
||||
let row = w * y + (t / x) % y;
|
||||
words[(row * THREADS + t) as usize] = acc;
|
||||
}
|
||||
}
|
||||
words
|
||||
}
|
||||
|
||||
/// `device`'s work counts once its pipeline pool holds no piece, waiting at most [`WAIT`].
|
||||
fn settled(device: &Device) -> WorkCounts {
|
||||
let until = Instant::now() + WAIT;
|
||||
loop {
|
||||
let counts = device.work_counts();
|
||||
if counts.pipeline_pool_busy == 0 {
|
||||
return counts;
|
||||
}
|
||||
assert!(Instant::now() < until, "the pipeline pool still busy");
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// A dispatch of threadgroups with no unit axis (4 x 2 x 2) never begins the kernel's unit-axes
|
||||
/// variant. The first dispatch of threadgroups of one thread along `y` (8 x 1 x 2) settles on the
|
||||
/// plain variant and begins the variant on the pool, its dispatch waiting for none of it; once
|
||||
/// its translation and its region's `VkPipeline` are made a later dispatch settles on it, and
|
||||
/// every one of them leaves Metal's words, the plain variant's.
|
||||
#[test]
|
||||
fn a_unit_axis_dispatch_takes_its_variant_once_made() {
|
||||
let scratch = Scratch::new("unit-axes");
|
||||
let device = device(&scratch.0);
|
||||
let state = state(&device);
|
||||
|
||||
// No unit axis: the plain variant, nothing begun.
|
||||
let plain = [4, 2, 2];
|
||||
assert_eq!(run(&device, &state, plain), expected(plain));
|
||||
let counts = settled(&device);
|
||||
assert_eq!(
|
||||
(counts.unit_axes_variants_begun, counts.unit_axes_meanwhile),
|
||||
(0, 0)
|
||||
);
|
||||
|
||||
// Unit `y`: the plain variant while the variant is made, then the variant.
|
||||
let unit = [8, 1, 2];
|
||||
let want = expected(unit);
|
||||
let first = run(&device, &state, unit);
|
||||
assert_eq!(first, want, "the plain variant");
|
||||
let counts = settled(&device);
|
||||
assert_eq!(counts.unit_axes_variants_begun, 1);
|
||||
assert_eq!(counts.unit_axes_meanwhile, 1);
|
||||
assert_eq!(counts.unit_axes_dispatches, 0);
|
||||
let mut taken = None;
|
||||
for attempt in 1..TRIES {
|
||||
assert_eq!(run(&device, &state, unit), want, "dispatch {attempt}");
|
||||
let counts = settled(&device);
|
||||
if counts.unit_axes_dispatches == 1 {
|
||||
taken = Some(counts);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let counts = taken.expect("the unit-axes variant taken");
|
||||
assert_eq!(counts.unit_axes_variants_begun, 1, "begun once");
|
||||
// The dispatches after it take what it planned, still the variant.
|
||||
assert_eq!(run(&device, &state, unit), want, "the variant again");
|
||||
assert_eq!(settled(&device).unit_axes_dispatches, 1);
|
||||
|
||||
// No unit axis still takes the plain variant.
|
||||
assert_eq!(run(&device, &state, plain), expected(plain));
|
||||
assert_eq!(settled(&device).unit_axes_variants_begun, 1);
|
||||
}
|
||||
@@ -117,6 +117,9 @@ pub(crate) struct Counters {
|
||||
stage_entries_shared: AtomicU64,
|
||||
functions_translated: AtomicU64,
|
||||
widest_pin_kernels_emulated: AtomicU64,
|
||||
unit_axes_variants_begun: AtomicU64,
|
||||
unit_axes_dispatches: AtomicU64,
|
||||
unit_axes_meanwhile: AtomicU64,
|
||||
functions_shared: AtomicU64,
|
||||
linked_use_questions_asked: AtomicU64,
|
||||
descriptor_keys_built: AtomicU64,
|
||||
@@ -2714,6 +2717,24 @@ impl Counters {
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A dispatch began its kernel's unit-axes variant on the device's pool
|
||||
/// (`pipeline/unit_axes.rs`).
|
||||
pub(crate) fn unit_axes_variant_begun(&self) {
|
||||
self.unit_axes_variants_begun
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A dispatch settled on its kernel's unit-axes variant (`pipeline/unit_axes.rs`).
|
||||
pub(crate) fn unit_axes_dispatch(&self) {
|
||||
self.unit_axes_dispatches.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A dispatch settled on its kernel's plain variant while its unit-axes variant was being
|
||||
/// made (`pipeline/unit_axes.rs`).
|
||||
pub(crate) fn unit_axes_meanwhile(&self) {
|
||||
self.unit_axes_meanwhile.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// An ask for a stage's function that found it compiled already -- in the device's memo, in a
|
||||
/// creation's binary archive or in the shader cache on disk -- so nothing was translated
|
||||
/// (`pipeline/sources.rs`).
|
||||
@@ -6489,6 +6510,20 @@ pub struct WorkCounts {
|
||||
/// where its compile time grows to seconds and past them (`docs/API.md`, section 3). Metal pins
|
||||
/// nothing: an Apple GPU runs every simdgroup 32 wide.
|
||||
pub widest_pin_kernels_emulated: u64,
|
||||
/// Kernels' unit-axes variants (`VariantKey::unit_axes`) begun on the device's pool, each by
|
||||
/// the first dispatch of threadgroups of one thread along axes that relieve its kernel's
|
||||
/// predicated walk of emulated simdgroups (`RuntimeFact::UnitAxes`): the variant takes those
|
||||
/// threads' positions on such an axis as uniform, which Metal's contract makes them. Metal
|
||||
/// compiles no such variant: an Apple GPU runs a simdgroup's lanes in lockstep, so its kernel
|
||||
/// walks no divergent block predicated.
|
||||
pub unit_axes_variants_begun: u64,
|
||||
/// Direct dispatches that settled on a kernel's unit-axes variant, its translation and each
|
||||
/// of its regions' `VkPipeline`s made: once per plan settled, so a dispatch that takes what
|
||||
/// an earlier one planned (`dispatches_planned_as_before`) counts nothing here.
|
||||
pub unit_axes_dispatches: u64,
|
||||
/// Direct dispatches that settled on a kernel's plain variant, which gives the same answers,
|
||||
/// while its unit-axes variant was being made on the pool: none waited for that making.
|
||||
pub unit_axes_meanwhile: u64,
|
||||
/// Asks for a stage's function that found it compiled already, so nothing was translated: in
|
||||
/// the device's memo, in one of the creation's binary archives, or in the shader cache on
|
||||
/// disk. With `functions_translated` it adds up to every ask the run made.
|
||||
@@ -11296,6 +11331,9 @@ impl Device {
|
||||
functions_translated: counters.functions_translated.load(Ordering::Relaxed),
|
||||
widest_pin_kernels_emulated: (counters.widest_pin_kernels_emulated)
|
||||
.load(Ordering::Relaxed),
|
||||
unit_axes_variants_begun: (counters.unit_axes_variants_begun).load(Ordering::Relaxed),
|
||||
unit_axes_dispatches: (counters.unit_axes_dispatches).load(Ordering::Relaxed),
|
||||
unit_axes_meanwhile: (counters.unit_axes_meanwhile).load(Ordering::Relaxed),
|
||||
functions_shared: counters.functions_shared.load(Ordering::Relaxed),
|
||||
linked_use_questions_asked: counters.linked_use_questions_asked.load(Ordering::Relaxed),
|
||||
descriptor_keys_built: counters.descriptor_keys_built.load(Ordering::Relaxed),
|
||||
|
||||
@@ -60,6 +60,16 @@
|
||||
//! one-row regions, and a dispatch with a region of more rows on it is `BindError::NeedsVariant`
|
||||
//! for the variant without it.
|
||||
//!
|
||||
//! **Unit axes**. A kernel walked predicated whose threads' positions alone steer some of its
|
||||
//! synchronizations, along some axes, states which masks of axes relieve it
|
||||
//! (`LocalRules::unit_relief`, `RuntimeFact::UnitAxes`). A dispatch whose threadgroups have one thread along such
|
||||
//! a mask's axes, Metal's `threads_per_threadgroup` 1 there and every region's local size too, is
|
||||
//! offered the kernel's unit-axes variant ([`BindingPlan::unit_axes_variant`],
|
||||
//! `VariantKey::unit_axes`), where the plan's own variant runs it: the plan's still does, and
|
||||
//! gives the same answers. The variant's plan runs every dispatch of threadgroups of one thread
|
||||
//! along its axes, and a dispatch of more is `BindError::NeedsVariant` for the variant without
|
||||
//! them.
|
||||
//!
|
||||
//! **Push bytes.** Each region's push write covers the stage's whole push range, so every
|
||||
//! statically used push byte is written (VUID-vkCmdDispatch-maintenance4-08602): the
|
||||
//! `DispatchRegion` bytes (`lower::dispatch::region_bytes`) in every region, `MultiRegion` or
|
||||
@@ -456,6 +466,20 @@ fn product(pieces: [Vec<Piece>; 3], force_multi: bool) -> Result<Vec<Region>, Bi
|
||||
|
||||
/// Whether a region of `planned` has more than one row (`y` or `z` above 1), where a simdgroup
|
||||
/// may span two rows.
|
||||
/// The axes along which every threadgroup of `planned` has one thread (bit 0 `x`, bit 1 `y`, bit
|
||||
/// 2 `z`): Metal's `threads_per_threadgroup` there is 1, and so is every region's local size.
|
||||
fn unit_axes(planned: &Planned) -> u8 {
|
||||
(0..3)
|
||||
.filter(|&a| planned.nominal[a] == 1 && planned.regions.iter().all(|r| r.local[a] <= 1))
|
||||
.fold(0, |axes, a| axes | 1 << a)
|
||||
}
|
||||
|
||||
/// Whether the unit-axes variant of `axes` (`VariantKey::unit_axes`) runs `planned`: every one of
|
||||
/// its threadgroups has one thread along each of those axes.
|
||||
fn unit_axes_run(axes: u8, planned: &Planned) -> bool {
|
||||
unit_axes(planned) & axes == axes
|
||||
}
|
||||
|
||||
fn multi_row(planned: &Planned) -> bool {
|
||||
planned
|
||||
.regions
|
||||
@@ -838,6 +862,12 @@ impl BindingPlan {
|
||||
variant: Box::new(self.one_row_variant(false)),
|
||||
});
|
||||
}
|
||||
// The unit-axes variant runs threadgroups of one thread along its axes only.
|
||||
if !unit_axes_run(self.variant.unit_axes, &planned) {
|
||||
return Err(BindError::NeedsVariant {
|
||||
variant: Box::new(self.unit_axes_key(0)),
|
||||
});
|
||||
}
|
||||
// A folded variant's region reads its record.
|
||||
if self.variant.folded_groups {
|
||||
for r in &mut planned.regions {
|
||||
@@ -942,6 +972,13 @@ impl BindingPlan {
|
||||
pub fn dispatch_variant(&self, dispatch: &Dispatch) -> Result<VariantKey, BindError> {
|
||||
let t = self.compute_template("dispatch_variant")?;
|
||||
let planned = regions(&t.local, dispatch, Ragged::of(&self.variant))?;
|
||||
// A unit-axes variant's plan sends threadgroups of more threads along one of its axes to
|
||||
// the variant without them.
|
||||
if !unit_axes_run(self.variant.unit_axes, &planned) {
|
||||
let mut base = self.clone();
|
||||
base.variant.unit_axes = 0;
|
||||
return base.dispatch_variant(dispatch);
|
||||
}
|
||||
Ok(if planned.emulated {
|
||||
self.emulated_variant()
|
||||
} else if t.local.rows && !planned.regions.is_empty() && !multi_row(&planned) {
|
||||
@@ -955,6 +992,39 @@ impl BindingPlan {
|
||||
})
|
||||
}
|
||||
|
||||
/// The unit-axes variant (`VariantKey::unit_axes`) a compute dispatch may run on in place of
|
||||
/// the plan's own: its variant with `unit_axes` the axes along which every threadgroup of the
|
||||
/// dispatch has one thread, where the plan's pipeline is walked predicated and a variant of
|
||||
/// exactly those axes relieves the walk (`RuntimeFact::UnitAxes`'s `relief`) and the plan's
|
||||
/// own variant runs the dispatch ([`dispatch_variant`](Self::dispatch_variant)). `None` where
|
||||
/// it does not, where the dispatch has no such axis, or where the plan is a unit-axes
|
||||
/// variant's. A pure function of the plan and the dispatch, so a consumer can make the variant
|
||||
/// before any dispatch runs on it, and run the dispatch on the plan's own pipeline until it
|
||||
/// is made: the two give the same answers, Metal's, since every thread's position along such
|
||||
/// an axis is 0 in its threadgroup and its threadgroup's in the grid.
|
||||
pub fn unit_axes_variant(&self, dispatch: &Dispatch) -> Result<Option<VariantKey>, BindError> {
|
||||
let t = self.compute_template("unit_axes_variant")?;
|
||||
if t.local.unit_relief == 0 || self.variant.unit_axes != 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let planned = regions(&t.local, dispatch, Ragged::of(&self.variant))?;
|
||||
let axes = unit_axes(&planned);
|
||||
if axes == 0 || t.local.unit_relief >> (axes - 1) & 1 == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.dispatch_variant(dispatch)? != self.variant {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(self.unit_axes_key(axes)))
|
||||
}
|
||||
|
||||
/// The plan's variant with `unit_axes` `axes`.
|
||||
fn unit_axes_key(&self, axes: u8) -> VariantKey {
|
||||
let mut v = self.variant.clone();
|
||||
v.unit_axes = axes;
|
||||
v
|
||||
}
|
||||
|
||||
/// The plan's variant with emulated simdgroups.
|
||||
fn emulated_variant(&self) -> VariantKey {
|
||||
let mut v = self.variant.clone();
|
||||
|
||||
@@ -38,6 +38,7 @@ fn rules() -> LocalRules {
|
||||
stage_flags: vk::PipelineShaderStageCreateFlags::empty(),
|
||||
scratch: None,
|
||||
rows: false,
|
||||
unit_relief: 0,
|
||||
tile: false,
|
||||
tile_threadgroup: None,
|
||||
}
|
||||
|
||||
@@ -581,6 +581,10 @@ pub(crate) struct LocalRules {
|
||||
pub scratch: Option<ScratchRule>,
|
||||
/// A region of one row needs no whole subgroups (`RuntimeFact::RowLockstep`).
|
||||
pub rows: bool,
|
||||
/// The masks of axes whose unit-axes variant relieves the kernel's predicated walk
|
||||
/// (`RuntimeFact::UnitAxes`'s `relief`: bit `m − 1` for mask `m`), 0 where none does or the
|
||||
/// pipeline is that variant.
|
||||
pub unit_relief: u8,
|
||||
/// The pipeline is a tile function (`RuntimeFact::TileFunction`): its threads take Metal's
|
||||
/// tile-dispatch layout, built for the threadgroups `dispatch::tile_layout_measured` takes,
|
||||
/// dispatched by threadgroups.
|
||||
|
||||
@@ -790,6 +790,14 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
// The unit axes a pipeline compiled as its unit-axes variant states, or the masks whose variant
|
||||
// relieves its predicated walk (`RuntimeFact::UnitAxes`).
|
||||
let unit_axes = (p.dependencies.iter())
|
||||
.find_map(|d| match d.fact {
|
||||
RuntimeFact::UnitAxes { axes, relief } => Some((axes, relief)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or((0, 0));
|
||||
let local = LocalRules {
|
||||
flat: layout.iter().any(|c| c.key == SpecKey::FlatLocalSize),
|
||||
multiples,
|
||||
@@ -808,6 +816,7 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
.dependencies
|
||||
.iter()
|
||||
.any(|d| d.fact == RuntimeFact::RowLockstep),
|
||||
unit_relief: unit_axes.1,
|
||||
tile: is_tile_function(p),
|
||||
tile_threadgroup: tile_threadgroup(p, shape)?,
|
||||
};
|
||||
@@ -864,6 +873,10 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
// A pipeline compiled as its one-row variant states it; a dispatch asks for it where every
|
||||
// region is one row of a kernel with `RowLockstep` (`dispatch_variant`).
|
||||
variant.one_row = p.dependencies.iter().any(|d| d.fact == RuntimeFact::OneRow);
|
||||
// A pipeline compiled as its unit-axes variant states its axes; a consumer asks for it where a
|
||||
// dispatch's threadgroups have one thread along axes that relieve the walk
|
||||
// (`unit_axes_variant`).
|
||||
variant.unit_axes = unit_axes.0;
|
||||
// A pipeline compiled for a flat grid states its variant, and one of the call's threadgroups
|
||||
// states that too.
|
||||
variant.flat_grid = p
|
||||
|
||||
+1
@@ -1323,6 +1323,7 @@ codec_enum! {
|
||||
RegionViewports,
|
||||
PartialThreadgroups,
|
||||
TexelRows { slot },
|
||||
UnitAxes { axes, relief },
|
||||
}
|
||||
UniformViewChoice { Viewed, Spare, Kept }
|
||||
Mechanism {
|
||||
|
||||
Vendored
+16
-2
@@ -61,7 +61,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 = 2120;
|
||||
pub const SEMANTICS_VERSION: u32 = 2121;
|
||||
|
||||
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
|
||||
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
|
||||
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523;
|
||||
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
|
||||
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
|
||||
/// keeps no history.
|
||||
pub const RUNTIME_VERSION: u32 = 2330;
|
||||
pub const RUNTIME_VERSION: u32 = 2331;
|
||||
|
||||
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
|
||||
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
|
||||
@@ -177,6 +177,15 @@ pub struct VariantKey {
|
||||
/// variant without it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub one_row: bool,
|
||||
/// The axes along which every threadgroup of the dispatch has one thread (bit 0 `x`, bit 1
|
||||
/// `y`, bit 2 `z`): a kernel whose walk is predicated, where those axes' thread positions
|
||||
/// alone make some of its synchronizations' blocks divergent (`RuntimeFact::UnitAxes`'s
|
||||
/// `relief`), compiles with them uniform (`LoweringInputs::unit_axes`). A consumer asks a
|
||||
/// plan for it (`BindingPlan::unit_axes_variant`), and the plan of a pipeline compiled under
|
||||
/// it states it and asks a dispatch of more threads along such an axis for the variant
|
||||
/// without it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub unit_axes: u8,
|
||||
/// The vertex function's `[[render_target_array_index]]` output is not written: in a pass of at
|
||||
/// most one layer (`BindShape::render_target_array_length` 0 or 1) every index renders slice 0,
|
||||
/// so a pipeline whose vertex function chooses its slice runs on this variant there, and only
|
||||
@@ -578,6 +587,7 @@ impl VariantKey {
|
||||
&& self.pulled_vertex_buffers.is_empty()
|
||||
&& !self.emulated_simdgroups
|
||||
&& !self.one_row
|
||||
&& self.unit_axes == 0
|
||||
&& !self.dropped_vertex_layer
|
||||
&& self.storage_view_slots.is_empty()
|
||||
&& self.srgb_textures.is_empty()
|
||||
@@ -655,6 +665,10 @@ impl VariantKey {
|
||||
out.emulated_simdgroups =
|
||||
self.emulated_simdgroups && stage == crate::pipeline::sym::Stage::Kernel;
|
||||
out.one_row = self.one_row && stage == crate::pipeline::sym::Stage::Kernel;
|
||||
out.unit_axes = match stage {
|
||||
crate::pipeline::sym::Stage::Kernel => self.unit_axes,
|
||||
_ => 0,
|
||||
};
|
||||
out.flat_grid = self.flat_grid && stage == crate::pipeline::sym::Stage::Kernel;
|
||||
out.call_threadgroups =
|
||||
self.call_threadgroups && stage == crate::pipeline::sym::Stage::Kernel;
|
||||
|
||||
@@ -158,6 +158,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck,
|
||||
// A pipeline compiled under the one-row variant; its plans state it.
|
||||
RuntimeFact::OneRow => Mechanism::Variant,
|
||||
// The relief a consumer reads to ask for the unit-axes variant, or the axes the variant
|
||||
// was compiled under; its plans state them.
|
||||
RuntimeFact::UnitAxes { .. } => Mechanism::Variant,
|
||||
// A pipeline compiled under the flat-grid variant; its plans state it.
|
||||
RuntimeFact::FlatGrid => Mechanism::Variant,
|
||||
RuntimeFact::CallThreadgroups => Mechanism::Variant,
|
||||
|
||||
@@ -132,6 +132,7 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
RuntimeFact::OpenClMode,
|
||||
RuntimeFact::RowLockstep,
|
||||
RuntimeFact::OneRow,
|
||||
RuntimeFact::UnitAxes { axes: 0, relief: 2 },
|
||||
RuntimeFact::FlatGrid,
|
||||
RuntimeFact::CallThreadgroups,
|
||||
RuntimeFact::SparseTextureWrites {
|
||||
@@ -403,6 +404,7 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
RuntimeFact::PartialThreadgroups => 98,
|
||||
RuntimeFact::TexelRows { .. } => 99,
|
||||
RuntimeFact::HeapStorageReads { .. } => 100,
|
||||
RuntimeFact::UnitAxes { .. } => 101,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,7 +412,7 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
let facts = every_fact();
|
||||
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
|
||||
assert_eq!(covered, (0..101).collect(), "every_fact misses a variant");
|
||||
assert_eq!(covered, (0..102).collect(), "every_fact misses a variant");
|
||||
for (stem, _) in super::committed_profiles() {
|
||||
let dev = device(&stem);
|
||||
let p = dev.profile();
|
||||
@@ -483,6 +485,7 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
| RuntimeFact::CallThreadgroups
|
||||
| RuntimeFact::PartialThreadgroups
|
||||
| RuntimeFact::OneRow
|
||||
| RuntimeFact::UnitAxes { .. }
|
||||
| RuntimeFact::AmplificationDraws { .. }
|
||||
| RuntimeFact::ViewportCompensation { .. }
|
||||
| RuntimeFact::FoldedGroups
|
||||
|
||||
@@ -600,6 +600,14 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result<DispatchPlan, Er
|
||||
if cx.inputs.one_row && cx.stage == crate::pipeline::sym::Stage::Kernel {
|
||||
cx.facts.insert(RuntimeFact::OneRow);
|
||||
}
|
||||
// So does one compiled as its unit-axes variant, which runs only threadgroups of one thread
|
||||
// along its axes.
|
||||
if cx.inputs.unit_axes != 0 && cx.stage == crate::pipeline::sym::Stage::Kernel {
|
||||
cx.facts.insert(RuntimeFact::UnitAxes {
|
||||
axes: cx.inputs.unit_axes,
|
||||
relief: 0,
|
||||
});
|
||||
}
|
||||
// A flat grid reads the grid's size whatever builtins it reads, and so does a folded
|
||||
// variant its group counts; the plans of both state their variant.
|
||||
if multi_region || flat_grid || folded_groups {
|
||||
|
||||
@@ -291,11 +291,11 @@ pub fn barriers(
|
||||
let u = match given {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
computed = Uniformity::of(cx.entry, cx.body, m)?;
|
||||
computed = workgroup_uniformity(cx, m)?;
|
||||
&computed
|
||||
}
|
||||
};
|
||||
let r = (|| -> Result<Option<(Predication, bool)>, Error> {
|
||||
let r = (|| -> Result<Option<(Predication, bool, u8)>, Error> {
|
||||
let divergent = cx.body.blocks.iter().any(|(b, block)| {
|
||||
!u.is_uniform(b)
|
||||
&& block.inst_ids().any(|id| {
|
||||
@@ -309,16 +309,21 @@ pub fn barriers(
|
||||
if !divergent && !partial {
|
||||
return Ok(None);
|
||||
}
|
||||
// A partial threadgroup walks to every barrier whatever its axes.
|
||||
let relief = match divergent && !partial {
|
||||
true => unit_relief(cx, strategy, u, set, m)?,
|
||||
false => 0,
|
||||
};
|
||||
let (mut p, extra) = plan(cx, strategy, u, set, m)?;
|
||||
demote(cross, extra);
|
||||
p.vote_word = sync_in_loop(cx, &p, m)?;
|
||||
p.partial_groups = partial;
|
||||
Ok(Some((p, divergent)))
|
||||
Ok(Some((p, divergent, relief)))
|
||||
})();
|
||||
if given.is_none() {
|
||||
m.release(u.ledger_bytes());
|
||||
}
|
||||
let Some((p, divergent)) = r? else {
|
||||
let Some((p, divergent, relief)) = r? else {
|
||||
return Ok(());
|
||||
};
|
||||
if p.vote_word {
|
||||
@@ -346,10 +351,82 @@ pub fn barriers(
|
||||
cx.facts.insert(RuntimeFact::PredicationVote);
|
||||
vote_in_object_arena(cx);
|
||||
}
|
||||
if relief != 0 {
|
||||
cx.facts.insert(RuntimeFact::UnitAxes { axes: 0, relief });
|
||||
}
|
||||
cx.families.simd.predication = Some(p);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The workgroup uniformity of `cx`'s entry: a kernel's under the unit axes it is compiled for
|
||||
/// (`LoweringInputs::unit_axes`, `uniform`'s "Unit axes"), every other stage's as it is.
|
||||
pub fn workgroup_uniformity(cx: &SelectCx<'_>, m: &mut Meter) -> Result<Uniformity, Error> {
|
||||
let unit = match cx.stage {
|
||||
Stage::Kernel => cx.inputs.unit_axes,
|
||||
_ => 0,
|
||||
};
|
||||
Uniformity::with_unit_axes(cx.entry, cx.body, unit, m)
|
||||
}
|
||||
|
||||
/// The blocks of `cx`'s entry that hold a synchronization of `set` and that `u` does not prove
|
||||
/// uniform.
|
||||
fn divergent_syncs(
|
||||
cx: &SelectCx<'_>,
|
||||
strategy: &[Option<Strategy>],
|
||||
u: &Uniformity,
|
||||
set: SyncSet,
|
||||
) -> usize {
|
||||
(cx.body.blocks.iter())
|
||||
.filter(|(b, block)| {
|
||||
!u.is_uniform(*b)
|
||||
&& block.inst_ids().any(|id| {
|
||||
(cx.values.inst(id))
|
||||
.and_then(|v| strategy.get(v.index()))
|
||||
.and_then(Option::as_ref)
|
||||
.is_some_and(|s| set.holds(s))
|
||||
})
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The unit-axes relief of a kernel compiled without unit axes and walked predicated under `u`
|
||||
/// (`RuntimeFact::UnitAxes`): bit `m − 1` for each mask `m` of axes (bit 0 `x`, bit 1 `y`, bit 2
|
||||
/// `z`) under which fewer of the blocks that hold a synchronization of `set` are divergent once the
|
||||
/// threads' positions along those axes are taken as uniform (`uniform`'s "Unit axes"); 0 for any
|
||||
/// other function. Taking more positions as uniform makes no block divergent, so where the three
|
||||
/// axes together relieve none no mask does: one more analysis then, at most seven.
|
||||
pub(super) fn unit_relief(
|
||||
cx: &SelectCx<'_>,
|
||||
strategy: &[Option<Strategy>],
|
||||
u: &Uniformity,
|
||||
set: SyncSet,
|
||||
m: &mut Meter,
|
||||
) -> Result<u8, Error> {
|
||||
if cx.stage != Stage::Kernel || cx.inputs.unit_axes != 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let base = divergent_syncs(cx, strategy, u, set);
|
||||
if base == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let fewer = |axes: u8, m: &mut Meter| -> Result<bool, Error> {
|
||||
let under = Uniformity::with_unit_axes(cx.entry, cx.body, axes, m)?;
|
||||
let n = divergent_syncs(cx, strategy, &under, set);
|
||||
m.release(under.ledger_bytes());
|
||||
Ok(n < base)
|
||||
};
|
||||
if !fewer(0b111, m)? {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut relief = 1 << 6;
|
||||
for axes in 1..0b111u8 {
|
||||
if fewer(axes, m)? {
|
||||
relief |= 1 << (axes - 1);
|
||||
}
|
||||
}
|
||||
Ok(relief)
|
||||
}
|
||||
|
||||
/// An object function's arena fact with the vote word in its static part, which the binder checks
|
||||
/// beside the encoder's lengths (`RuntimeFact::ObjectThreadgroupArena`).
|
||||
fn vote_in_object_arena(cx: &mut SelectCx<'_>) {
|
||||
|
||||
@@ -756,7 +756,7 @@ pub fn partly_live(
|
||||
// A kernel's partial threadgroup leaves its lanes past the grid out of every block, as
|
||||
// another stage's groups are not whole.
|
||||
let u = if cx.stage == Stage::Kernel && !cx.inputs.partial_threadgroups {
|
||||
Some(uniform::Uniformity::of(cx.entry, cx.body, m)?)
|
||||
Some(divergent::workgroup_uniformity(cx, m)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -29,6 +29,20 @@
|
||||
//!
|
||||
//! Every other instruction is divergent exactly when one of its operands is.
|
||||
//!
|
||||
//! **Lanes.** A vector of at most [`LANES`] lanes is tracked lane by lane: a lane-wise operation
|
||||
//! (an arithmetic operation, comparison, cast, `select`, `freeze` or negation whose operands and
|
||||
//! result have its lane count, a scalar operand standing for every lane) is divergent in a lane
|
||||
//! exactly when an operand is there, an element extracted at a constant index is divergent when
|
||||
//! its lane is, an insertion at a constant index replaces its lane's, and a shuffle with no
|
||||
//! `poison` lane moves each lane's. A value is divergent when any of its lanes is.
|
||||
//!
|
||||
//! **Unit axes** ([`Uniformity::with_unit_axes`]). In a threadgroup of one thread along an axis,
|
||||
//! every thread's `thread_position_in_threadgroup` there is 0 and its `thread_position_in_grid`
|
||||
//! there is its threadgroup's `threadgroup_position_in_grid`, so among a workgroup's or a
|
||||
//! simdgroup's invocations both are uniform on that axis: the analysis of a dispatch whose
|
||||
//! threadgroups have such axes takes those lanes of the two builtins (the first, a scalar one's)
|
||||
//! as uniform.
|
||||
//!
|
||||
//! **Blocks.** A block is divergent when some invocations of a workgroup may execute it while
|
||||
//! others do not, or a different number of times: it is control dependent on a branch or switch
|
||||
//! whose condition is divergent, or on one in a divergent block (control dependence is read off
|
||||
@@ -69,7 +83,8 @@
|
||||
use crate::air::abi::{Builtin, ParamRole};
|
||||
use crate::air::intrinsics::{AirIntrinsic, GroupOp, GroupScope, LlvmIntrinsic, Sync, ThreadScope};
|
||||
use crate::air::ir::{
|
||||
AddrSpace, BlockId, Body, Callee, Const, ConstId, Idx, InstId, InstKind, Type, Value,
|
||||
AddrSpace, BlockId, Body, Callee, Const, ConstId, Idx, Inst, InstId, InstKind, Type, TypeId,
|
||||
Value,
|
||||
};
|
||||
use crate::air::Entry;
|
||||
use crate::budget::Meter;
|
||||
@@ -137,6 +152,50 @@ pub enum Among {
|
||||
Primitive,
|
||||
}
|
||||
|
||||
/// The most lanes of a vector the analysis tracks lane by lane (the module docs, "Lanes"); a
|
||||
/// value's lanes are the bits of a mask, and a value of no tracked lanes (a scalar, an aggregate,
|
||||
/// a wider vector) is divergent in [`ALL`] of them or in none.
|
||||
pub const LANES: u32 = 8;
|
||||
|
||||
/// Every lane of a value divergent.
|
||||
const ALL: u8 = u8::MAX;
|
||||
|
||||
/// The axes of a threadgroup of one thread along each: bit 0 `x`, bit 1 `y`, bit 2 `z`.
|
||||
pub type UnitAxes = u8;
|
||||
|
||||
/// The lanes of the dispatch builtin `b`, a parameter of `lanes` tracked lanes (`None` a scalar),
|
||||
/// that are divergent among the invocations `among` relates in threadgroups of one thread along
|
||||
/// the axes `unit` (the module docs, "Unit axes"); [`ALL`] where every lane may be.
|
||||
fn builtin_lanes(b: &Builtin, among: Among, lanes: Option<u32>, unit: UnitAxes) -> u8 {
|
||||
if !per_invocation(b, among) {
|
||||
return 0;
|
||||
}
|
||||
let positional = matches!(
|
||||
b,
|
||||
Builtin::ThreadPositionInThreadgroup | Builtin::ThreadPositionInGrid
|
||||
);
|
||||
if !positional || unit == 0 || among == Among::Primitive {
|
||||
return ALL;
|
||||
}
|
||||
match lanes {
|
||||
// A scalar position is its `x`.
|
||||
None => match unit & 1 {
|
||||
0 => ALL,
|
||||
_ => 0,
|
||||
},
|
||||
Some(n) => lane_bits(n) & !unit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The mask of a value of `n` tracked lanes.
|
||||
fn lane_bits(n: u32) -> u8 {
|
||||
match n {
|
||||
0 => 0,
|
||||
n if n >= 8 => ALL,
|
||||
n => (1u8 << n) - 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the dispatch builtin `b` may differ between the invocations `among` relates.
|
||||
fn per_invocation(b: &Builtin, among: Among) -> bool {
|
||||
if among == Among::Simdgroup && *b == Builtin::SimdgroupIndexInThreadgroup {
|
||||
@@ -255,8 +314,9 @@ struct State<'a> {
|
||||
e: &'a Entry,
|
||||
body: &'a Body,
|
||||
among: Among,
|
||||
args: Vec<bool>,
|
||||
insts: Vec<bool>,
|
||||
/// By parameter and by instruction: the divergent lanes (the module docs, "Lanes").
|
||||
args: Vec<u8>,
|
||||
insts: Vec<u8>,
|
||||
blocks: Vec<bool>,
|
||||
/// By block: uniform by the barrier contract, never divergent (empty without the contract).
|
||||
pinned: Vec<bool>,
|
||||
@@ -272,10 +332,117 @@ struct State<'a> {
|
||||
|
||||
impl State<'_> {
|
||||
fn value_divergent(&self, v: Value) -> bool {
|
||||
self.lanes_of(v) != 0
|
||||
}
|
||||
|
||||
/// The divergent lanes of `v`.
|
||||
fn lanes_of(&self, v: Value) -> u8 {
|
||||
match v {
|
||||
Value::Arg(a) => self.args.get(a.index()).copied().unwrap_or(true),
|
||||
Value::Const(c) => const_divergent(self.e, c),
|
||||
Value::Inst(i) => self.insts.get(i.index()).copied().unwrap_or(true),
|
||||
Value::Arg(a) => self.args.get(a.index()).copied().unwrap_or(ALL),
|
||||
Value::Const(c) => match const_divergent(self.e, c) {
|
||||
true => ALL,
|
||||
false => 0,
|
||||
},
|
||||
Value::Inst(i) => self.insts.get(i.index()).copied().unwrap_or(ALL),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tracked lanes of a value of type `ty`: `None` for any other type (the module docs).
|
||||
fn tracked(&self, ty: TypeId) -> Option<u32> {
|
||||
match self.e.module.types().get(ty)? {
|
||||
Type::Vector { len, .. } if *len <= LANES => Some(*len),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tracked lanes of `v`'s type.
|
||||
fn tracked_value(&self, v: Value) -> Option<u32> {
|
||||
self.tracked(self.e.module.value_ty(self.e.func, v)?)
|
||||
}
|
||||
|
||||
/// The constant index `v`, where it is one below [`LANES`].
|
||||
fn lane_index(&self, v: Value) -> Option<u32> {
|
||||
let Value::Const(c) = v else {
|
||||
return None;
|
||||
};
|
||||
match self.e.module.consts().get(c).map(|k| &k.value) {
|
||||
Some(Const::Int(k)) if *k < u64::from(LANES) => u32::try_from(*k).ok(),
|
||||
Some(Const::Null) => Some(0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The divergent lanes of a lane-wise operation's operand `v` in a result of `n` lanes: its
|
||||
/// own where it has `n` tracked lanes, every lane or none for a scalar, `None` for any other.
|
||||
fn operand_lanes(&self, v: Value, n: u32) -> Option<u8> {
|
||||
match self.tracked_value(v) {
|
||||
Some(k) if k == n => Some(self.lanes_of(v)),
|
||||
Some(_) => None,
|
||||
None => {
|
||||
let scalar = self.e.module.value_ty(self.e.func, v).is_some_and(|ty| {
|
||||
matches!(
|
||||
self.e.module.types().get(ty),
|
||||
Some(
|
||||
Type::Int(_)
|
||||
| Type::Half
|
||||
| Type::BFloat
|
||||
| Type::Float
|
||||
| Type::Double
|
||||
| Type::Ptr { .. }
|
||||
)
|
||||
)
|
||||
});
|
||||
scalar.then(|| match self.value_divergent(v) {
|
||||
true => lane_bits(n),
|
||||
false => 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The divergent lanes of instruction `i`, of `n` tracked lanes, where it moves or combines
|
||||
/// lanes (the module docs, "Lanes"); `None` where it does not, or an operand is not tracked.
|
||||
fn eval_lanes(&self, kind: &InstKind, n: u32) -> Option<u8> {
|
||||
let all = lane_bits(n);
|
||||
match kind {
|
||||
InstKind::InsertElement { vec, elt, idx } => {
|
||||
let k = self.lane_index(*idx)?;
|
||||
let vec = self.operand_lanes(*vec, n)?;
|
||||
let elt = match self.value_divergent(*elt) {
|
||||
true => 1u8 << k,
|
||||
false => 0,
|
||||
};
|
||||
Some((vec & !(1u8 << k) | elt) & all)
|
||||
}
|
||||
InstKind::ShuffleVector { a, b, mask } => {
|
||||
let na = self.tracked_value(*a)?;
|
||||
let (la, lb) = (self.lanes_of(*a), self.lanes_of(*b));
|
||||
let mut out = 0u8;
|
||||
for (j, lane) in mask.iter().enumerate() {
|
||||
let src = (*lane)?;
|
||||
let bit = match src < na {
|
||||
true => la >> src & 1,
|
||||
false => lb >> (src - na) & 1,
|
||||
};
|
||||
out |= bit << j;
|
||||
}
|
||||
Some(out & all)
|
||||
}
|
||||
InstKind::BinOp { a, b, .. }
|
||||
| InstKind::ICmp { a, b, .. }
|
||||
| InstKind::FCmp { a, b, .. } => {
|
||||
Some((self.operand_lanes(*a, n)? | self.operand_lanes(*b, n)?) & all)
|
||||
}
|
||||
InstKind::Select { c, t, f, .. } => Some(
|
||||
(self.operand_lanes(*c, n)?
|
||||
| self.operand_lanes(*t, n)?
|
||||
| self.operand_lanes(*f, n)?)
|
||||
& all,
|
||||
),
|
||||
InstKind::Cast { v, .. } | InstKind::FNeg { v, .. } | InstKind::Freeze(v) => {
|
||||
Some(self.operand_lanes(*v, n)? & all)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,11 +469,33 @@ impl State<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether instruction `i` is divergent under the current facts.
|
||||
fn eval(&self, i: InstId) -> bool {
|
||||
/// The divergent lanes of instruction `i` under the current facts.
|
||||
fn eval(&self, i: InstId) -> u8 {
|
||||
let Some(inst) = self.body.insts.get(i) else {
|
||||
return true;
|
||||
return ALL;
|
||||
};
|
||||
if let Some(n) = self.tracked(inst.ty) {
|
||||
if let Some(lanes) = self.eval_lanes(&inst.kind, n) {
|
||||
return lanes;
|
||||
}
|
||||
}
|
||||
// An element extracted at a constant index is its lane's.
|
||||
if let InstKind::ExtractElement { vec, idx } = &inst.kind {
|
||||
if let (Some(k), Some(_)) = (self.lane_index(*idx), self.tracked_value(*vec)) {
|
||||
return match self.lanes_of(*vec) >> k & 1 {
|
||||
0 => 0,
|
||||
_ => ALL,
|
||||
};
|
||||
}
|
||||
}
|
||||
match self.eval_whole(i, inst) {
|
||||
true => ALL,
|
||||
false => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether instruction `i`, `inst`, is divergent as a whole under the current facts.
|
||||
fn eval_whole(&self, i: InstId, inst: &Inst) -> bool {
|
||||
match &inst.kind {
|
||||
InstKind::Phi { incoming, .. } => incoming
|
||||
.iter()
|
||||
@@ -385,7 +574,18 @@ impl Uniformity {
|
||||
/// The uniformity of the blocks of `e`'s entry body. The returned structure stays charged to
|
||||
/// `m` ([`Uniformity::ledger_bytes`]); the analysis' own tables are released.
|
||||
pub fn of(e: &Entry, body: &Body, m: &mut Meter) -> Result<Uniformity, Error> {
|
||||
Uniformity::analyze(e, body, Among::Workgroup, None, &[], m)
|
||||
Uniformity::analyze(e, body, Among::Workgroup, None, &[], 0, m)
|
||||
}
|
||||
|
||||
/// [`of`](Self::of) for a dispatch whose threadgroups have one thread along the axes `unit`
|
||||
/// (the module docs, "Unit axes").
|
||||
pub fn with_unit_axes(
|
||||
e: &Entry,
|
||||
body: &Body,
|
||||
unit: UnitAxes,
|
||||
m: &mut Meter,
|
||||
) -> Result<Uniformity, Error> {
|
||||
Uniformity::analyze(e, body, Among::Workgroup, None, &[], unit, m)
|
||||
}
|
||||
|
||||
/// The uniformity of the blocks and values of vertex function `e`'s entry body among the
|
||||
@@ -398,7 +598,7 @@ impl Uniformity {
|
||||
uniform: &[u32],
|
||||
m: &mut Meter,
|
||||
) -> Result<Uniformity, Error> {
|
||||
Uniformity::analyze(e, body, Among::Primitive, None, uniform, m)
|
||||
Uniformity::analyze(e, body, Among::Primitive, None, uniform, 0, m)
|
||||
}
|
||||
|
||||
/// The uniformity of the blocks of `e`'s entry body among the invocations `among` relates,
|
||||
@@ -413,7 +613,7 @@ impl Uniformity {
|
||||
loops: &LoopForest<BlockId>,
|
||||
m: &mut Meter,
|
||||
) -> Result<Uniformity, Error> {
|
||||
Uniformity::analyze(e, body, among, Some(loops), &[], m)
|
||||
Uniformity::analyze(e, body, among, Some(loops), &[], 0, m)
|
||||
}
|
||||
|
||||
fn analyze(
|
||||
@@ -422,21 +622,34 @@ impl Uniformity {
|
||||
among: Among,
|
||||
contract: Option<&LoopForest<BlockId>>,
|
||||
uniform: &[u32],
|
||||
unit: UnitAxes,
|
||||
m: &mut Meter,
|
||||
) -> Result<Uniformity, Error> {
|
||||
let n = body.insts.len();
|
||||
let nb = body.blocks.len();
|
||||
// The users table, the per-instruction flags, homes, and worklist items, and the
|
||||
// per-block flags and worklist items (each instruction and block turns divergent once; a
|
||||
// simdgroup collective is queued once more when its block does).
|
||||
let mut uses = 0usize;
|
||||
// simdgroup collective is queued once more when its block does; the users of a tracked
|
||||
// vector are queued once more per lane it turns divergent in after its first).
|
||||
let types = e.module.types();
|
||||
let vector = |d: InstId| {
|
||||
body.insts.get(d).is_some_and(|inst| {
|
||||
matches!(types.get(inst.ty), Some(Type::Vector { len, .. }) if *len <= LANES)
|
||||
})
|
||||
};
|
||||
let (mut uses, mut vector_uses) = (0usize, 0usize);
|
||||
for inst in body.insts.values() {
|
||||
inst.kind
|
||||
.for_each_value(|v| uses += usize::from(matches!(v, Value::Inst(_))));
|
||||
inst.kind.for_each_value(|v| {
|
||||
if let Value::Inst(d) = v {
|
||||
uses += 1;
|
||||
vector_uses += usize::from(vector(d));
|
||||
}
|
||||
});
|
||||
}
|
||||
let scratch = n
|
||||
.saturating_mul(4 + 4 + 3 * 16)
|
||||
.saturating_add(uses.saturating_mul(4))
|
||||
.saturating_add(vector_uses.saturating_mul(16 * (LANES as usize - 1)))
|
||||
.saturating_add(nb.saturating_mul(2 + 16));
|
||||
// What the result keeps: the block, instruction, and argument flags.
|
||||
let kept = nb.saturating_add(n).saturating_add(e.ep.params.len());
|
||||
@@ -444,7 +657,7 @@ impl Uniformity {
|
||||
let result = PostDomTree::compute(&e.cfg, m)
|
||||
.map_err(Error::from)
|
||||
.and_then(|pdom| {
|
||||
let r = State::new(e, body, among, uniform, m)
|
||||
let r = State::new(e, body, among, uniform, unit, m)
|
||||
.and_then(|st| match contract {
|
||||
Some(loops) => st.pin(&pdom, loops, m),
|
||||
None => Ok(st),
|
||||
@@ -475,27 +688,39 @@ impl<'a> State<'a> {
|
||||
body: &'a Body,
|
||||
among: Among,
|
||||
uniform: &[u32],
|
||||
unit: UnitAxes,
|
||||
m: &mut Meter,
|
||||
) -> Result<State<'a>, Error> {
|
||||
let n = body.insts.len();
|
||||
let nb = body.blocks.len();
|
||||
let nargs = e
|
||||
let params: Vec<TypeId> = e
|
||||
.module
|
||||
.func(e.func)
|
||||
.and_then(|f| match e.module.types().get(f.ty) {
|
||||
Some(Type::Function { params, .. }) => Some(params.len()),
|
||||
Some(Type::Function { params, .. }) => Some(params.to_vec()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let mut args = vec![true; nargs];
|
||||
.unwrap_or_default();
|
||||
let mut args = vec![ALL; params.len()];
|
||||
for b in &e.ep.params {
|
||||
let lanes =
|
||||
(params.get(b.param as usize)).and_then(|&ty| match e.module.types().get(ty) {
|
||||
Some(Type::Vector { len, .. }) if *len <= LANES => Some(*len),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(a) = args.get_mut(b.param as usize) {
|
||||
*a = divergent_role(&b.role, among);
|
||||
*a = match &b.role {
|
||||
ParamRole::Builtin(builtin) => builtin_lanes(builtin, among, lanes, unit),
|
||||
role => match divergent_role(role, among) {
|
||||
true => ALL,
|
||||
false => 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
for &p in uniform {
|
||||
if let Some(a) = args.get_mut(p as usize) {
|
||||
*a = false;
|
||||
*a = 0;
|
||||
}
|
||||
}
|
||||
let mut home = vec![u32::MAX; n];
|
||||
@@ -543,7 +768,7 @@ impl<'a> State<'a> {
|
||||
body,
|
||||
among,
|
||||
args,
|
||||
insts: vec![false; n],
|
||||
insts: vec![0; n],
|
||||
blocks: vec![false; nb],
|
||||
pinned: Vec::new(),
|
||||
home,
|
||||
@@ -634,14 +859,20 @@ impl<'a> State<'a> {
|
||||
};
|
||||
let branch =
|
||||
matches!(inst.kind, InstKind::CondBr { .. } | InstKind::Switch { .. });
|
||||
let already = self.insts.get(i.index()).copied().unwrap_or(true);
|
||||
if already || !self.eval(i) {
|
||||
// A value's divergent lanes only grow: a scalar's once, a vector's at most
|
||||
// once per lane.
|
||||
let old = self.insts.get(i.index()).copied().unwrap_or(ALL);
|
||||
if old == ALL {
|
||||
continue;
|
||||
}
|
||||
let new = old | self.eval(i);
|
||||
if new == old {
|
||||
continue;
|
||||
}
|
||||
if let Some(d) = self.insts.get_mut(i.index()) {
|
||||
*d = true;
|
||||
*d = new;
|
||||
}
|
||||
if branch {
|
||||
if branch && old == 0 {
|
||||
let a = BlockId::new(self.home.get(i.index()).copied().unwrap_or(0));
|
||||
self.mark_region(a, pdom, m)?;
|
||||
}
|
||||
@@ -684,8 +915,8 @@ impl<'a> State<'a> {
|
||||
}
|
||||
Ok(Uniformity {
|
||||
divergent: self.blocks,
|
||||
values: self.insts,
|
||||
args: self.args,
|
||||
values: self.insts.iter().map(|&l| l != 0).collect(),
|
||||
args: self.args.iter().map(|&l| l != 0).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +342,7 @@ pub fn check(
|
||||
let u = match given {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
computed = Uniformity::of(cx.entry, cx.body, m)?;
|
||||
computed = divergent::workgroup_uniformity(cx, m)?;
|
||||
&computed
|
||||
}
|
||||
};
|
||||
@@ -351,9 +351,15 @@ pub fn check(
|
||||
Some(_) => divergent::plan(cx, strategy, u, divergent::SyncSet::Emulated, m).map(Some),
|
||||
None => Ok(None),
|
||||
};
|
||||
// Where the walk is predicated, the unit axes that would relieve it.
|
||||
let relief = match &planned {
|
||||
Ok(Some(_)) => divergent::unit_relief(cx, strategy, u, divergent::SyncSet::Emulated, m),
|
||||
_ => Ok(0),
|
||||
};
|
||||
if given.is_none() {
|
||||
m.release(u.ledger_bytes());
|
||||
}
|
||||
let relief = relief?;
|
||||
let (predication, demoted) = match planned? {
|
||||
Some((p, extra)) => (Some(p), Some(extra)),
|
||||
None => (None, None),
|
||||
@@ -417,6 +423,9 @@ pub fn check(
|
||||
if let Some(fact) = fact {
|
||||
cx.facts.insert(fact);
|
||||
}
|
||||
if relief != 0 {
|
||||
cx.facts.insert(RuntimeFact::UnitAxes { axes: 0, relief });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -214,6 +214,7 @@ mod serde_round_trips {
|
||||
pulled_vertex_buffers: BTreeSet::from([2, 5]),
|
||||
emulated_simdgroups: true,
|
||||
one_row: true,
|
||||
unit_axes: 6,
|
||||
dropped_vertex_layer: true,
|
||||
storage_view_slots: BTreeSet::from([buffer(3)]),
|
||||
srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
|
||||
@@ -492,6 +493,7 @@ mod serde_round_trips {
|
||||
object_payload: Some(64),
|
||||
region_viewports: true,
|
||||
region_copies: true,
|
||||
unit_axes: 2,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -540,6 +540,10 @@ pub fn function_key(
|
||||
if inputs.region_copies {
|
||||
h.bytes(b"region-copies");
|
||||
}
|
||||
// Appended only when set.
|
||||
if inputs.unit_axes != 0 {
|
||||
h.bytes(b"unit-axes").u64(u64::from(inputs.unit_axes));
|
||||
}
|
||||
// Appended only when present, so a stage that links nothing keeps its key: the tag's length
|
||||
// prefix keeps the encoding unambiguous.
|
||||
if !linked.is_empty() {
|
||||
|
||||
@@ -747,7 +747,8 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
|
||||
.replace(", object_payload: None", "")
|
||||
.replace(", tessellation: None", "")
|
||||
.replace(", region_viewports: false", "")
|
||||
.replace(", region_copies: false", ""),
|
||||
.replace(", region_copies: false", "")
|
||||
.replace(", unit_axes: 0", ""),
|
||||
"{derived}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -349,6 +349,16 @@ pub enum RuntimeFact {
|
||||
/// barriers its `RowLockstep` plan had (its threadgroup ones kept). Its plans state the
|
||||
/// variant, and a dispatch with a region of more than one row asks for the variant without it.
|
||||
OneRow,
|
||||
/// Unit axes (`lower::simd::uniform`, "Unit axes"; bit 0 `x`, bit 1 `y`, bit 2 `z`). Where
|
||||
/// `axes` is 0, the kernel's walk is predicated and `relief` holds, at bit `m − 1`, each mask
|
||||
/// `m` of axes under which fewer of its synchronizations' blocks are divergent once its
|
||||
/// threads' positions along them are taken as uniform: a dispatch whose threadgroups have one
|
||||
/// thread along exactly the axes `m` may run the kernel's unit-axes variant
|
||||
/// (`VariantKey::unit_axes`, `BindingPlan::unit_axes_variant`). Where `axes` is not 0, the
|
||||
/// kernel was compiled under that variant (`LoweringInputs::unit_axes`), `relief` is 0, its
|
||||
/// plans state the variant, and a dispatch with more than one thread along one of `axes` asks
|
||||
/// for the variant without it.
|
||||
UnitAxes { axes: u8, relief: u8 },
|
||||
/// The kernel was compiled under `VariantKey::flat_grid` (`LoweringInputs::flat_grid`): it
|
||||
/// runs any grid in threadgroups of its own size, reading the grid from the 32-byte region
|
||||
/// record at its `PushField::ReplayRegionAddress`, which a preprocess writes beside the
|
||||
|
||||
@@ -912,6 +912,17 @@ pub struct LoweringInputs {
|
||||
/// through each region's viewport. Any other stage compiles as without it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub region_copies: bool,
|
||||
/// The axes along which every threadgroup the kernel runs has one thread
|
||||
/// (`VariantKey::unit_axes`; bit 0 `x`, bit 1 `y`, bit 2 `z`): there every thread's
|
||||
/// `thread_position_in_threadgroup` is 0 and its `thread_position_in_grid` is its
|
||||
/// threadgroup's `threadgroup_position_in_grid`, partial threadgroups included, so the
|
||||
/// workgroup-uniformity analysis takes those lanes of the two builtins as uniform
|
||||
/// (`lower::simd::uniform`, "Unit axes") and a block they alone made divergent is walked as a
|
||||
/// uniform one. A kernel compiled under it states `RuntimeFact::UnitAxes { axes, .. }`, and its
|
||||
/// plans run only dispatches whose threadgroups have one thread along every such axis. Any
|
||||
/// other stage compiles as without it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub unit_axes: u8,
|
||||
}
|
||||
|
||||
/// One group of a render pipeline's color attachments (`LoweringInputs::color_group`,
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//! A kernel's unit-axes variant (`VariantKey::unit_axes`, `LoweringInputs::unit_axes`).
|
||||
//!
|
||||
//! In a threadgroup of one thread along an axis (Metal's `threads_per_threadgroup` 1 there), every
|
||||
//! thread's position along it is 0 in its threadgroup and its threadgroup's in the grid, so a
|
||||
//! branch on it is uniform across the threadgroup. A kernel whose emulated simdgroups are walked
|
||||
//! predicated only because such a position steers a synchronization states the axes whose variant
|
||||
//! relieves the walk (`RuntimeFact::UnitAxes`), and its plan offers that variant to a dispatch of
|
||||
//! such threadgroups (`BindingPlan::unit_axes_variant`). The authored kernel here sums its
|
||||
//! simdgroup in a loop whose trip count reads `thread_position_in_grid.y` (and, for the control,
|
||||
//! `.x`). Each module runs on the CPU interpreter at 8, 16 and 32 subgroup lanes in both
|
||||
//! scheduling orders, under Vulkan's barrier rule. No GPU is used.
|
||||
//!
|
||||
//! `llvm-as` assembles the kernels; a missing tool skips visibly.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::bind::{BindState, BoundBuffer, Dispatch, StageTable};
|
||||
use crate::budget::Budget;
|
||||
use crate::cache::VariantKey;
|
||||
use crate::device::subgroup::Tier;
|
||||
use crate::device::{Device, DevicePolicy};
|
||||
use crate::error::BindError;
|
||||
use crate::library::Library;
|
||||
use crate::lower::select::Plan;
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::sym::{Axis, ResourceKind, ResourceSlot, SpecKey, Stage};
|
||||
use crate::pipeline::testing::{
|
||||
llvm_assemble, typed_module, typed_module_with, AssembleError, Scratch,
|
||||
};
|
||||
use crate::pipeline::{
|
||||
ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, StageSource,
|
||||
};
|
||||
use crate::spirv::interp::{
|
||||
run, BarrierRule, Buffer, Config, InterpError, Order, Resources, SubgroupSize, TrapKind,
|
||||
};
|
||||
use crate::spirv::ir::TypedModule;
|
||||
|
||||
/// `kernel void name(device uint *out [[buffer(0)]], uint3 gid [[thread_position_in_grid]],
|
||||
/// uint t [[thread_index_in_threadgroup]])`: with `g = gid[axis]`, a loop of `(g & 3) + 1`
|
||||
/// iterations, each adding `simd_sum(t + i)`, then `out[t + N gid.y] = acc`, `N` the
|
||||
/// threadgroup's threads (a constant here: `n`).
|
||||
fn kernel(name: &str, axis: u32, n: u32) -> String {
|
||||
format!(
|
||||
r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
|
||||
target triple = "air64_v28-apple-macosx26.0.0"
|
||||
|
||||
define void @{name}(ptr addrspace(1) %out, <3 x i32> %gid, i32 %t) #0 {{
|
||||
entry:
|
||||
%g = extractelement <3 x i32> %gid, i64 {axis}
|
||||
%k = and i32 %g, 3
|
||||
%trip = add i32 %k, 1
|
||||
br label %loop
|
||||
loop:
|
||||
%i = phi i32 [ 0, %entry ], [ %i1, %loop ]
|
||||
%acc = phi i32 [ 0, %entry ], [ %acc1, %loop ]
|
||||
%v = add i32 %t, %i
|
||||
%s = tail call i32 @air.simd_sum.u.i32(i32 %v)
|
||||
%acc1 = add i32 %acc, %s
|
||||
%i1 = add i32 %i, 1
|
||||
%more = icmp ult i32 %i1, %trip
|
||||
br i1 %more, label %loop, label %done
|
||||
done:
|
||||
%y = extractelement <3 x i32> %gid, i64 1
|
||||
%row = mul i32 %y, {n}
|
||||
%at32 = add i32 %row, %t
|
||||
%at = zext i32 %at32 to i64
|
||||
%p = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %at
|
||||
store i32 %acc1, ptr addrspace(1) %p, align 4
|
||||
ret void
|
||||
}}
|
||||
|
||||
declare i32 @air.simd_sum.u.i32(i32) #1
|
||||
|
||||
attributes #0 = {{ convergent mustprogress nounwind willreturn }}
|
||||
attributes #1 = {{ convergent mustprogress nounwind willreturn memory(none) }}
|
||||
|
||||
!air.kernel = !{{!0}}
|
||||
!air.version = !{{!6}}
|
||||
!air.language_version = !{{!7}}
|
||||
|
||||
!0 = !{{ptr @{name}, !1, !2}}
|
||||
!1 = !{{}}
|
||||
!2 = !{{!3, !4, !5}}
|
||||
!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}}
|
||||
!4 = !{{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint3", !"air.arg_name", !"gid"}}
|
||||
!5 = !{{i32 2, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}}
|
||||
!6 = !{{i32 2, i32 8, i32 0}}
|
||||
!7 = !{{!"Metal", i32 4, i32 0, i32 0}}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
/// The threadgroup every run takes: 8 x 1 x 8, two simdgroups, one thread along `y`.
|
||||
const LOCAL: [u32; 3] = [8, 1, 8];
|
||||
/// The threadgroups along `y` a run dispatches: trip counts 1 to 4 on the `y` kernel.
|
||||
const ROWS: u32 = 4;
|
||||
/// `RuntimeFact::UnitAxes`'s `relief` of a kernel whose loop reads `y`: the masks with `y`
|
||||
/// (`y`, `x | y`, `y | z`, `x | y | z`), bit `m - 1` for mask `m`.
|
||||
const RELIEF_Y: u8 = 1 << 1 | 1 << 2 | 1 << 5 | 1 << 6;
|
||||
/// The same for a loop that reads `x`: the masks with `x`.
|
||||
const RELIEF_X: u8 = 1 | 1 << 2 | 1 << 4 | 1 << 6;
|
||||
|
||||
fn assemble(name: &str, text: &str) -> Option<Vec<u8>> {
|
||||
let scratch = Scratch::new(&format!("m2v-unit-axes-{name}"));
|
||||
let path = scratch.path().join("kernel.ll");
|
||||
std::fs::write(&path, text).expect("write");
|
||||
match llvm_assemble(&path) {
|
||||
Ok(b) => Some(b),
|
||||
Err(AssembleError::Missing(why)) => {
|
||||
eprintln!("SKIPPED: {why}");
|
||||
None
|
||||
}
|
||||
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn lavapipe() -> Device {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../metal2vulkan-validation/profiles/lavapipe.json");
|
||||
let text = std::fs::read_to_string(path).expect("profile");
|
||||
let desc =
|
||||
crate::device::DeviceDescription::from_khronos_json(&text, None).expect("description");
|
||||
Device::new(desc, DevicePolicy::default()).expect("device")
|
||||
}
|
||||
|
||||
/// The unit axes `plan` states, with their relief (`RuntimeFact::UnitAxes`).
|
||||
fn unit_axes(plan: &Plan) -> Option<(u8, u8)> {
|
||||
plan.facts.iter().find_map(|fact| match *fact {
|
||||
RuntimeFact::UnitAxes { axes, relief } => Some((axes, relief)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The module of `name` under unit axes `axes`.
|
||||
fn module(bc: &[u8], name: &str, dev: &Device, axes: u8) -> (Plan, TypedModule) {
|
||||
let mut inputs = LoweringInputs::new();
|
||||
inputs.unit_axes = axes;
|
||||
match axes {
|
||||
0 => typed_module(bc, name, dev.profile()),
|
||||
_ => typed_module_with(bc, name, dev.profile(), &inputs),
|
||||
}
|
||||
.unwrap_or_else(|e| panic!("{name} under {axes}: {e}"))
|
||||
}
|
||||
|
||||
/// Buffer 0 after `ROWS` threadgroups of `local` along `y` ran `m` (planned as `plan`) with
|
||||
/// `lanes`-wide subgroups, identical in both scheduling orders; or why a run did not complete.
|
||||
fn run_rows(
|
||||
plan: &Plan,
|
||||
m: &TypedModule,
|
||||
local: [u32; 3],
|
||||
lanes: SubgroupSize,
|
||||
) -> Result<Vec<u32>, InterpError> {
|
||||
let mut spec = BTreeMap::new();
|
||||
for (a, v) in [Axis::X, Axis::Y, Axis::Z].into_iter().zip(local) {
|
||||
spec.insert(SpecKey::LocalSize(a), u64::from(v));
|
||||
}
|
||||
let n: u32 = local.iter().product();
|
||||
spec.insert(SpecKey::FlatLocalSize, u64::from(n));
|
||||
let res = Resources {
|
||||
buffers: vec![Buffer {
|
||||
slot: Some(ResourceSlot {
|
||||
stage: Stage::Kernel,
|
||||
kind: ResourceKind::Buffer,
|
||||
index: 0,
|
||||
}),
|
||||
address: None,
|
||||
bytes: vec![0; (n * ROWS * local[1]) as usize * 4],
|
||||
}],
|
||||
push: vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)],
|
||||
spec,
|
||||
};
|
||||
let mut outs = Vec::new();
|
||||
for order in [Order::Forward, Order::Reverse] {
|
||||
let cfg = Config {
|
||||
workgroups: [1, ROWS, 1],
|
||||
subgroup: lanes,
|
||||
order,
|
||||
barriers: BarrierRule::Vulkan,
|
||||
..Config::default()
|
||||
};
|
||||
outs.push(run(m, &cfg, res.clone())?.buffers.swap_remove(0));
|
||||
}
|
||||
assert_eq!(outs[0], outs[1], "order independent");
|
||||
let bytes = outs.swap_remove(0);
|
||||
Ok(bytes
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|w| u32::from_le_bytes(*w))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Metal's words for `LOCAL` threadgroups of the kernel whose loop reads `axis`: thread `t` of
|
||||
/// threadgroup `w` runs `(g & 3) + 1` iterations, `g` its grid position on the axis (`t mod 8`
|
||||
/// on `x`, `w` on `y`), each adding the sum of `t' + i` over the threads `t'` of its simdgroup
|
||||
/// (32 consecutive threads) still in the loop.
|
||||
fn expected(axis: u32) -> Vec<u32> {
|
||||
let n: u32 = LOCAL.iter().product();
|
||||
let trip = |t: u32, w: u32| match axis {
|
||||
0 => ((t % LOCAL[0]) & 3) + 1,
|
||||
_ => (w & 3) + 1,
|
||||
};
|
||||
let mut words = Vec::new();
|
||||
for w in 0..ROWS {
|
||||
for t in 0..n {
|
||||
let group = (t / 32) * 32..((t / 32) * 32 + 32).min(n);
|
||||
let acc = (0..trip(t, w))
|
||||
.map(|i| {
|
||||
group
|
||||
.clone()
|
||||
.filter(|&u| trip(u, w) > i)
|
||||
.map(|u| u + i)
|
||||
.sum::<u32>()
|
||||
})
|
||||
.sum();
|
||||
words.push(acc);
|
||||
}
|
||||
}
|
||||
words
|
||||
}
|
||||
|
||||
fn pipeline(dev: &Device, bc: &[u8], name: &str, key: &VariantKey) -> ComputePipeline {
|
||||
let f = Library::from_air(bc)
|
||||
.ok()
|
||||
.and_then(|lib| lib.function(name).ok())
|
||||
.expect("kernel");
|
||||
let budget = Budget::standard();
|
||||
let compiled = dev
|
||||
.compile_function(
|
||||
&FunctionDescriptor::new(f),
|
||||
&key.lowering_inputs(Stage::Kernel),
|
||||
&budget,
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
dev.compile_compute_pipeline(
|
||||
&ComputePipelineDescriptor::new(StageSource::Compiled(compiled)),
|
||||
&budget,
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{name}: {e}"))
|
||||
}
|
||||
|
||||
fn bind_state() -> BindState {
|
||||
let mut table = StageTable::default();
|
||||
table.buffers.insert(
|
||||
0,
|
||||
BoundBuffer::Buffer {
|
||||
length: 4096,
|
||||
offset: 0,
|
||||
gpu_address: 0x1_0000,
|
||||
device_address: None,
|
||||
attribute_stride: None,
|
||||
},
|
||||
);
|
||||
let mut state = BindState::default();
|
||||
state.stages.insert(Stage::Kernel, table);
|
||||
state
|
||||
}
|
||||
|
||||
fn groups(threads_per_group: [u32; 3]) -> Dispatch {
|
||||
Dispatch::Threadgroups {
|
||||
groups: [1, ROWS, 1],
|
||||
threads_per_group,
|
||||
}
|
||||
}
|
||||
|
||||
fn keyed(axes: u8) -> VariantKey {
|
||||
let mut key = VariantKey::new();
|
||||
key.unit_axes = axes;
|
||||
key
|
||||
}
|
||||
|
||||
/// The emulated walk of a kernel whose simdgroup sum sits in a loop steered by
|
||||
/// `thread_position_in_grid.y` is predicated, and its module states the masks of unit axes that
|
||||
/// relieve it (every mask with `y`). Compiled for unit `y` it is walked unpredicated, states its
|
||||
/// axes, and gives Metal's words in threadgroups of one thread along `y` at every width, the
|
||||
/// same as the predicated module's; in a threadgroup of two threads along `y` it is not Metal's
|
||||
/// kernel (two trip counts meet the exchange's barrier: Vulkan's rule traps), which its plan
|
||||
/// never runs, sending such a dispatch back to the plain variant. Unit `x` relieves nothing of
|
||||
/// it, and the same kernel steered by `.x` is relieved by no mask without `x`, so its plan
|
||||
/// offers no variant for unit `y`.
|
||||
#[test]
|
||||
fn a_unit_axis_relieves_the_predicated_walk() {
|
||||
let dev = lavapipe();
|
||||
let (y, x) = ("unit_axes_y", "unit_axes_x");
|
||||
let n: u32 = LOCAL.iter().product();
|
||||
let Some(ybc) = assemble(y, &kernel(y, 1, n)) else {
|
||||
return;
|
||||
};
|
||||
let Some(xbc) = assemble(x, &kernel(x, 0, n)) else {
|
||||
return;
|
||||
};
|
||||
let lanes = [SubgroupSize::W8, SubgroupSize::W16, SubgroupSize::W32];
|
||||
|
||||
// The kernel's own module: predicated, relieved by every mask with `y`.
|
||||
let (base, bm) = module(&ybc, y, &dev, 0);
|
||||
assert_eq!(base.simd.1, Tier::Emulated);
|
||||
assert!(
|
||||
base.families.simd.predication.is_some(),
|
||||
"walked predicated"
|
||||
);
|
||||
assert_eq!(unit_axes(&base), Some((0, RELIEF_Y)));
|
||||
// Its variant for unit `y`: unpredicated, stating its axes.
|
||||
let (unit, um) = module(&ybc, y, &dev, 0b010);
|
||||
assert_eq!(unit.simd.1, Tier::Emulated);
|
||||
assert!(
|
||||
unit.families.simd.predication.is_none(),
|
||||
"walked unpredicated"
|
||||
);
|
||||
assert_eq!(unit_axes(&unit), Some((0b010, 0)));
|
||||
let want = expected(1);
|
||||
for w in lanes {
|
||||
assert_eq!(run_rows(&base, &bm, LOCAL, w).as_ref(), Ok(&want), "{w:?}");
|
||||
assert_eq!(run_rows(&unit, &um, LOCAL, w).as_ref(), Ok(&want), "{w:?}");
|
||||
}
|
||||
// Two threads along `y`: the variant's barrier is met by two trip counts.
|
||||
match run_rows(&unit, &um, [8, 2, 4], SubgroupSize::W32) {
|
||||
Err(InterpError::Trap(trap)) => assert_eq!(trap.kind, TrapKind::NonUniformBarrier),
|
||||
other => panic!("the unit-y module at two threads along y: {other:?}"),
|
||||
}
|
||||
// Unit `x` relieves nothing.
|
||||
let (other, _) = module(&ybc, y, &dev, 0b001);
|
||||
assert!(other.families.simd.predication.is_some(), "unit x");
|
||||
assert_eq!(unit_axes(&other), Some((0b001, 0)));
|
||||
|
||||
// The kernel steered by `x`: no relief for unit `y`.
|
||||
let (xbase, xm) = module(&xbc, x, &dev, 0);
|
||||
assert!(xbase.families.simd.predication.is_some());
|
||||
assert_eq!(unit_axes(&xbase), Some((0, RELIEF_X)));
|
||||
let (xunit, _) = module(&xbc, x, &dev, 0b010);
|
||||
assert!(xunit.families.simd.predication.is_some(), "x under unit y");
|
||||
let want = expected(0);
|
||||
for w in lanes {
|
||||
assert_eq!(run_rows(&xbase, &xm, LOCAL, w).as_ref(), Ok(&want), "{w:?}");
|
||||
}
|
||||
|
||||
// The binder's offer.
|
||||
let state = bind_state();
|
||||
let shape = state.shape();
|
||||
let plan = pipeline(&dev, &ybc, y, &VariantKey::new())
|
||||
.plan(&dev, &shape)
|
||||
.expect("plan");
|
||||
assert_eq!(
|
||||
plan.compute.as_ref().map(|c| c.local.unit_relief),
|
||||
Some(RELIEF_Y)
|
||||
);
|
||||
let row = groups(LOCAL);
|
||||
assert_eq!(plan.dispatch_variant(&row), Ok(VariantKey::new()));
|
||||
assert_eq!(plan.unit_axes_variant(&row), Ok(Some(keyed(0b010))));
|
||||
// One thread along `x` and `y`: their variant, which `y` relieves too.
|
||||
assert_eq!(
|
||||
plan.unit_axes_variant(&groups([1, 1, 32])),
|
||||
Ok(Some(keyed(0b011)))
|
||||
);
|
||||
// No unit axis, or only `x`, which relieves nothing.
|
||||
assert_eq!(plan.unit_axes_variant(&groups([8, 2, 4])), Ok(None));
|
||||
assert_eq!(plan.unit_axes_variant(&groups([1, 4, 8])), Ok(None));
|
||||
// The plain variant runs the dispatch, as it ran before.
|
||||
assert!(plan.instantiate_dispatch(&state, &row).is_ok());
|
||||
|
||||
// The variant's plan: runs threadgroups of one thread along `y` only, and offers nothing.
|
||||
let variant = pipeline(&dev, &ybc, y, &keyed(0b010));
|
||||
assert!(variant.dependencies.iter().any(|d| d.fact
|
||||
== RuntimeFact::UnitAxes {
|
||||
axes: 0b010,
|
||||
relief: 0
|
||||
}));
|
||||
let vplan = variant.plan(&dev, &shape).expect("variant plan");
|
||||
assert_eq!(
|
||||
vplan.variant,
|
||||
keyed(0b010),
|
||||
"the variant's plan states its key"
|
||||
);
|
||||
assert_eq!(vplan.dispatch_variant(&row), Ok(keyed(0b010)));
|
||||
assert!(vplan.instantiate_dispatch(&state, &row).is_ok());
|
||||
assert_eq!(vplan.unit_axes_variant(&row), Ok(None));
|
||||
let two = groups([8, 2, 4]);
|
||||
assert_eq!(vplan.dispatch_variant(&two), Ok(VariantKey::new()));
|
||||
assert_eq!(
|
||||
vplan.instantiate_dispatch(&state, &two),
|
||||
Err(BindError::NeedsVariant {
|
||||
variant: Box::new(VariantKey::new())
|
||||
})
|
||||
);
|
||||
|
||||
// The kernel steered by `x` offers no variant for unit `y`.
|
||||
let xplan = pipeline(&dev, &xbc, x, &VariantKey::new())
|
||||
.plan(&dev, &shape)
|
||||
.expect("plan");
|
||||
assert_eq!(xplan.unit_axes_variant(&row), Ok(None));
|
||||
}
|
||||
@@ -158,6 +158,7 @@ mod engine_simd_matrix;
|
||||
mod engine_simd_partly_live;
|
||||
mod engine_simd_past_n;
|
||||
mod engine_simd_products;
|
||||
mod engine_simd_unit_axes;
|
||||
mod engine_skeleton;
|
||||
mod engine_snapshot_exact;
|
||||
mod engine_sparse_unmapped;
|
||||
|
||||
@@ -3703,6 +3703,9 @@ field metal2vulkan-runtime::WorkCounts.trail_waits_blocked pub trail_waits_block
|
||||
field metal2vulkan-runtime::WorkCounts.twin_decode_failed_withheld pub twin_decode_failed_withheld: u64
|
||||
field metal2vulkan-runtime::WorkCounts.two_plane_draws pub two_plane_draws: u64
|
||||
field metal2vulkan-runtime::WorkCounts.uncached_host_images pub uncached_host_images: u64
|
||||
field metal2vulkan-runtime::WorkCounts.unit_axes_dispatches pub unit_axes_dispatches: u64
|
||||
field metal2vulkan-runtime::WorkCounts.unit_axes_meanwhile pub unit_axes_meanwhile: u64
|
||||
field metal2vulkan-runtime::WorkCounts.unit_axes_variants_begun pub unit_axes_variants_begun: u64
|
||||
field metal2vulkan-runtime::WorkCounts.unlisted_argument_sampler_buffers pub unlisted_argument_sampler_buffers: u64
|
||||
field metal2vulkan-runtime::WorkCounts.unobserved_padding_aliases pub unobserved_padding_aliases: u64
|
||||
field metal2vulkan-runtime::WorkCounts.unrun_instances_ended pub unrun_instances_ended: u64
|
||||
@@ -4480,6 +4483,7 @@ field metal2vulkan::cache::VariantKey.storage_images pub storage_images: BTreeMa
|
||||
field metal2vulkan::cache::VariantKey.storage_view_slots pub storage_view_slots: BTreeSet<SlotRef>
|
||||
field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTreeSet<SlotRef>
|
||||
field metal2vulkan::cache::VariantKey.texel_rows pub texel_rows: BTreeSet<SlotRef>
|
||||
field metal2vulkan::cache::VariantKey.unit_axes pub unit_axes: u8
|
||||
field metal2vulkan::cache::VariantKey.viewport_compensation pub viewport_compensation: Option<crate::pipeline::ViewportCompensation>
|
||||
field metal2vulkan::cache::VariantKey.window_depth_varying pub window_depth_varying: bool
|
||||
field metal2vulkan::cache::VariantKey.ycbcr_in_place pub ycbcr_in_place: BTreeSet<SlotRef>
|
||||
@@ -5105,6 +5109,7 @@ field metal2vulkan::pipeline::LoweringInputs.threadgroup_size_matches_tile_size
|
||||
field metal2vulkan::pipeline::LoweringInputs.tile_attachments pub tile_attachments: Option<BTreeMap<u32, metal::PixelFormat>>
|
||||
field metal2vulkan::pipeline::LoweringInputs.unattached_colors pub unattached_colors: BTreeSet<u32>
|
||||
field metal2vulkan::pipeline::LoweringInputs.uniform_varyings pub uniform_varyings: BTreeSet<VaryingKey>
|
||||
field metal2vulkan::pipeline::LoweringInputs.unit_axes pub unit_axes: u8
|
||||
field metal2vulkan::pipeline::LoweringInputs.vertex_fetch pub vertex_fetch: Option<VertexFetchProjection>
|
||||
field metal2vulkan::pipeline::LoweringInputs.viewport_compensation pub viewport_compensation: Option<ViewportCompensation>
|
||||
field metal2vulkan::pipeline::LoweringInputs.viewport_index_varying pub viewport_index_varying: bool
|
||||
@@ -9392,6 +9397,7 @@ method metal2vulkan::bind::BindingPlan::sampler_tables pub fn sampler_tables(&se
|
||||
method metal2vulkan::bind::BindingPlan::slot_rebinds pub fn slot_rebinds(&self, slots: &[SlotRef]) -> Option<SlotRebinds>
|
||||
method metal2vulkan::bind::BindingPlan::slot_rebinds_into pub fn slot_rebinds_into(&self, slots: &[SlotRef], into: &mut SlotRebinds) -> bool
|
||||
method metal2vulkan::bind::BindingPlan::specialized_value pub fn specialized_value(&self, key: SpecKey) -> Option<u64>
|
||||
method metal2vulkan::bind::BindingPlan::unit_axes_variant pub fn unit_axes_variant(&self, dispatch: &Dispatch) -> Result<Option<VariantKey>, BindError>
|
||||
method metal2vulkan::bind::BlockDecodeModule::shape pub fn shape([width, height, depth]: [u32; 3]) -> [u8; Self::SHAPE_WORDS as usize * 4]
|
||||
method metal2vulkan::bind::BoundAccelerationStructure::new pub fn new(instance_count: u32) -> BoundAccelerationStructure
|
||||
method metal2vulkan::bind::BoundBuffer::same_shape pub fn same_shape(&self, other: &BoundBuffer, view_base_alignment: u32) -> bool
|
||||
@@ -15185,6 +15191,7 @@ variant metal2vulkan::pipeline::RuntimeFact::TileThreadgroupMemory TileThreadgro
|
||||
variant metal2vulkan::pipeline::RuntimeFact::UlongAtomicView UlongAtomicView { slot: SlotRef }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::UniformViewAliasing UniformViewAliasing { slot: SlotRef }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::UniformViewRange UniformViewRange { slot: SlotRef, choice: UniformViewChoice }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::UnitAxes UnitAxes { axes: u8, relief: u8 }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::VertexBufferStride VertexBufferStride { layout: u32 }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::VertexFetch VertexFetch { attr: u32 }
|
||||
variant metal2vulkan::pipeline::RuntimeFact::ViewportCompensation ViewportCompensation { depth: bool, point_guard: bool, mirrors: bool, vertex_clamp: bool }
|
||||
|
||||
|
Can't render this file because it is too large.
|
+26
@@ -778,6 +778,32 @@ faster; from 40 the pinned compile took 1.6 to 24 times the emulated one and its
|
||||
were the same bits on both tiers. The estimate costs time linear in the body: 5 ms of a 3.4 s
|
||||
release translation of a 162,914-instruction kernel.
|
||||
|
||||
On the emulated tier, a simdgroup operation or barrier in a block whose control flow differs
|
||||
between threads is walked predicated: each thread carries a live flag, the threads that do not run
|
||||
the block take part in its exchanges as inactive lanes, and a loop that holds one votes on its
|
||||
exit. A kernel whose threads' positions alone make such a block differ, along some axes
|
||||
(`thread_position_in_threadgroup` or `thread_position_in_grid`, read by lane), states
|
||||
`RuntimeFact::UnitAxes { axes: 0, relief }`: `relief` holds, at bit `m - 1`, each mask `m` of axes
|
||||
(bit 0 `x`, bit 1 `y`, bit 2 `z`) under which fewer of those blocks differ once the positions along
|
||||
them are taken as uniform. In a threadgroup of one thread along an axis, Metal's
|
||||
`threads_per_threadgroup` is 1 there, so every thread's `thread_position_in_threadgroup` on that
|
||||
axis is 0 and its `thread_position_in_grid` is its threadgroup's position, partial threadgroups
|
||||
included. `BindingPlan::unit_axes_variant(&dispatch)` offers a dispatch of such threadgroups,
|
||||
where its axes are among the masks of `relief`, the kernel's unit-axes variant
|
||||
(`VariantKey::unit_axes`, which `LoweringInputs::unit_axes` compiles): the same kernel with those
|
||||
positions uniform, walked without the predication they caused, giving the same answers. Its plan
|
||||
states `UnitAxes { axes, relief: 0 }` and sends a dispatch with more than one thread along one of
|
||||
its axes back to the variant without them (`BindError::NeedsVariant`). A kernel has at most seven
|
||||
such variants per variant it runs on, one per mask. `metal2vulkan-runtime` begins the variant on
|
||||
its pipeline pool at the first dispatch it is offered to, and runs that dispatch and the next ones
|
||||
on the plain variant until the variant's translation and its regions' `VkPipeline`s are made, so
|
||||
no dispatch waits for it (`WorkCounts::unit_axes_variants_begun`, `unit_axes_meanwhile`,
|
||||
`unit_axes_dispatches`). On the Iris Xe, an authored kernel of four shuffles each way and a
|
||||
simdgroup sum in a loop of 8 to 11 trips, in threadgroups of 8 x 1 x 16, ran 1.14 to 2.16 times
|
||||
the GPU time predicated (its trip count read from `thread_position_in_grid.y`) as with the same
|
||||
trip counts read from `threadgroup_position_in_grid.y`, over four sizes from 46 to 126 estimated
|
||||
words (one run each), with the same bits.
|
||||
|
||||
### What the module contains
|
||||
|
||||
Every stage states the size and shape of its module, counted by the verifier that runs on every
|
||||
|
||||
Reference in new issue
Block a user