1use std::{
12 fmt,
13 sync::atomic::{AtomicU64, Ordering},
14};
15
16use super::{
17 region::RegionDecline,
18 rules::{MergeRule, PairRule},
19};
20use crate::runtime::FusionStats;
21
22const PAIR_RULE_COUNT: usize = PairRule::ALL.len();
23const PAIR_OUTCOME_COUNT: usize = 2 + RegionDecline::ALL.len();
24
25#[derive(Clone, Copy)]
29pub(super) enum PairOutcome {
30 Applied,
31 LegacyGuard,
32 Declined(RegionDecline),
33}
34
35impl PairOutcome {
36 const fn index(self) -> usize {
37 match self {
38 Self::Applied => 0,
39 Self::LegacyGuard => 1,
40 Self::Declined(decline) => 2 + decline as usize,
41 }
42 }
43
44 const fn name(self) -> &'static str {
45 match self {
46 Self::Applied => "applied",
47 Self::LegacyGuard => "legacy_guard",
48 Self::Declined(decline) => decline.name(),
49 }
50 }
51}
52
53fn pair_outcomes() -> impl Iterator<Item = PairOutcome> {
54 [PairOutcome::Applied, PairOutcome::LegacyGuard]
55 .into_iter()
56 .chain(RegionDecline::ALL.into_iter().map(PairOutcome::Declined))
57}
58
59pub(in crate::runtime) struct PairRuleStats {
62 rule: PairRule,
63 counters: [u64; PAIR_OUTCOME_COUNT],
64}
65
66fn rule_stats(
67 formatter: &mut fmt::Formatter<'_>,
68 name: &'static str,
69 counters: &[u64; PAIR_OUTCOME_COUNT],
70) -> fmt::Result {
71 let proposals = counters
72 .iter()
73 .fold(0u64, |total, count| total.wrapping_add(*count));
74 write!(formatter, "rule={name} proposals={proposals}")?;
75 for outcome in pair_outcomes() {
76 write!(
77 formatter,
78 " {}={}",
79 outcome.name(),
80 counters[outcome.index()]
81 )?;
82 }
83 Ok(())
84}
85
86impl fmt::Display for PairRuleStats {
87 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88 rule_stats(formatter, self.rule.name(), &self.counters)
89 }
90}
91
92pub(in crate::runtime) struct MergeRuleStats {
94 rule: MergeRule,
95 counters: [u64; PAIR_OUTCOME_COUNT],
96}
97
98impl fmt::Display for MergeRuleStats {
99 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
100 rule_stats(formatter, self.rule.name(), &self.counters)
101 }
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub(in crate::runtime) enum NodeOutcome {
107 Disabled,
109 NotElementwise,
111 PolicyExcluded,
113 Hazard,
115 Isolated,
117 ExtentBoundary,
119 CrossInvocation,
121 ProgramRejected,
123 ForeignDevice,
125 TapeBound,
127 TapeCapacity,
129 Resource,
131 SpecializationDeclined,
133 TapeFused,
135 SpecializedFused,
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub(in crate::runtime) enum JitOutcome {
142 Disabled,
144 Admitted,
146 Reused,
148 PolicyTape,
150 CachedNegative,
152 Bound,
154 CompilerUnavailable,
156 CompileRejected,
158 PipelineRejected,
160 Queued,
162 Pending,
164}
165
166#[derive(Clone, Copy)]
167#[repr(usize)]
168enum Counter {
169 Examined,
170 Disabled,
171 NotElementwise,
172 PolicyExcluded,
173 Hazard,
174 Isolated,
175 ExtentBoundary,
176 CrossInvocation,
177 ProgramRejected,
178 ForeignDevice,
179 TapeBound,
180 TapeCapacity,
181 Resource,
182 SpecializationDeclined,
183 TapeFused,
184 SpecializedFused,
185 Pass,
186 StructuralRegion,
187 StructuralNode,
188 TapeRegion,
189 SpecializedRegion,
190 JitDisabled,
191 JitAdmitted,
192 JitReused,
193 JitPolicyTape,
194 JitCachedNegative,
195 JitBound,
196 JitCompilerUnavailable,
197 JitCompileRejected,
198 JitPipelineRejected,
199 JitQueued,
200 JitPending,
201 JitCompile,
202 JitCompileNs,
203 JitPipelineNs,
204 DnnApplied,
205 DnnFallback,
206}
207
208const COUNTER_COUNT: usize = Counter::DnnFallback as usize + 1;
209
210impl NodeOutcome {
211 const fn counter(self) -> Counter {
212 match self {
213 Self::Disabled => Counter::Disabled,
214 Self::NotElementwise => Counter::NotElementwise,
215 Self::PolicyExcluded => Counter::PolicyExcluded,
216 Self::Hazard => Counter::Hazard,
217 Self::Isolated => Counter::Isolated,
218 Self::ExtentBoundary => Counter::ExtentBoundary,
219 Self::CrossInvocation => Counter::CrossInvocation,
220 Self::ProgramRejected => Counter::ProgramRejected,
221 Self::ForeignDevice => Counter::ForeignDevice,
222 Self::TapeBound => Counter::TapeBound,
223 Self::TapeCapacity => Counter::TapeCapacity,
224 Self::Resource => Counter::Resource,
225 Self::SpecializationDeclined => Counter::SpecializationDeclined,
226 Self::TapeFused => Counter::TapeFused,
227 Self::SpecializedFused => Counter::SpecializedFused,
228 }
229 }
230}
231
232impl JitOutcome {
233 const fn counter(self) -> Counter {
234 match self {
235 Self::Disabled => Counter::JitDisabled,
236 Self::Admitted => Counter::JitAdmitted,
237 Self::Reused => Counter::JitReused,
238 Self::PolicyTape => Counter::JitPolicyTape,
239 Self::CachedNegative => Counter::JitCachedNegative,
240 Self::Bound => Counter::JitBound,
241 Self::CompilerUnavailable => Counter::JitCompilerUnavailable,
242 Self::CompileRejected => Counter::JitCompileRejected,
243 Self::PipelineRejected => Counter::JitPipelineRejected,
244 Self::Queued => Counter::JitQueued,
245 Self::Pending => Counter::JitPending,
246 }
247 }
248}
249
250pub(in crate::runtime) struct FusionCensus {
251 counters: [AtomicU64; COUNTER_COUNT],
252 pairs: [[AtomicU64; PAIR_OUTCOME_COUNT]; PAIR_RULE_COUNT],
253 merges: [[AtomicU64; PAIR_OUTCOME_COUNT]; MergeRule::COUNT],
254 fusion_ns: AtomicU64,
258}
259
260impl FusionCensus {
261 pub(in crate::runtime) fn new() -> Self {
262 Self {
263 counters: std::array::from_fn(|_| AtomicU64::new(0)),
264 pairs: std::array::from_fn(|_| std::array::from_fn(|_| AtomicU64::new(0))),
265 merges: std::array::from_fn(|_| std::array::from_fn(|_| AtomicU64::new(0))),
266 fusion_ns: AtomicU64::new(0),
267 }
268 }
269
270 pub(super) fn pair(&self, rule: PairRule, outcome: PairOutcome) {
271 self.pairs[rule as usize][outcome.index()].fetch_add(1, Ordering::Relaxed);
272 }
273
274 pub(in crate::runtime) fn pair_diagnostics(&self) -> [PairRuleStats; PAIR_RULE_COUNT] {
275 std::array::from_fn(|index| PairRuleStats {
276 rule: PairRule::ALL[index],
277 counters: std::array::from_fn(|outcome| self.pairs[index][outcome].load(Ordering::Relaxed)),
278 })
279 }
280
281 pub(super) fn merge(&self, rule: MergeRule, outcome: PairOutcome) {
282 self.merges[rule as usize][outcome.index()].fetch_add(1, Ordering::Relaxed);
283 }
284
285 pub(in crate::runtime) fn merge_diagnostics(&self) -> Vec<MergeRuleStats> {
286 MergeRule::ALL
287 .into_iter()
288 .enumerate()
289 .map(|(index, rule)| MergeRuleStats {
290 rule,
291 counters: std::array::from_fn(|outcome| {
292 self.merges[index][outcome].load(Ordering::Relaxed)
293 }),
294 })
295 .collect()
296 }
297
298 fn add(&self, counter: Counter, amount: u64) {
299 self.counters[counter as usize].fetch_add(amount, Ordering::Relaxed);
302 }
303
304 fn get(&self, counter: Counter) -> u64 {
305 self.counters[counter as usize].load(Ordering::Relaxed)
306 }
307
308 pub(in crate::runtime) fn pass(&self, nodes: usize) {
310 self.add(Counter::Pass, 1);
311 self.add(Counter::Examined, nodes as u64);
312 }
313
314 pub(in crate::runtime) fn nodes(&self, outcome: NodeOutcome, count: usize) {
315 self.add(outcome.counter(), count as u64);
316 }
317
318 pub(in crate::runtime) fn fused(&self, specialized: bool, nodes: usize) {
320 let (region, outcome) = if specialized {
321 (Counter::SpecializedRegion, NodeOutcome::SpecializedFused)
322 } else {
323 (Counter::TapeRegion, NodeOutcome::TapeFused)
324 };
325 self.add(region, 1);
326 self.nodes(outcome, nodes);
327 }
328
329 pub(in crate::runtime) fn structural(&self, regions: usize, nodes: usize) {
331 self.add(Counter::StructuralRegion, regions as u64);
332 self.add(Counter::StructuralNode, nodes as u64);
333 }
334
335 pub(in crate::runtime) fn jit(&self, outcome: JitOutcome) {
336 self.add(outcome.counter(), 1);
337 }
338
339 pub(in crate::runtime) fn jit_compile(&self, elapsed: std::time::Duration) {
340 self.add(Counter::JitCompile, 1);
341 self.add(Counter::JitCompileNs, duration_ns(elapsed));
342 }
343
344 pub(in crate::runtime) fn jit_pipeline(&self, elapsed: std::time::Duration) {
345 self.add(Counter::JitPipelineNs, duration_ns(elapsed));
346 }
347
348 pub(in crate::runtime) fn fusion_pass(&self, elapsed: std::time::Duration) {
352 self
353 .fusion_ns
354 .fetch_add(duration_ns(elapsed), Ordering::Relaxed);
355 }
356
357 pub(in crate::runtime) fn fusion_ns(&self) -> u64 {
359 self.fusion_ns.load(Ordering::Relaxed)
360 }
361
362 pub(in crate::runtime) fn dnn(&self, applied: u32, fallback: u32) {
364 self.add(Counter::DnnApplied, u64::from(applied));
365 self.add(Counter::DnnFallback, u64::from(fallback));
366 }
367
368 pub(in crate::runtime) fn snapshot(&self) -> FusionStats {
369 FusionStats {
370 examined_node_count: self.get(Counter::Examined),
371 disabled_node_count: self.get(Counter::Disabled),
372 not_elementwise_node_count: self.get(Counter::NotElementwise),
373 policy_excluded_node_count: self.get(Counter::PolicyExcluded),
374 hazard_node_count: self.get(Counter::Hazard),
375 isolated_node_count: self.get(Counter::Isolated),
376 extent_boundary_node_count: self.get(Counter::ExtentBoundary),
377 cross_invocation_node_count: self.get(Counter::CrossInvocation),
378 program_rejected_node_count: self.get(Counter::ProgramRejected),
379 foreign_device_node_count: self.get(Counter::ForeignDevice),
380 tape_bound_node_count: self.get(Counter::TapeBound),
381 tape_capacity_node_count: self.get(Counter::TapeCapacity),
382 resource_node_count: self.get(Counter::Resource),
383 specialization_declined_node_count: self.get(Counter::SpecializationDeclined),
384 tape_fused_node_count: self.get(Counter::TapeFused),
385 specialized_fused_node_count: self.get(Counter::SpecializedFused),
386 pass_count: self.get(Counter::Pass),
387 structural_region_count: self.get(Counter::StructuralRegion),
388 structural_node_count: self.get(Counter::StructuralNode),
389 tape_region_count: self.get(Counter::TapeRegion),
390 specialized_region_count: self.get(Counter::SpecializedRegion),
391 jit_disabled_count: self.get(Counter::JitDisabled),
392 jit_admitted_count: self.get(Counter::JitAdmitted),
393 jit_reused_count: self.get(Counter::JitReused),
394 jit_policy_tape_count: self.get(Counter::JitPolicyTape),
395 jit_cached_negative_count: self.get(Counter::JitCachedNegative),
396 jit_bound_count: self.get(Counter::JitBound),
397 jit_compiler_unavailable_count: self.get(Counter::JitCompilerUnavailable),
398 jit_compile_rejected_count: self.get(Counter::JitCompileRejected),
399 jit_pipeline_rejected_count: self.get(Counter::JitPipelineRejected),
400 jit_queued_count: self.get(Counter::JitQueued),
401 jit_pending_count: self.get(Counter::JitPending),
402 jit_compile_count: self.get(Counter::JitCompile),
403 jit_compile_ns: self.get(Counter::JitCompileNs),
404 jit_pipeline_ns: self.get(Counter::JitPipelineNs),
405 dnn_applied_partition_count: self.get(Counter::DnnApplied),
406 dnn_fallback_partition_count: self.get(Counter::DnnFallback),
407 }
408 }
409}
410
411fn duration_ns(elapsed: std::time::Duration) -> u64 {
412 u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX)
413}
414
415impl FusionStats {
416 pub const fn examined_node_count(self) -> u64 {
422 self.examined_node_count
423 }
424
425 pub const fn disabled_node_count(self) -> u64 {
427 self.disabled_node_count
428 }
429
430 pub const fn not_elementwise_node_count(self) -> u64 {
434 self.not_elementwise_node_count
435 }
436
437 pub const fn policy_excluded_node_count(self) -> u64 {
439 self.policy_excluded_node_count
440 }
441
442 pub const fn hazard_node_count(self) -> u64 {
444 self.hazard_node_count
445 }
446
447 pub const fn isolated_node_count(self) -> u64 {
449 self.isolated_node_count
450 }
451
452 pub const fn extent_boundary_node_count(self) -> u64 {
454 self.extent_boundary_node_count
455 }
456
457 pub const fn cross_invocation_node_count(self) -> u64 {
460 self.cross_invocation_node_count
461 }
462
463 pub const fn program_rejected_node_count(self) -> u64 {
465 self.program_rejected_node_count
466 }
467
468 pub const fn foreign_device_node_count(self) -> u64 {
470 self.foreign_device_node_count
471 }
472
473 pub const fn tape_bound_node_count(self) -> u64 {
475 self.tape_bound_node_count
476 }
477
478 pub const fn tape_capacity_node_count(self) -> u64 {
480 self.tape_capacity_node_count
481 }
482
483 pub const fn resource_node_count(self) -> u64 {
485 self.resource_node_count
486 }
487
488 pub const fn specialization_declined_node_count(self) -> u64 {
490 self.specialization_declined_node_count
491 }
492
493 pub const fn tape_fused_node_count(self) -> u64 {
495 self.tape_fused_node_count
496 }
497
498 pub const fn specialized_fused_node_count(self) -> u64 {
500 self.specialized_fused_node_count
501 }
502
503 pub const fn pass_count(self) -> u64 {
508 self.pass_count
509 }
510
511 pub const fn structural_region_count(self) -> u64 {
513 self.structural_region_count
514 }
515
516 pub const fn structural_node_count(self) -> u64 {
518 self.structural_node_count
519 }
520
521 pub const fn tape_region_count(self) -> u64 {
523 self.tape_region_count
524 }
525
526 pub const fn specialized_region_count(self) -> u64 {
528 self.specialized_region_count
529 }
530
531 pub const fn jit_disabled_count(self) -> u64 {
533 self.jit_disabled_count
534 }
535
536 pub const fn jit_admitted_count(self) -> u64 {
538 self.jit_admitted_count
539 }
540
541 pub const fn jit_reused_count(self) -> u64 {
543 self.jit_reused_count
544 }
545
546 pub const fn jit_policy_tape_count(self) -> u64 {
548 self.jit_policy_tape_count
549 }
550
551 pub const fn jit_cached_negative_count(self) -> u64 {
553 self.jit_cached_negative_count
554 }
555
556 pub const fn jit_bound_count(self) -> u64 {
558 self.jit_bound_count
559 }
560
561 pub const fn jit_compiler_unavailable_count(self) -> u64 {
563 self.jit_compiler_unavailable_count
564 }
565
566 pub const fn jit_compile_rejected_count(self) -> u64 {
568 self.jit_compile_rejected_count
569 }
570
571 pub const fn jit_pipeline_rejected_count(self) -> u64 {
573 self.jit_pipeline_rejected_count
574 }
575
576 pub const fn jit_queued_count(self) -> u64 {
578 self.jit_queued_count
579 }
580
581 pub const fn jit_pending_count(self) -> u64 {
583 self.jit_pending_count
584 }
585
586 pub const fn jit_compile_count(self) -> u64 {
588 self.jit_compile_count
589 }
590
591 pub const fn jit_compile_ns(self) -> u64 {
593 self.jit_compile_ns
594 }
595
596 pub const fn jit_pipeline_ns(self) -> u64 {
598 self.jit_pipeline_ns
599 }
600
601 pub const fn dnn_applied_partition_count(self) -> u64 {
603 self.dnn_applied_partition_count
604 }
605
606 pub const fn dnn_fallback_partition_count(self) -> u64 {
608 self.dnn_fallback_partition_count
609 }
610}
611
612impl fmt::Display for FusionStats {
614 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
615 let fields = [
616 ("examined", self.examined_node_count),
617 ("disabled", self.disabled_node_count),
618 ("not_elementwise", self.not_elementwise_node_count),
619 ("policy_excluded", self.policy_excluded_node_count),
620 ("hazard", self.hazard_node_count),
621 ("isolated", self.isolated_node_count),
622 ("extent_boundary", self.extent_boundary_node_count),
623 ("cross_invocation", self.cross_invocation_node_count),
624 ("program_rejected", self.program_rejected_node_count),
625 ("foreign_device", self.foreign_device_node_count),
626 ("tape_bound", self.tape_bound_node_count),
627 ("tape_capacity", self.tape_capacity_node_count),
628 ("resource", self.resource_node_count),
629 (
630 "specialization_declined",
631 self.specialization_declined_node_count,
632 ),
633 ("tape_fused", self.tape_fused_node_count),
634 ("specialized_fused", self.specialized_fused_node_count),
635 ("passes", self.pass_count),
636 ("structural_regions", self.structural_region_count),
637 ("structural_nodes", self.structural_node_count),
638 ("tape_regions", self.tape_region_count),
639 ("specialized_regions", self.specialized_region_count),
640 ("jit_disabled", self.jit_disabled_count),
641 ("jit_admitted", self.jit_admitted_count),
642 ("jit_reused", self.jit_reused_count),
643 ("jit_policy_tape", self.jit_policy_tape_count),
644 ("jit_cached_negative", self.jit_cached_negative_count),
645 ("jit_bound", self.jit_bound_count),
646 (
647 "jit_compiler_unavailable",
648 self.jit_compiler_unavailable_count,
649 ),
650 ("jit_compile_rejected", self.jit_compile_rejected_count),
651 ("jit_pipeline_rejected", self.jit_pipeline_rejected_count),
652 ("jit_queued", self.jit_queued_count),
653 ("jit_pending", self.jit_pending_count),
654 ("jit_compiles", self.jit_compile_count),
655 ("jit_compile_ns", self.jit_compile_ns),
656 ("jit_pipeline_ns", self.jit_pipeline_ns),
657 ("dnn_applied", self.dnn_applied_partition_count),
658 ("dnn_fallback", self.dnn_fallback_partition_count),
659 ];
660 for (index, (key, value)) in fields.iter().enumerate() {
661 if index > 0 {
662 formatter.write_str(" ")?;
663 }
664 write!(formatter, "{key}={value}")?;
665 }
666 Ok(())
667 }
668}
669
670#[cfg(test)]
671#[path = "../../../../../../test/rs/runtime/fusion_census_unit.rs"]
672mod tests;