use std::{
fmt,
sync::atomic::{AtomicU64, Ordering},
};
use super::{
region::RegionDecline,
rules::{MergeRule, PairRule},
};
use crate::runtime::FusionStats;
const PAIR_RULE_COUNT: usize = PairRule::ALL.len();
const PAIR_OUTCOME_COUNT: usize = 2 + RegionDecline::ALL.len();
#[derive(Clone, Copy)]
pub(super) enum PairOutcome {
Applied,
LegacyGuard,
Declined(RegionDecline),
}
impl PairOutcome {
const fn index(self) -> usize {
match self {
Self::Applied => 0,
Self::LegacyGuard => 1,
Self::Declined(decline) => 2 + decline as usize,
}
}
const fn name(self) -> &'static str {
match self {
Self::Applied => "applied",
Self::LegacyGuard => "legacy_guard",
Self::Declined(decline) => decline.name(),
}
}
}
fn pair_outcomes() -> impl Iterator<Item = PairOutcome> {
[PairOutcome::Applied, PairOutcome::LegacyGuard]
.into_iter()
.chain(RegionDecline::ALL.into_iter().map(PairOutcome::Declined))
}
pub(in crate::runtime) struct PairRuleStats {
rule: PairRule,
counters: [u64; PAIR_OUTCOME_COUNT],
}
fn rule_stats(
formatter: &mut fmt::Formatter<'_>,
name: &'static str,
counters: &[u64; PAIR_OUTCOME_COUNT],
) -> fmt::Result {
let proposals = counters
.iter()
.fold(0u64, |total, count| total.wrapping_add(*count));
write!(formatter, "rule={name} proposals={proposals}")?;
for outcome in pair_outcomes() {
write!(
formatter,
" {}={}",
outcome.name(),
counters[outcome.index()]
)?;
}
Ok(())
}
impl fmt::Display for PairRuleStats {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
rule_stats(formatter, self.rule.name(), &self.counters)
}
}
pub(in crate::runtime) struct MergeRuleStats {
rule: MergeRule,
counters: [u64; PAIR_OUTCOME_COUNT],
}
impl fmt::Display for MergeRuleStats {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
rule_stats(formatter, self.rule.name(), &self.counters)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::runtime) enum NodeOutcome {
Disabled,
NotElementwise,
PolicyExcluded,
Hazard,
Isolated,
ExtentBoundary,
CrossInvocation,
ProgramRejected,
ForeignDevice,
TapeBound,
TapeCapacity,
Resource,
SpecializationDeclined,
TapeFused,
SpecializedFused,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::runtime) enum JitOutcome {
Disabled,
Admitted,
Reused,
PolicyTape,
CachedNegative,
Bound,
CompilerUnavailable,
CompileRejected,
PipelineRejected,
Queued,
Pending,
}
#[derive(Clone, Copy)]
#[repr(usize)]
enum Counter {
Examined,
Disabled,
NotElementwise,
PolicyExcluded,
Hazard,
Isolated,
ExtentBoundary,
CrossInvocation,
ProgramRejected,
ForeignDevice,
TapeBound,
TapeCapacity,
Resource,
SpecializationDeclined,
TapeFused,
SpecializedFused,
Pass,
StructuralRegion,
StructuralNode,
TapeRegion,
SpecializedRegion,
JitDisabled,
JitAdmitted,
JitReused,
JitPolicyTape,
JitCachedNegative,
JitBound,
JitCompilerUnavailable,
JitCompileRejected,
JitPipelineRejected,
JitQueued,
JitPending,
JitCompile,
JitCompileNs,
JitPipelineNs,
DnnApplied,
DnnFallback,
}
const COUNTER_COUNT: usize = Counter::DnnFallback as usize + 1;
impl NodeOutcome {
const fn counter(self) -> Counter {
match self {
Self::Disabled => Counter::Disabled,
Self::NotElementwise => Counter::NotElementwise,
Self::PolicyExcluded => Counter::PolicyExcluded,
Self::Hazard => Counter::Hazard,
Self::Isolated => Counter::Isolated,
Self::ExtentBoundary => Counter::ExtentBoundary,
Self::CrossInvocation => Counter::CrossInvocation,
Self::ProgramRejected => Counter::ProgramRejected,
Self::ForeignDevice => Counter::ForeignDevice,
Self::TapeBound => Counter::TapeBound,
Self::TapeCapacity => Counter::TapeCapacity,
Self::Resource => Counter::Resource,
Self::SpecializationDeclined => Counter::SpecializationDeclined,
Self::TapeFused => Counter::TapeFused,
Self::SpecializedFused => Counter::SpecializedFused,
}
}
}
impl JitOutcome {
const fn counter(self) -> Counter {
match self {
Self::Disabled => Counter::JitDisabled,
Self::Admitted => Counter::JitAdmitted,
Self::Reused => Counter::JitReused,
Self::PolicyTape => Counter::JitPolicyTape,
Self::CachedNegative => Counter::JitCachedNegative,
Self::Bound => Counter::JitBound,
Self::CompilerUnavailable => Counter::JitCompilerUnavailable,
Self::CompileRejected => Counter::JitCompileRejected,
Self::PipelineRejected => Counter::JitPipelineRejected,
Self::Queued => Counter::JitQueued,
Self::Pending => Counter::JitPending,
}
}
}
pub(in crate::runtime) struct FusionCensus {
counters: [AtomicU64; COUNTER_COUNT],
pairs: [[AtomicU64; PAIR_OUTCOME_COUNT]; PAIR_RULE_COUNT],
merges: [[AtomicU64; PAIR_OUTCOME_COUNT]; MergeRule::COUNT],
fusion_ns: AtomicU64,
}
impl FusionCensus {
pub(in crate::runtime) fn new() -> Self {
Self {
counters: std::array::from_fn(|_| AtomicU64::new(0)),
pairs: std::array::from_fn(|_| std::array::from_fn(|_| AtomicU64::new(0))),
merges: std::array::from_fn(|_| std::array::from_fn(|_| AtomicU64::new(0))),
fusion_ns: AtomicU64::new(0),
}
}
pub(super) fn pair(&self, rule: PairRule, outcome: PairOutcome) {
self.pairs[rule as usize][outcome.index()].fetch_add(1, Ordering::Relaxed);
}
pub(in crate::runtime) fn pair_diagnostics(&self) -> [PairRuleStats; PAIR_RULE_COUNT] {
std::array::from_fn(|index| PairRuleStats {
rule: PairRule::ALL[index],
counters: std::array::from_fn(|outcome| self.pairs[index][outcome].load(Ordering::Relaxed)),
})
}
pub(super) fn merge(&self, rule: MergeRule, outcome: PairOutcome) {
self.merges[rule as usize][outcome.index()].fetch_add(1, Ordering::Relaxed);
}
pub(in crate::runtime) fn merge_diagnostics(&self) -> Vec<MergeRuleStats> {
MergeRule::ALL
.into_iter()
.enumerate()
.map(|(index, rule)| MergeRuleStats {
rule,
counters: std::array::from_fn(|outcome| {
self.merges[index][outcome].load(Ordering::Relaxed)
}),
})
.collect()
}
fn add(&self, counter: Counter, amount: u64) {
self.counters[counter as usize].fetch_add(amount, Ordering::Relaxed);
}
fn get(&self, counter: Counter) -> u64 {
self.counters[counter as usize].load(Ordering::Relaxed)
}
pub(in crate::runtime) fn pass(&self, nodes: usize) {
self.add(Counter::Pass, 1);
self.add(Counter::Examined, nodes as u64);
}
pub(in crate::runtime) fn nodes(&self, outcome: NodeOutcome, count: usize) {
self.add(outcome.counter(), count as u64);
}
pub(in crate::runtime) fn fused(&self, specialized: bool, nodes: usize) {
let (region, outcome) = if specialized {
(Counter::SpecializedRegion, NodeOutcome::SpecializedFused)
} else {
(Counter::TapeRegion, NodeOutcome::TapeFused)
};
self.add(region, 1);
self.nodes(outcome, nodes);
}
pub(in crate::runtime) fn structural(&self, regions: usize, nodes: usize) {
self.add(Counter::StructuralRegion, regions as u64);
self.add(Counter::StructuralNode, nodes as u64);
}
pub(in crate::runtime) fn jit(&self, outcome: JitOutcome) {
self.add(outcome.counter(), 1);
}
pub(in crate::runtime) fn jit_compile(&self, elapsed: std::time::Duration) {
self.add(Counter::JitCompile, 1);
self.add(Counter::JitCompileNs, duration_ns(elapsed));
}
pub(in crate::runtime) fn jit_pipeline(&self, elapsed: std::time::Duration) {
self.add(Counter::JitPipelineNs, duration_ns(elapsed));
}
pub(in crate::runtime) fn fusion_pass(&self, elapsed: std::time::Duration) {
self
.fusion_ns
.fetch_add(duration_ns(elapsed), Ordering::Relaxed);
}
pub(in crate::runtime) fn fusion_ns(&self) -> u64 {
self.fusion_ns.load(Ordering::Relaxed)
}
pub(in crate::runtime) fn dnn(&self, applied: u32, fallback: u32) {
self.add(Counter::DnnApplied, u64::from(applied));
self.add(Counter::DnnFallback, u64::from(fallback));
}
pub(in crate::runtime) fn snapshot(&self) -> FusionStats {
FusionStats {
examined_node_count: self.get(Counter::Examined),
disabled_node_count: self.get(Counter::Disabled),
not_elementwise_node_count: self.get(Counter::NotElementwise),
policy_excluded_node_count: self.get(Counter::PolicyExcluded),
hazard_node_count: self.get(Counter::Hazard),
isolated_node_count: self.get(Counter::Isolated),
extent_boundary_node_count: self.get(Counter::ExtentBoundary),
cross_invocation_node_count: self.get(Counter::CrossInvocation),
program_rejected_node_count: self.get(Counter::ProgramRejected),
foreign_device_node_count: self.get(Counter::ForeignDevice),
tape_bound_node_count: self.get(Counter::TapeBound),
tape_capacity_node_count: self.get(Counter::TapeCapacity),
resource_node_count: self.get(Counter::Resource),
specialization_declined_node_count: self.get(Counter::SpecializationDeclined),
tape_fused_node_count: self.get(Counter::TapeFused),
specialized_fused_node_count: self.get(Counter::SpecializedFused),
pass_count: self.get(Counter::Pass),
structural_region_count: self.get(Counter::StructuralRegion),
structural_node_count: self.get(Counter::StructuralNode),
tape_region_count: self.get(Counter::TapeRegion),
specialized_region_count: self.get(Counter::SpecializedRegion),
jit_disabled_count: self.get(Counter::JitDisabled),
jit_admitted_count: self.get(Counter::JitAdmitted),
jit_reused_count: self.get(Counter::JitReused),
jit_policy_tape_count: self.get(Counter::JitPolicyTape),
jit_cached_negative_count: self.get(Counter::JitCachedNegative),
jit_bound_count: self.get(Counter::JitBound),
jit_compiler_unavailable_count: self.get(Counter::JitCompilerUnavailable),
jit_compile_rejected_count: self.get(Counter::JitCompileRejected),
jit_pipeline_rejected_count: self.get(Counter::JitPipelineRejected),
jit_queued_count: self.get(Counter::JitQueued),
jit_pending_count: self.get(Counter::JitPending),
jit_compile_count: self.get(Counter::JitCompile),
jit_compile_ns: self.get(Counter::JitCompileNs),
jit_pipeline_ns: self.get(Counter::JitPipelineNs),
dnn_applied_partition_count: self.get(Counter::DnnApplied),
dnn_fallback_partition_count: self.get(Counter::DnnFallback),
}
}
}
fn duration_ns(elapsed: std::time::Duration) -> u64 {
u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX)
}
impl FusionStats {
pub const fn examined_node_count(self) -> u64 {
self.examined_node_count
}
pub const fn disabled_node_count(self) -> u64 {
self.disabled_node_count
}
pub const fn not_elementwise_node_count(self) -> u64 {
self.not_elementwise_node_count
}
pub const fn policy_excluded_node_count(self) -> u64 {
self.policy_excluded_node_count
}
pub const fn hazard_node_count(self) -> u64 {
self.hazard_node_count
}
pub const fn isolated_node_count(self) -> u64 {
self.isolated_node_count
}
pub const fn extent_boundary_node_count(self) -> u64 {
self.extent_boundary_node_count
}
pub const fn cross_invocation_node_count(self) -> u64 {
self.cross_invocation_node_count
}
pub const fn program_rejected_node_count(self) -> u64 {
self.program_rejected_node_count
}
pub const fn foreign_device_node_count(self) -> u64 {
self.foreign_device_node_count
}
pub const fn tape_bound_node_count(self) -> u64 {
self.tape_bound_node_count
}
pub const fn tape_capacity_node_count(self) -> u64 {
self.tape_capacity_node_count
}
pub const fn resource_node_count(self) -> u64 {
self.resource_node_count
}
pub const fn specialization_declined_node_count(self) -> u64 {
self.specialization_declined_node_count
}
pub const fn tape_fused_node_count(self) -> u64 {
self.tape_fused_node_count
}
pub const fn specialized_fused_node_count(self) -> u64 {
self.specialized_fused_node_count
}
pub const fn pass_count(self) -> u64 {
self.pass_count
}
pub const fn structural_region_count(self) -> u64 {
self.structural_region_count
}
pub const fn structural_node_count(self) -> u64 {
self.structural_node_count
}
pub const fn tape_region_count(self) -> u64 {
self.tape_region_count
}
pub const fn specialized_region_count(self) -> u64 {
self.specialized_region_count
}
pub const fn jit_disabled_count(self) -> u64 {
self.jit_disabled_count
}
pub const fn jit_admitted_count(self) -> u64 {
self.jit_admitted_count
}
pub const fn jit_reused_count(self) -> u64 {
self.jit_reused_count
}
pub const fn jit_policy_tape_count(self) -> u64 {
self.jit_policy_tape_count
}
pub const fn jit_cached_negative_count(self) -> u64 {
self.jit_cached_negative_count
}
pub const fn jit_bound_count(self) -> u64 {
self.jit_bound_count
}
pub const fn jit_compiler_unavailable_count(self) -> u64 {
self.jit_compiler_unavailable_count
}
pub const fn jit_compile_rejected_count(self) -> u64 {
self.jit_compile_rejected_count
}
pub const fn jit_pipeline_rejected_count(self) -> u64 {
self.jit_pipeline_rejected_count
}
pub const fn jit_queued_count(self) -> u64 {
self.jit_queued_count
}
pub const fn jit_pending_count(self) -> u64 {
self.jit_pending_count
}
pub const fn jit_compile_count(self) -> u64 {
self.jit_compile_count
}
pub const fn jit_compile_ns(self) -> u64 {
self.jit_compile_ns
}
pub const fn jit_pipeline_ns(self) -> u64 {
self.jit_pipeline_ns
}
pub const fn dnn_applied_partition_count(self) -> u64 {
self.dnn_applied_partition_count
}
pub const fn dnn_fallback_partition_count(self) -> u64 {
self.dnn_fallback_partition_count
}
}
impl fmt::Display for FusionStats {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let fields = [
("examined", self.examined_node_count),
("disabled", self.disabled_node_count),
("not_elementwise", self.not_elementwise_node_count),
("policy_excluded", self.policy_excluded_node_count),
("hazard", self.hazard_node_count),
("isolated", self.isolated_node_count),
("extent_boundary", self.extent_boundary_node_count),
("cross_invocation", self.cross_invocation_node_count),
("program_rejected", self.program_rejected_node_count),
("foreign_device", self.foreign_device_node_count),
("tape_bound", self.tape_bound_node_count),
("tape_capacity", self.tape_capacity_node_count),
("resource", self.resource_node_count),
(
"specialization_declined",
self.specialization_declined_node_count,
),
("tape_fused", self.tape_fused_node_count),
("specialized_fused", self.specialized_fused_node_count),
("passes", self.pass_count),
("structural_regions", self.structural_region_count),
("structural_nodes", self.structural_node_count),
("tape_regions", self.tape_region_count),
("specialized_regions", self.specialized_region_count),
("jit_disabled", self.jit_disabled_count),
("jit_admitted", self.jit_admitted_count),
("jit_reused", self.jit_reused_count),
("jit_policy_tape", self.jit_policy_tape_count),
("jit_cached_negative", self.jit_cached_negative_count),
("jit_bound", self.jit_bound_count),
(
"jit_compiler_unavailable",
self.jit_compiler_unavailable_count,
),
("jit_compile_rejected", self.jit_compile_rejected_count),
("jit_pipeline_rejected", self.jit_pipeline_rejected_count),
("jit_queued", self.jit_queued_count),
("jit_pending", self.jit_pending_count),
("jit_compiles", self.jit_compile_count),
("jit_compile_ns", self.jit_compile_ns),
("jit_pipeline_ns", self.jit_pipeline_ns),
("dnn_applied", self.dnn_applied_partition_count),
("dnn_fallback", self.dnn_fallback_partition_count),
];
for (index, (key, value)) in fields.iter().enumerate() {
if index > 0 {
formatter.write_str(" ")?;
}
write!(formatter, "{key}={value}")?;
}
Ok(())
}
}
#[cfg(test)]
#[path = "../../../../../../test/rs/runtime/fusion_census_unit.rs"]
mod tests;