1use crate::plan::backend_for_device;
52use fuel_graph::opt::execution_plan;
53use fuel_graph::{Graph, NodeId, Op, SharedGraph, opt, topo_order_multi};
54use fuel_ir::{DeviceLocation, Error, Result};
55use std::collections::HashMap;
56
57#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct LiveRange {
65 pub node: NodeId,
66 pub bytes: usize,
67 pub first_use: usize,
68 pub last_use: usize,
69 pub inactive_gap: usize,
70}
71
72#[derive(Debug, Clone)]
74pub struct ResidencyReport {
75 pub total_bytes: usize,
78 pub peak_bytes: usize,
82 pub peak_op_index: usize,
84 pub eviction_candidates: Vec<LiveRange>,
88}
89
90impl ResidencyReport {
91 pub fn fits_in(&self, budget: usize) -> bool {
93 self.peak_bytes <= budget
94 }
95
96 pub fn overage(&self, budget: usize) -> usize {
98 self.peak_bytes.saturating_sub(budget)
99 }
100}
101
102pub struct ResidencyPlanner;
107
108impl ResidencyPlanner {
109 pub fn analyze(g: &Graph, roots: &[NodeId]) -> ResidencyReport {
112 Self::analyze_ordered(g, roots, topo_order_multi(g, roots), |_| true)
113 }
114
115 pub fn analyze_on(g: &Graph, roots: &[NodeId], device: DeviceLocation) -> ResidencyReport {
122 let resident = |nid: NodeId| match &g.node(nid).op {
123 Op::Move { target } | Op::Copy { target } | Op::Alloc { target } => *target == device,
124 _ => g.placement(nid).is_none_or(|p| p == device),
127 };
128 Self::analyze_ordered(g, roots, execution_plan(g, roots), resident)
129 }
130
131 fn analyze_ordered(
132 g: &Graph,
133 roots: &[NodeId],
134 order: Vec<NodeId>,
135 resident: impl Fn(NodeId) -> bool,
136 ) -> ResidencyReport {
137 let n = order.len();
143 let mut byte_of: HashMap<NodeId, usize> = HashMap::with_capacity(n);
144 let mut first_use: HashMap<NodeId, usize> = HashMap::with_capacity(n);
145 let mut last_use: HashMap<NodeId, usize> = HashMap::with_capacity(n);
146 let mut reads_at: Vec<Vec<NodeId>> = vec![Vec::new(); n];
149
150 for (op_idx, &nid) in order.iter().enumerate() {
151 let node = g.node(nid);
152 let elems = node.shape.elem_count();
153 let bytes = if resident(nid) {
154 elems * node.dtype.size_in_bytes()
155 } else {
156 0
157 };
158 byte_of.insert(nid, bytes);
159 first_use.entry(nid).or_insert(op_idx);
160
161 for &input in &node.inputs {
162 last_use.insert(input, op_idx);
163 reads_at[op_idx].push(input);
164 }
165 }
166 for &r in roots {
169 if let Some(pos) = order.iter().position(|&x| x == r) {
170 last_use.entry(r).or_insert(pos);
171 }
172 }
173
174 let (peak_bytes, peak_op_index, total_bytes) =
175 scan_peak(&order, &byte_of, &last_use, &reads_at);
176
177 let gap_of = inactive_gaps(&first_use, &last_use, &reads_at);
178
179 let cands = rank_candidates(&order, &byte_of, &first_use, &last_use, &gap_of);
180
181 ResidencyReport {
182 total_bytes,
183 peak_bytes,
184 peak_op_index,
185 eviction_candidates: cands,
186 }
187 }
188}
189
190fn scan_peak(
193 order: &[NodeId],
194 byte_of: &HashMap<NodeId, usize>,
195 last_use: &HashMap<NodeId, usize>,
196 reads_at: &[Vec<NodeId>],
197) -> (usize, usize, usize) {
198 let mut live_bytes: usize = 0;
199 let mut peak_bytes: usize = 0;
200 let mut peak_op_index: usize = 0;
201 let mut total_bytes: usize = 0;
202 for (op_idx, &nid) in order.iter().enumerate() {
203 let bytes = *byte_of.get(&nid).unwrap_or(&0);
204 live_bytes += bytes;
205 total_bytes += bytes;
206 if live_bytes > peak_bytes {
207 peak_bytes = live_bytes;
208 peak_op_index = op_idx;
209 }
210 for &input in &reads_at[op_idx] {
212 if last_use.get(&input) == Some(&op_idx) {
213 let b = *byte_of.get(&input).unwrap_or(&0);
214 live_bytes = live_bytes.saturating_sub(b);
215 }
216 }
217 }
218 (peak_bytes, peak_op_index, total_bytes)
219}
220
221fn inactive_gaps(
224 first_use: &HashMap<NodeId, usize>,
225 last_use: &HashMap<NodeId, usize>,
226 reads_at: &[Vec<NodeId>],
227) -> HashMap<NodeId, usize> {
228 let mut gap_of: HashMap<NodeId, usize> = HashMap::with_capacity(first_use.len());
229 for (nid, &first) in first_use {
230 let mut points = vec![first];
231 points.extend(
232 reads_at
233 .iter()
234 .enumerate()
235 .filter(|(_, rs)| rs.contains(nid))
236 .map(|(i, _)| i),
237 );
238 points.push(last_use.get(nid).copied().unwrap_or(first));
239 points.sort();
240 let max_gap = points.windows(2).map(|w| w[1] - w[0]).max().unwrap_or(0);
241 gap_of.insert(*nid, max_gap);
242 }
243 gap_of
244}
245
246fn rank_candidates(
250 order: &[NodeId],
251 byte_of: &HashMap<NodeId, usize>,
252 first_use: &HashMap<NodeId, usize>,
253 last_use: &HashMap<NodeId, usize>,
254 gap_of: &HashMap<NodeId, usize>,
255) -> Vec<LiveRange> {
256 let mut cands: Vec<LiveRange> = order
257 .iter()
258 .map(|&nid| LiveRange {
259 node: nid,
260 bytes: *byte_of.get(&nid).unwrap_or(&0),
261 first_use: *first_use.get(&nid).unwrap_or(&0),
262 last_use: *last_use.get(&nid).unwrap_or(&0),
263 inactive_gap: *gap_of.get(&nid).unwrap_or(&0),
264 })
265 .collect();
266 cands.sort_by(|a, b| {
267 let a_score = (a.bytes as u128) * (a.inactive_gap as u128);
268 let b_score = (b.bytes as u128) * (b.inactive_gap as u128);
269 b_score.cmp(&a_score).then(b.bytes.cmp(&a.bytes))
270 });
271 cands.retain(|c| c.bytes > 0 && c.inactive_gap > 0);
272 cands.truncate(32);
273 cands
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub struct EvictReload {
282 pub candidate: NodeId,
283 pub move_node: NodeId,
284 pub reload: NodeId,
285 pub src_device: DeviceLocation,
286}
287
288#[derive(Debug, Clone, PartialEq)]
291#[non_exhaustive]
292pub struct EvictionOutcome {
293 pub device: DeviceLocation,
295 pub budget_bytes: usize,
297 pub peak_before: usize,
299 pub peak_after: usize,
301 pub chains: Vec<EvictReload>,
303 pub budget_source: Option<crate::device_budget::BudgetSource>,
306}
307
308impl EvictionOutcome {
309 pub fn fits(&self) -> bool {
311 self.peak_after <= self.budget_bytes
312 }
313}
314
315pub fn insert_residency_evictions(
338 graph: &SharedGraph,
339 roots: &[NodeId],
340 budget_bytes: usize,
341 max_rounds: usize,
342 placement_of: impl Fn(NodeId) -> Option<DeviceLocation>,
343) -> Result<Vec<EvictReload>> {
344 let device = roots
347 .first()
348 .and_then(|&r| placement_of(r))
349 .unwrap_or(DeviceLocation::Cpu);
350 let mut g = write_graph(graph)?;
351 Ok(insert_residency_evictions_in(
352 &mut g,
353 roots,
354 device,
355 budget_bytes,
356 max_rounds,
357 placement_of,
358 )?
359 .chains)
360}
361
362pub fn insert_residency_evictions_in(
374 g: &mut Graph,
375 roots: &[NodeId],
376 device: DeviceLocation,
377 budget_bytes: usize,
378 max_rounds: usize,
379 placement_of: impl Fn(NodeId) -> Option<DeviceLocation>,
380) -> Result<EvictionOutcome> {
381 let mut evicted: std::collections::HashSet<NodeId> = std::collections::HashSet::new();
386 let mut chains: Vec<EvictReload> = Vec::new();
387 let peak_before = ResidencyPlanner::analyze_on(g, roots, device).peak_bytes;
388 let mut peak = peak_before;
389
390 for _round in 0..max_rounds {
391 let report = ResidencyPlanner::analyze_on(g, roots, device);
392 if report.fits_in(budget_bytes) {
393 break;
394 }
395 let Some((cand, post_gap_consumers)) =
398 first_evictable(g, roots, &report.eviction_candidates, &evicted)
399 else {
400 break;
401 };
402 let src_device = placement_of(cand).unwrap_or(DeviceLocation::Cpu);
403 chains.push(evict_one(g, cand, src_device, &post_gap_consumers));
404 evicted.insert(cand);
405 let after = ResidencyPlanner::analyze_on(g, roots, device).peak_bytes;
406 let progressed = after < peak;
407 peak = after;
408 if !progressed {
409 break;
410 }
411 }
412 Ok(EvictionOutcome {
413 device,
414 budget_bytes,
415 peak_before,
416 peak_after: peak,
417 chains,
418 budget_source: None,
419 })
420}
421
422fn first_evictable(
425 g: &Graph,
426 roots: &[NodeId],
427 candidates: &[LiveRange],
428 evicted: &std::collections::HashSet<NodeId>,
429) -> Option<(NodeId, Vec<NodeId>)> {
430 candidates.iter().find_map(|c| {
431 if roots.contains(&c.node) || evicted.contains(&c.node) || already_evicted(g, c.node) {
432 return None;
433 }
434 match find_gap_consumers(g, c.node) {
435 Some((_pre_gap, post)) if !post.is_empty() => Some((c.node, post)),
436 _ => None,
437 }
438 })
439}
440
441fn evict_one(
446 g: &mut Graph,
447 candidate: NodeId,
448 src_device: DeviceLocation,
449 post_gap_consumers: &[NodeId],
450) -> EvictReload {
451 let (move_id, reload_id) =
452 opt::insert_evict_reload_in(g, candidate, src_device, post_gap_consumers);
453 g.set_target_backend(move_id, backend_for_device(src_device));
454 g.set_target_backend(reload_id, backend_for_device(DeviceLocation::Cpu));
455 g.set_placement(move_id, DeviceLocation::Cpu);
456 g.set_placement(reload_id, src_device);
457 EvictReload {
458 candidate,
459 move_node: move_id,
460 reload: reload_id,
461 src_device,
462 }
463}
464
465fn already_evicted(g: &Graph, candidate: NodeId) -> bool {
471 (0..g.len()).any(|i| {
472 let n = g.node(NodeId(i));
473 matches!(n.op, Op::Move { .. }) && n.inputs.first() == Some(&candidate)
474 })
475}
476
477fn find_gap_consumers(g: &Graph, candidate: NodeId) -> Option<(NodeId, Vec<NodeId>)> {
485 let all: Vec<NodeId> = (0..g.len()).map(NodeId).collect();
489 let order = topo_order_multi(g, &all);
490
491 let mut positions: Vec<(usize, NodeId)> = Vec::new();
493 for (i, &nid) in order.iter().enumerate() {
494 if g.node(nid).inputs.contains(&candidate) {
495 positions.push((i, nid));
496 }
497 }
498
499 if positions.len() < 2 {
500 return None;
501 }
502
503 let mut best_gap = 0usize;
505 let mut gap_idx = 0usize;
506 for i in 0..positions.len() - 1 {
507 let gap = positions[i + 1].0 - positions[i].0;
508 if gap > best_gap {
509 best_gap = gap;
510 gap_idx = i;
511 }
512 }
513
514 if best_gap < 2 {
515 return None;
516 }
517
518 let last_before = positions[gap_idx].1;
519 let after_gap: Vec<NodeId> = positions[gap_idx + 1..].iter().map(|(_, n)| *n).collect();
520
521 Some((last_before, after_gap))
522}
523
524fn write_graph(graph: &SharedGraph) -> Result<std::sync::RwLockWriteGuard<'_, Graph>> {
525 graph
526 .write()
527 .map_err(|_| Error::Msg("residency: graph RwLock poisoned".into()).bt())
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533 use crate::pipelined::{PipelinedExecutor, StorageCache};
534 use fuel_graph::Node;
535 use fuel_ir::{DType, Shape, probe::BackendId};
536 use std::sync::{Arc, RwLock};
537
538 fn shared() -> SharedGraph {
539 Arc::new(RwLock::new(Graph::new()))
540 }
541
542 fn push(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize]) -> NodeId {
543 g.push(Node {
544 op,
545 inputs,
546 shape: Shape::from_dims(dims),
547 dtype: DType::F32,
548 })
549 }
550
551 fn count_op(graph: &SharedGraph, pred: impl Fn(&Op) -> bool) -> usize {
552 let g = graph.read().unwrap();
553 (0..g.len())
554 .filter(|i| pred(&g.node(NodeId(*i)).op))
555 .count()
556 }
557
558 #[test]
564 fn chain_graph_peak_is_two_live_tensors() {
565 let graph = shared();
571 let c = {
572 let mut g = graph.write().unwrap();
573 let a = push(&mut g, Op::Const, vec![], &[1024]);
574 let b = push(&mut g, Op::Relu, vec![a], &[1024]);
575 push(&mut g, Op::Neg, vec![b], &[1024])
576 };
577 let g = graph.read().unwrap();
578 let report = ResidencyPlanner::analyze(&g, &[c]);
579 assert_eq!(report.total_bytes, 4096 * 3);
580 assert_eq!(report.peak_bytes, 4096 * 2);
581 }
582
583 #[test]
584 fn shared_const_stays_live_across_multiple_uses() {
585 let graph = shared();
589 let (a, sum) = {
590 let mut g = graph.write().unwrap();
591 let a = push(&mut g, Op::Const, vec![], &[256]);
592 let b = push(&mut g, Op::Const, vec![], &[256]);
593 let ab = push(&mut g, Op::Add, vec![a, b], &[256]);
594 let na = push(&mut g, Op::Neg, vec![a], &[256]);
595 let sum = push(&mut g, Op::Add, vec![ab, na], &[256]);
596 (a, sum)
597 };
598 let g = graph.read().unwrap();
599 let report = ResidencyPlanner::analyze(&g, &[sum]);
600 let a_range = report.eviction_candidates.iter().find(|c| c.node == a);
601 assert!(
602 a_range.is_some() || report.peak_bytes > 0,
603 "expected `a` tracked with a gap OR at least some peak bytes",
604 );
605 }
606
607 #[test]
608 fn report_fits_in_and_overage() {
609 let graph = shared();
610 let b = {
611 let mut g = graph.write().unwrap();
612 let a = push(&mut g, Op::Const, vec![], &[256]);
613 push(&mut g, Op::Relu, vec![a], &[256])
614 };
615 let g = graph.read().unwrap();
616 let report = ResidencyPlanner::analyze(&g, &[b]);
617 assert!(report.fits_in(10_000));
618 assert!(!report.fits_in(1));
619 assert_eq!(report.overage(10_000), 0);
620 assert!(report.overage(1) > 0);
621 }
622
623 fn over_budget_graph() -> (SharedGraph, NodeId, NodeId) {
636 let graph = shared();
637 let (a, out) = {
638 let mut g = graph.write().unwrap();
639 let a = push(&mut g, Op::Const, vec![], &[4]);
640 let b = push(&mut g, Op::Relu, vec![a], &[4]);
641 let pad = push(&mut g, Op::Neg, vec![b], &[4]);
642 let pad2 = push(&mut g, Op::Neg, vec![pad], &[4]);
643 let c = push(&mut g, Op::Mul, vec![pad2, a], &[4]);
644 let out = push(&mut g, Op::Add, vec![b, c], &[4]);
645 for n in [b, pad, pad2, c, out] {
646 g.set_target_backend(n, BackendId::Cpu);
647 }
648 (a, out)
649 };
650 (graph, a, out)
651 }
652
653 #[test]
654 fn eviction_is_noop_under_budget() {
655 let (graph, _a, out) = over_budget_graph();
656 let moves_before = count_op(&graph, |op| matches!(op, Op::Move { .. }));
657 let copies_before = count_op(&graph, |op| matches!(op, Op::Copy { .. }));
658
659 let chains = insert_residency_evictions(&graph, &[out], 1_000_000_000, 16, |_| None)
660 .expect("eviction pass");
661 assert!(
662 chains.is_empty(),
663 "under-budget graph should emit no chains"
664 );
665 assert_eq!(
666 count_op(&graph, |op| matches!(op, Op::Move { .. })),
667 moves_before
668 );
669 assert_eq!(
670 count_op(&graph, |op| matches!(op, Op::Copy { .. })),
671 copies_before
672 );
673 }
674
675 #[test]
676 fn eviction_emits_move_reload_chain_when_over_budget() {
677 let (graph, a, out) = over_budget_graph();
678
679 let chains =
681 insert_residency_evictions(&graph, &[out], 1, 16, |_| Some(DeviceLocation::Cpu))
682 .expect("eviction pass");
683
684 assert!(
685 !chains.is_empty(),
686 "over-budget graph should emit at least one chain"
687 );
688 assert!(
689 count_op(&graph, |op| matches!(op, Op::Move { .. })) >= 1,
690 "over-budget graph should emit at least one Op::Move",
691 );
692 assert!(
693 count_op(&graph, |op| matches!(op, Op::Copy { .. })) >= 1,
694 "each chain carries a reload Op::Copy",
695 );
696
697 let chain = chains
700 .iter()
701 .find(|c| c.candidate == a)
702 .unwrap_or(&chains[0]);
703 let g = graph.read().unwrap();
704 assert!(matches!(
705 g.node(chain.move_node).op,
706 Op::Move {
707 target: DeviceLocation::Cpu
708 },
709 ));
710 assert_eq!(g.node(chain.reload).inputs, vec![chain.move_node]);
711 assert_eq!(g.target_backend(chain.move_node), Some(BackendId::Cpu));
713 assert_eq!(g.target_backend(chain.reload), Some(BackendId::Cpu));
714 }
715
716 #[test]
720 fn analyze_on_does_not_count_the_staged_host_copy() {
721 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
722 let graph = shared();
723 let out = {
724 let mut g = graph.write().unwrap();
725 let a = push(&mut g, Op::Const, vec![], &[4]);
726 let b = push(&mut g, Op::Relu, vec![a], &[4]);
727 let staged = push(
728 &mut g,
729 Op::Move {
730 target: DeviceLocation::Cpu,
731 },
732 vec![a],
733 &[4],
734 );
735 push(&mut g, Op::Add, vec![b, staged], &[4])
736 };
737 let g = graph.read().unwrap();
738 let blind = ResidencyPlanner::analyze(&g, &[out]).peak_bytes;
739 let on = ResidencyPlanner::analyze_on(&g, &[out], cuda).peak_bytes;
740 assert!(
741 on < blind,
742 "device peak {on} must be below the blind peak {blind}"
743 );
744 let on_cpu = ResidencyPlanner::analyze_on(&g, &[out], DeviceLocation::Cpu).peak_bytes;
746 assert_eq!(on_cpu, blind);
747 }
748
749 #[test]
755 fn today_the_reload_runs_eagerly_so_the_device_peak_does_not_drop() {
756 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
757 let (graph, _a, out) = over_budget_graph();
758 let before = ResidencyPlanner::analyze_on(&graph.read().unwrap(), &[out], cuda).peak_bytes;
759 let chains = insert_residency_evictions(&graph, &[out], before - 1, 16, |_| Some(cuda))
760 .expect("eviction pass");
761 assert!(!chains.is_empty(), "a budget below the peak must evict");
762 let g = graph.read().unwrap();
763 let order = fuel_graph::opt::execution_plan(&g, &[out]);
764 let pos = |n: NodeId| order.iter().position(|&x| x == n).unwrap();
765 let c = &chains[0];
766 assert_eq!(
767 pos(c.reload),
768 pos(c.move_node) + 1,
769 "the reload follows its Move immediately in the executor's order"
770 );
771 let after = ResidencyPlanner::analyze_on(&g, &[out], cuda).peak_bytes;
772 assert_eq!(after, before, "so the analysed peak is unchanged");
773 }
774
775 #[test]
779 fn a_candidate_is_evicted_at_most_once_across_runs() {
780 let (graph, _a, out) = over_budget_graph();
781 let first = insert_residency_evictions(&graph, &[out], 0, 16, |_| None).expect("run 1");
782 assert!(!first.is_empty());
783 let second = insert_residency_evictions(&graph, &[out], 0, 16, |_| None).expect("run 2");
784 let evicted_before: Vec<NodeId> = first.iter().map(|c| c.candidate).collect();
785 assert!(
786 second
787 .iter()
788 .all(|c| !evicted_before.contains(&c.candidate)),
789 "run 2 re-evicted a candidate of run 1"
790 );
791 let g = graph.read().unwrap();
793 let _ = fuel_graph::opt::execution_plan(&g, &[out]);
794 }
795
796 #[test]
802 fn eviction_preserves_correctness_end_to_end_on_pipelined() {
803 let realize = |evict: bool| -> Vec<f32> {
810 let (graph, a, out) = over_budget_graph();
811 if evict {
812 let chains = insert_residency_evictions(&graph, &[out], 1, 16, |_| {
813 Some(DeviceLocation::Cpu)
814 })
815 .expect("eviction pass");
816 assert!(!chains.is_empty(), "budget=1 must trigger eviction");
817 }
818 let mut inputs = StorageCache::new();
819 inputs.insert(
820 a,
821 Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
822 -1.0_f32, 2.0, -3.0, 4.0,
823 ]))),
824 );
825 let (storage, _layout) =
826 PipelinedExecutor::realize(graph, out, inputs).expect("realize");
827 let guard = storage.read().unwrap();
828 let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
829 panic!("expected CPU output");
830 };
831 c.as_slice::<f32>().unwrap().to_vec()
832 };
833
834 let baseline = realize(false);
835 let evicted = realize(true);
836 assert_eq!(
837 baseline, evicted,
838 "eviction must preserve the output bit-exactly",
839 );
840 assert_eq!(baseline, vec![0.0_f32, 6.0, 0.0, 20.0]);
841 }
842
843 #[test]
847 fn a_realize_root_is_never_evicted() {
848 let (graph, a, out) = over_budget_graph();
849 let chains =
850 insert_residency_evictions(&graph, &[a, out], 1, 16, |_| Some(DeviceLocation::Cpu))
851 .expect("eviction pass");
852 assert!(
853 chains.iter().all(|c| c.candidate != a),
854 "the root `a` was evicted: {chains:?}"
855 );
856 let (graph, a, out) = over_budget_graph();
859 let chains =
860 insert_residency_evictions(&graph, &[out], 1, 16, |_| Some(DeviceLocation::Cpu))
861 .expect("eviction pass");
862 assert!(
863 chains.iter().any(|c| c.candidate == a),
864 "control: without the root exclusion `a` is evicted"
865 );
866 }
867
868 #[test]
872 fn a_round_that_does_not_lower_the_peak_stops_and_is_reported() {
873 let cuda = DeviceLocation::Cuda { gpu_id: 0 };
874 let (graph, _a, out) = over_budget_graph();
875 let mut g = graph.write().unwrap();
876 let before = ResidencyPlanner::analyze_on(&g, &[out], cuda).peak_bytes;
877 let outcome =
878 insert_residency_evictions_in(&mut g, &[out], cuda, before - 1, 16, |_| Some(cuda))
879 .expect("eviction pass");
880 assert_eq!(outcome.peak_before, before);
881 assert_eq!(
882 outcome.chains.len(),
883 1,
884 "a stalled pass must stop after the round that showed the stall, not run to max_rounds"
885 );
886 assert!(outcome.peak_after >= outcome.peak_before);
887 assert!(
888 !outcome.fits(),
889 "the budget was NOT met and the outcome must say so"
890 );
891 let ok =
893 insert_residency_evictions_in(&mut g, &[out], cuda, usize::MAX, 16, |_| Some(cuda))
894 .expect("eviction pass");
895 assert!(ok.fits() && ok.chains.is_empty());
896 }
897
898 #[test]
901 fn a_candidate_read_twice_by_one_consumer_is_rewired_in_both_slots() {
902 let graph = shared();
905 let (a, pad2, late) = {
906 let mut g = graph.write().unwrap();
907 let a = push(&mut g, Op::Const, vec![], &[4]);
908 let early = push(&mut g, Op::Relu, vec![a], &[4]);
909 let pad = push(&mut g, Op::Neg, vec![early], &[4]);
910 let pad2 = push(&mut g, Op::Neg, vec![pad], &[4]);
911 let late = push(&mut g, Op::Where, vec![pad2, a, a], &[4]);
912 for n in [early, pad, pad2, late] {
913 g.set_target_backend(n, BackendId::Cpu);
914 }
915 (a, pad2, late)
916 };
917 let chains =
918 insert_residency_evictions(&graph, &[late], 1, 4, |_| Some(DeviceLocation::Cpu))
919 .expect("eviction pass");
920 let chain = chains
921 .iter()
922 .find(|c| c.candidate == a)
923 .expect("`a` is evicted");
924 let g = graph.read().unwrap();
925 assert_eq!(
926 g.node(late).inputs,
927 vec![pad2, chain.reload, chain.reload],
928 "both slots that read `a` must read the reload"
929 );
930 }
931
932 #[test]
938 fn eviction_terminates_when_budget_unreachable() {
939 let (graph, _a, out) = over_budget_graph();
940 let chains =
941 insert_residency_evictions(&graph, &[out], 0, 16, |_| None).expect("eviction pass");
942 let len_after = graph.read().unwrap().len();
943 let chains2 = insert_residency_evictions(&graph, &[out], 0, 16, |_| None)
946 .expect("second eviction pass");
947 let len_final = graph.read().unwrap().len();
948 assert!(chains.len() <= 16);
949 assert!(chains2.len() <= 16);
954 assert!(len_final >= len_after);
955 assert!(len_final - len_after <= 2 * chains2.len());
956 }
957}