1use super::MegakernelWorkItem;
7
8mod prologue;
9pub use prologue::shared_prologue_length;
10
11pub(super) const MAX_DENSE_FUSION_ITEMS: usize = 4096;
15
16#[derive(Debug, Default)]
21pub struct FusionSelectionScratch {
22 order: Vec<usize>,
23 result: Vec<u32>,
24 conflict_degrees: Vec<u32>,
25 selected: Vec<usize>,
26}
27
28impl FusionSelectionScratch {
29 #[must_use]
31 pub fn result(&self) -> &[u32] {
32 &self.result
33 }
34
35 #[must_use]
37 pub fn take_result(&mut self) -> Vec<u32> {
38 std::mem::take(&mut self.result)
39 }
40
41 fn prepare(&mut self, n: usize) {
42 self.order.clear();
43 self.order.extend(0..n);
44 self.result.clear();
45 self.result.resize(n, 0);
46 self.conflict_degrees.clear();
47 self.conflict_degrees.resize(n, 0);
48 self.selected.clear();
49 }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum FusionSelectionError {
55 ExchangeSizeOverflow {
57 n: usize,
59 },
60 CostLen {
62 expected: usize,
64 actual: usize,
66 },
67 ExchangeAdjLen {
69 expected: usize,
71 actual: usize,
73 },
74}
75
76impl std::fmt::Display for FusionSelectionError {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 match self {
79 Self::ExchangeSizeOverflow { n } => write!(
80 f,
81 "megakernel fusion selector n*n overflow for n={n}. Fix: shard the work batch before fusion selection."
82 ),
83 Self::CostLen { expected, actual } => write!(
84 f,
85 "megakernel fusion selector cost length {actual} does not match n={expected}. Fix: pass one cost per work item."
86 ),
87 Self::ExchangeAdjLen { expected, actual } => write!(
88 f,
89 "megakernel fusion selector exchange_adj length {actual} does not match n*n={expected}. Fix: pass a dense row-major n*n exchange graph."
90 ),
91 }
92 }
93}
94
95impl std::error::Error for FusionSelectionError {}
96
97fn validate_selector_shape(
98 cost_len: usize,
99 n: u32,
100 exchange_adj_len: usize,
101) -> Result<(usize, usize), FusionSelectionError> {
102 let n_usize = usize::try_from(n)
103 .map_err(|_| FusionSelectionError::ExchangeSizeOverflow { n: usize::MAX })?;
104 let cells = n_usize
105 .checked_mul(n_usize)
106 .ok_or(FusionSelectionError::ExchangeSizeOverflow { n: n_usize })?;
107 if cost_len != n_usize {
108 return Err(FusionSelectionError::CostLen {
109 expected: n_usize,
110 actual: cost_len,
111 });
112 }
113 if exchange_adj_len != cells {
114 return Err(FusionSelectionError::ExchangeAdjLen {
115 expected: cells,
116 actual: exchange_adj_len,
117 });
118 }
119 Ok((n_usize, cells))
120}
121
122#[derive(Debug, Default)]
127pub struct CompactFusionPlanningScratch {
128 costs_q16: Vec<u16>,
129 stalks: Vec<f32>,
130 diffused_stalks: Vec<f32>,
131 effective_divergence: Vec<u32>,
132 deltas: Vec<f32>,
133 sorted_deltas: Vec<f32>,
134 exchange_adj: Vec<u32>,
135 order: Vec<usize>,
136 selection: FusionSelectionScratch,
137}
138
139impl CompactFusionPlanningScratch {
140 #[must_use]
142 pub fn exchange_adj(&self) -> &[u32] {
143 &self.exchange_adj
144 }
145
146 #[must_use]
148 pub fn selected(&self) -> &[u32] {
149 self.selection.result()
150 }
151}
152
153pub fn plan_compact_fusion_into<'a>(
158 work_items: &[MegakernelWorkItem],
159 scratch: &'a mut CompactFusionPlanningScratch,
160) -> &'a [u32] {
161 let n = work_items.len();
162 if n > MAX_DENSE_FUSION_ITEMS {
163 scratch.selection.prepare(n);
164 scratch.selection.result.fill(1);
165 scratch.exchange_adj.clear();
166 return scratch.selection.result();
167 }
168
169 if n == 0 {
170 scratch.costs_q16.clear();
171 scratch.stalks.clear();
172 scratch.diffused_stalks.clear();
173 scratch.effective_divergence.clear();
174 scratch.deltas.clear();
175 scratch.sorted_deltas.clear();
176 scratch.exchange_adj.clear();
177 scratch.selection.prepare(0);
178 return scratch.selection.result();
179 }
180
181 scratch.costs_q16.clear();
182 scratch.costs_q16.resize(n, u16::MAX);
183
184 scratch.stalks.clear();
185 scratch.stalks.extend(
186 work_items
187 .iter()
188 .enumerate()
189 .map(|(item_idx, _item)| (item_idx as f32) * 0.001),
190 );
191 scratch.diffused_stalks.clear();
192 scratch.diffused_stalks.extend_from_slice(&scratch.stalks);
193 for _ in 0..8 {
194 for value in &mut scratch.diffused_stalks {
195 *value -= 0.5_f32 * 0.7_f32 * *value;
196 }
197 }
198
199 let divergence_threshold = 0.05_f32;
200 let mut delta_sum = 0.0_f32;
201 let mut delta_max = 0.0_f32;
202 scratch.effective_divergence.clear();
203 for (&initial, &diffused) in scratch.stalks.iter().zip(scratch.diffused_stalks.iter()) {
204 let delta = (initial - diffused).abs();
205 delta_sum += delta;
206 delta_max = delta_max.max(delta);
207 scratch
208 .effective_divergence
209 .push(u32::from(delta > divergence_threshold));
210 }
211
212 let n_f32 = n as f32;
213 let gap_signal = if delta_max > 0.0_f32 && n_f32 > 0.0_f32 {
214 delta_sum / (n_f32 * delta_max)
215 } else {
216 1.0_f32
217 };
218 if gap_signal < 0.3 {
219 scratch.deltas.clear();
220 scratch.deltas.extend(
221 scratch
222 .stalks
223 .iter()
224 .zip(scratch.diffused_stalks.iter())
225 .map(|(s, d)| (s - d).abs()),
226 );
227 scratch.sorted_deltas.clear();
228 scratch.sorted_deltas.extend_from_slice(&scratch.deltas);
229 scratch
230 .sorted_deltas
231 .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
232 let median = scratch
233 .sorted_deltas
234 .get(scratch.sorted_deltas.len() / 2)
235 .copied()
236 .unwrap_or(0.0);
237 for (flag, delta) in scratch
238 .effective_divergence
239 .iter_mut()
240 .zip(scratch.deltas.iter())
241 {
242 if *delta < median {
243 *flag = 0;
244 }
245 }
246 }
247
248 scratch.exchange_adj.clear();
249 let dense_cells = n * n;
250 scratch.exchange_adj.resize(dense_cells, 0);
251 let mut has_exchange_conflict = false;
252
253 let mut has_op_conflict = false;
254 scratch.order.clear();
255 scratch.order.extend(0..n);
256 if scratch.order.len() > 1 {
257 scratch
258 .order
259 .sort_unstable_by_key(|&item_idx| work_items[item_idx].op_handle);
260 if scratch
261 .order
262 .windows(2)
263 .any(|window| work_items[window[0]].op_handle == work_items[window[1]].op_handle)
264 {
265 has_op_conflict = true;
266 }
267 }
268 let has_output_input_chain = (0..n.checked_sub(1).unwrap_or(0)).any(|i| {
269 work_items.get(i).map(|w| w.output_handle) == work_items.get(i + 1).map(|w| w.input_handle)
270 });
271 let has_divergence_conflict = scratch.effective_divergence.iter().any(|&v| v != 0);
272 scratch.selection.prepare(n);
273
274 if !has_op_conflict && !has_divergence_conflict {
275 if has_output_input_chain {
276 for cost in scratch.costs_q16.iter_mut() {
277 *cost = discount_q16(*cost, 3_276);
278 }
279 }
280
281 scratch.selection.result.fill(1);
282 return scratch.selection.result();
283 }
284
285 {
286 let conflict_degrees = &mut scratch.selection.conflict_degrees;
287 for i in 0..n {
288 let row_start = i * n;
289 for j in 0..n {
290 if i == j {
291 continue;
292 }
293 let same_op = work_items[i].op_handle == work_items[j].op_handle;
294 if n <= 32 && same_op {
295 scratch.costs_q16[i] = discount_q16(scratch.costs_q16[i], 3_276);
296 }
297 let divergent =
298 scratch.effective_divergence[i] != 0 && scratch.effective_divergence[j] != 0;
299 if same_op || divergent {
300 scratch.exchange_adj[row_start + j] = 1;
301 if i < j {
302 conflict_degrees[i] = increment_degree(conflict_degrees[i]);
303 conflict_degrees[j] = increment_degree(conflict_degrees[j]);
304 }
305 has_exchange_conflict = true;
306 }
307 }
308 }
309 }
310 if has_output_input_chain {
311 for cost in scratch.costs_q16.iter_mut() {
312 *cost = discount_q16(*cost, 3_276);
313 }
314 }
315 if !has_exchange_conflict {
316 scratch.selection.result.fill(1);
317 return scratch.selection.result();
318 }
319
320 let conflict_degrees = &scratch.selection.conflict_degrees;
321 scratch.selection.order.sort_unstable_by(|&a, &b| {
322 scratch.costs_q16[a]
323 .cmp(&scratch.costs_q16[b])
324 .then_with(|| conflict_degrees[a].cmp(&conflict_degrees[b]))
325 .then_with(|| a.cmp(&b))
326 });
327 select_ordered_maximal(
328 &scratch.exchange_adj,
329 n,
330 &scratch.selection.order,
331 &mut scratch.selection.selected,
332 &mut scratch.selection.result,
333 );
334 scratch.selection.result()
335}
336
337#[must_use]
345pub fn select_fused_subset(costs: &[f64], n: u32, exchange_adj: &[u32]) -> Vec<u32> {
346 let mut scratch = FusionSelectionScratch::default();
347 select_fused_subset_into(costs, n, exchange_adj, &mut scratch);
348 scratch.take_result()
349}
350
351pub fn select_fused_subset_into(
356 costs: &[f64],
357 n: u32,
358 exchange_adj: &[u32],
359 scratch: &mut FusionSelectionScratch,
360) {
361 if let Ok((n_usize, _cells)) = validate_selector_shape(costs.len(), n, exchange_adj.len()) {
362 if n_usize <= MAX_DENSE_FUSION_ITEMS && exchange_adj.iter().all(|&edge| edge == 0) {
363 scratch.prepare(n_usize);
364 scratch.result.fill(1);
365 return;
366 }
367 }
368 if let Err(error) = select_fused_subset_checked_into(costs, n, exchange_adj, scratch) {
373 panic!("vyre-runtime fusion subset selection failed on malformed planner input: {error}");
374 }
375}
376
377fn select_fused_subset_checked_by(
378 cost_len: usize,
379 n: u32,
380 exchange_adj: &[u32],
381 scratch: &mut FusionSelectionScratch,
382 compare_costs: impl Fn(usize, usize) -> std::cmp::Ordering,
383) -> Result<(), FusionSelectionError> {
384 let (n_usize, _cells) = validate_selector_shape(cost_len, n, exchange_adj.len())?;
385 if n_usize > MAX_DENSE_FUSION_ITEMS {
386 scratch.prepare(n_usize);
387 scratch.result.fill(1);
388 return Ok(());
389 }
390 scratch.prepare(n_usize);
391 if exchange_adj.iter().all(|&edge| edge == 0)
392 || !compute_conflict_degrees_with_conflict(
393 exchange_adj,
394 n_usize,
395 &mut scratch.conflict_degrees,
396 )
397 {
398 scratch.result.fill(1);
399 return Ok(());
400 }
401 let conflict_degrees = &scratch.conflict_degrees;
402 scratch.order.sort_unstable_by(|&a, &b| {
403 compare_costs(a, b)
404 .then_with(|| conflict_degrees[a].cmp(&conflict_degrees[b]))
405 .then_with(|| a.cmp(&b))
406 });
407 select_ordered_maximal(
408 exchange_adj,
409 n_usize,
410 &scratch.order,
411 &mut scratch.selected,
412 &mut scratch.result,
413 );
414 Ok(())
415}
416
417pub fn select_fused_subset_checked_into(
419 costs: &[f64],
420 n: u32,
421 exchange_adj: &[u32],
422 scratch: &mut FusionSelectionScratch,
423) -> Result<(), FusionSelectionError> {
424 select_fused_subset_checked_by(costs.len(), n, exchange_adj, scratch, |a, b| {
425 costs[a].total_cmp(&costs[b])
426 })
427}
428
429#[must_use]
435pub fn select_fused_subset_compact(costs_q16: &[u16], n: u32, exchange_adj: &[u32]) -> Vec<u32> {
436 let mut scratch = FusionSelectionScratch::default();
437 select_fused_subset_compact_into(costs_q16, n, exchange_adj, &mut scratch);
438 scratch.take_result()
439}
440
441pub fn select_fused_subset_compact_into(
446 costs_q16: &[u16],
447 n: u32,
448 exchange_adj: &[u32],
449 scratch: &mut FusionSelectionScratch,
450) {
451 if let Ok((n_usize, _cells)) = validate_selector_shape(costs_q16.len(), n, exchange_adj.len()) {
452 if n_usize <= MAX_DENSE_FUSION_ITEMS && exchange_adj.iter().all(|&edge| edge == 0) {
453 scratch.prepare(n_usize);
454 scratch.result.fill(1);
455 return;
456 }
457 }
458 if let Err(error) =
461 select_fused_subset_compact_checked_into(costs_q16, n, exchange_adj, scratch)
462 {
463 panic!(
464 "vyre-runtime compact fusion subset selection failed on malformed planner input: {error}"
465 );
466 }
467}
468
469pub fn select_fused_subset_compact_checked_into(
471 costs_q16: &[u16],
472 n: u32,
473 exchange_adj: &[u32],
474 scratch: &mut FusionSelectionScratch,
475) -> Result<(), FusionSelectionError> {
476 select_fused_subset_checked_by(costs_q16.len(), n, exchange_adj, scratch, |a, b| {
477 costs_q16[a].cmp(&costs_q16[b])
478 })
479}
480
481#[must_use]
484
485pub fn select_optimal_fused_subset(costs: &[f64], n: u32, exchange_adj: &[u32]) -> Vec<u32> {
486 select_fused_subset(costs, n, exchange_adj)
487}
488
489#[must_use]
491pub fn select_fused_subset_with_rate(costs: &[f64], n: u32, exchange_adj: &[u32]) -> Vec<u32> {
492 select_fused_subset(costs, n, exchange_adj)
493}
494
495#[must_use]
502pub fn select_fused_subset_pruned(
503 costs: &[f64],
504 n: u32,
505 exchange_adj: &[u32],
506 dead_mask: &[bool],
507) -> Vec<u32> {
508 let mut selection = select_fused_subset(costs, n, exchange_adj);
509 prune_dead_arms_inplace(&mut selection, dead_mask);
510 selection
511}
512
513pub fn select_fused_subset_pruned_into(
515 costs: &[f64],
516 n: u32,
517 exchange_adj: &[u32],
518 dead_mask: &[bool],
519 scratch: &mut FusionSelectionScratch,
520) {
521 select_fused_subset_into(costs, n, exchange_adj, scratch);
522 prune_dead_arms_inplace(&mut scratch.result, dead_mask);
523}
524
525pub fn prune_dead_arms_inplace(selection: &mut [u32], dead_mask: &[bool]) -> u32 {
547 if selection.len() != dead_mask.len() {
548 return 0;
549 }
550 let mut eliminated = 0_u32;
551 for (slot, &dead) in selection.iter_mut().zip(dead_mask.iter()) {
552 if dead && *slot != 0 {
553 *slot = 0;
554 eliminated = eliminated.saturating_add(1);
555 }
556 }
557 eliminated
558}
559
560fn compute_conflict_degrees_with_conflict(exchange_adj: &[u32], n: usize, out: &mut [u32]) -> bool {
561 debug_assert_eq!(out.len(), n);
562 out.fill(0);
563 let mut has_conflict = false;
564 for i in 0..n {
565 let row = i * n;
566 for j in (i + 1)..n {
567 if exchange_adj[row + j] != 0 || exchange_adj[j * n + i] != 0 {
568 out[i] = increment_degree(out[i]);
569 out[j] = increment_degree(out[j]);
570 has_conflict = true;
571 }
572 }
573 }
574 has_conflict
575}
576
577fn discount_q16(value: u16, amount: u16) -> u16 {
578 value.saturating_sub(amount)
579}
580
581fn increment_degree(value: u32) -> u32 {
582 value.saturating_add(1)
583}
584
585fn select_ordered_maximal(
586 exchange_adj: &[u32],
587 n: usize,
588 order: &[usize],
589 selected: &mut Vec<usize>,
590 result: &mut [u32],
591) {
592 result.fill(0);
593 selected.clear();
594
595 if n == 0 {
596 return;
597 }
598
599 if n <= 64 {
600 let mut conflict_masks = [0_u64; 64];
601 for i in 0..n {
602 let row = i * n;
603 let mut mask = 0_u64;
604 for j in 0..n {
605 if i == j {
606 continue;
607 }
608 if exchange_adj[row + j] != 0 || exchange_adj[j * n + i] != 0 {
609 mask |= 1_u64 << j;
610 }
611 }
612 conflict_masks[i] = mask;
613 }
614
615 let mut selected_mask = 0_u64;
616 for &item in order {
617 if item >= n {
618 continue;
619 }
620 if conflict_masks[item] & selected_mask == 0 {
621 result[item] = 1;
622 selected_mask |= 1_u64 << item;
623 selected.push(item);
624 }
625 }
626 return;
627 }
628
629 if n <= 128 {
630 let mut conflict_masks_lo = [0_u64; 128];
631 let mut conflict_masks_hi = [0_u64; 128];
632 for i in 0..n {
633 let row = i * n;
634 let mut mask_lo = 0_u64;
635 let mut mask_hi = 0_u64;
636 for j in 0..n {
637 if i == j {
638 continue;
639 }
640 if exchange_adj[row + j] != 0 || exchange_adj[j * n + i] != 0 {
641 if j < 64 {
642 mask_lo |= 1_u64 << j;
643 } else {
644 mask_hi |= 1_u64 << (j - 64);
645 }
646 }
647 }
648 conflict_masks_lo[i] = mask_lo;
649 conflict_masks_hi[i] = mask_hi;
650 }
651
652 let mut selected_lo = 0_u64;
653 let mut selected_hi = 0_u64;
654 for &item in order {
655 if item >= n {
656 continue;
657 }
658 let conflict = (conflict_masks_lo[item] & selected_lo) != 0
659 || (conflict_masks_hi[item] & selected_hi) != 0;
660 if !conflict {
661 result[item] = 1;
662 if item < 64 {
663 selected_lo |= 1_u64 << item;
664 } else {
665 selected_hi |= 1_u64 << (item - 64);
666 }
667 selected.push(item);
668 }
669 }
670 return;
671 }
672
673 if n <= 192 {
674 let mut conflict_masks_0 = [0_u64; 192];
675 let mut conflict_masks_1 = [0_u64; 192];
676 let mut conflict_masks_2 = [0_u64; 192];
677 for i in 0..n {
678 let row = i * n;
679 let mut mask_0 = 0_u64;
680 let mut mask_1 = 0_u64;
681 let mut mask_2 = 0_u64;
682 for j in 0..n {
683 if i == j {
684 continue;
685 }
686 if exchange_adj[row + j] != 0 || exchange_adj[j * n + i] != 0 {
687 match j / 64 {
688 0 => mask_0 |= 1_u64 << (j % 64),
689 1 => mask_1 |= 1_u64 << (j % 64),
690 2 => mask_2 |= 1_u64 << (j % 64),
691 _ => {}
692 }
693 }
694 }
695 conflict_masks_0[i] = mask_0;
696 conflict_masks_1[i] = mask_1;
697 conflict_masks_2[i] = mask_2;
698 }
699
700 let mut selected_0 = 0_u64;
701 let mut selected_1 = 0_u64;
702 let mut selected_2 = 0_u64;
703 for &item in order {
704 if item >= n {
705 continue;
706 }
707 let conflict = (conflict_masks_0[item] & selected_0 != 0)
708 || (conflict_masks_1[item] & selected_1 != 0)
709 || (conflict_masks_2[item] & selected_2 != 0);
710 if !conflict {
711 result[item] = 1;
712 let bit = 1_u64 << (item % 64);
713 match item / 64 {
714 0 => selected_0 |= bit,
715 1 => selected_1 |= bit,
716 2 => selected_2 |= bit,
717 _ => {}
718 }
719 selected.push(item);
720 }
721 }
722 return;
723 }
724
725 if n <= 256 {
726 let mut conflict_masks_0 = [0_u64; 256];
727 let mut conflict_masks_1 = [0_u64; 256];
728 let mut conflict_masks_2 = [0_u64; 256];
729 let mut conflict_masks_3 = [0_u64; 256];
730 for i in 0..n {
731 let row = i * n;
732 let mut mask_0 = 0_u64;
733 let mut mask_1 = 0_u64;
734 let mut mask_2 = 0_u64;
735 let mut mask_3 = 0_u64;
736 for j in 0..n {
737 if i == j {
738 continue;
739 }
740 if exchange_adj[row + j] != 0 || exchange_adj[j * n + i] != 0 {
741 match j / 64 {
742 0 => mask_0 |= 1_u64 << (j % 64),
743 1 => mask_1 |= 1_u64 << (j % 64),
744 2 => mask_2 |= 1_u64 << (j % 64),
745 _ => mask_3 |= 1_u64 << (j % 64),
746 }
747 }
748 }
749 conflict_masks_0[i] = mask_0;
750 conflict_masks_1[i] = mask_1;
751 conflict_masks_2[i] = mask_2;
752 conflict_masks_3[i] = mask_3;
753 }
754
755 let mut selected_0 = 0_u64;
756 let mut selected_1 = 0_u64;
757 let mut selected_2 = 0_u64;
758 let mut selected_3 = 0_u64;
759 for &item in order {
760 if item >= n {
761 continue;
762 }
763 let conflict = (conflict_masks_0[item] & selected_0 != 0)
764 || (conflict_masks_1[item] & selected_1 != 0)
765 || (conflict_masks_2[item] & selected_2 != 0)
766 || (conflict_masks_3[item] & selected_3 != 0);
767 if !conflict {
768 result[item] = 1;
769 let bit = 1_u64 << (item % 64);
770 match item / 64 {
771 0 => selected_0 |= bit,
772 1 => selected_1 |= bit,
773 2 => selected_2 |= bit,
774 _ => selected_3 |= bit,
775 }
776 selected.push(item);
777 }
778 }
779 return;
780 }
781
782 let chunks = n.div_ceil(64);
783 let mut conflict_masks = vec![0_u64; n * chunks];
784 for i in 0..n {
785 for j in (i + 1)..n {
786 if exchange_adj[i * n + j] != 0 || exchange_adj[j * n + i] != 0 {
787 let i_word = i / 64;
788 let i_bit = 1_u64 << (i % 64);
789 let j_word = j / 64;
790 let j_bit = 1_u64 << (j % 64);
791
792 let i_base = i * chunks;
793 let j_base = j * chunks;
794 conflict_masks[i_base + j_word] |= j_bit;
795 conflict_masks[j_base + i_word] |= i_bit;
796 }
797 }
798 }
799
800 let mut selected_mask = vec![0_u64; chunks];
801 for &item in order {
802 if item >= n {
803 continue;
804 }
805 let base = item * chunks;
806 let mut conflict = false;
807 for chunk in 0..chunks {
808 if conflict_masks[base + chunk] & selected_mask[chunk] != 0 {
809 conflict = true;
810 break;
811 }
812 }
813 if !conflict {
814 result[item] = 1;
815 selected.push(item);
816 selected_mask[item / 64] |= 1_u64 << (item % 64);
817 }
818 }
819}
820
821#[cfg(test)]
822mod tests;