1use crate::accelerator::ExecutionBackend;
10use crate::cluster::ClusterState;
11use crate::host::{AccelerationMode, RuntimeProfile};
12use crate::system_profile::SystemProfile;
13use crate::watcher::ProfileChange;
14use std::sync::Arc;
15
16#[derive(Clone, Copy, Debug)]
18pub struct LoadBalanceConfig {
19 pub lock_timeout_us: u64,
21 pub min_load_threshold: f32,
23 pub max_layers_per_assignment: usize,
25 pub max_concurrent_rebalances: usize,
27}
28
29impl Default for LoadBalanceConfig {
30 fn default() -> Self {
31 Self {
32 lock_timeout_us: 1000, min_load_threshold: 1.25,
34 max_layers_per_assignment: 100,
35 max_concurrent_rebalances: 1,
36 }
37 }
38}
39
40impl LoadBalanceConfig {
41 pub fn autotuned(profile: &RuntimeProfile) -> Self {
43 let base_timeout = match profile.acceleration_mode {
44 AccelerationMode::Gpu => 500,
45 AccelerationMode::Avx512 => 750,
46 _ => 1000,
47 };
48 let min_load_threshold = match profile.acceleration_mode {
54 AccelerationMode::Gpu => 1.15,
55 AccelerationMode::Avx512 => 1.05,
56 _ => 1.02,
57 };
58 let max_layers_per_assignment = profile.recommended_workers.max(1) * 2;
59
60 Self {
61 lock_timeout_us: base_timeout,
62 min_load_threshold,
63 max_layers_per_assignment,
64 max_concurrent_rebalances: profile.recommended_workers.clamp(1, 8),
65 }
66 }
67}
68
69#[derive(Clone, Debug)]
71pub struct TensorSlice {
72 pub layer_range: (usize, usize), pub size_gb: f32,
76 pub num_weights: u32,
78}
79
80impl TensorSlice {
81 pub fn new(layer_range: (usize, usize), size_gb: f32) -> Self {
83 Self {
84 layer_range,
85 size_gb,
86 num_weights: 0,
87 }
88 }
89}
90
91#[derive(Clone, Debug)]
93pub struct LoadDistributionPlan {
94 pub distributions: Vec<(String, Vec<TensorSlice>)>,
96 pub total_layers: usize,
98 pub participating_nodes: Vec<String>,
100}
101
102impl LoadDistributionPlan {
103 pub fn new(distributions: Vec<(String, Vec<TensorSlice>)>, total_layers: usize) -> Self {
105 let participating_nodes = distributions
106 .iter()
107 .map(|(node_id, _)| node_id.clone())
108 .collect();
109
110 Self {
111 distributions,
112 total_layers,
113 participating_nodes,
114 }
115 }
116
117 pub fn summary(&self) -> String {
119 let mut output = String::from("Load Distribution Plan\n");
120 output.push_str("======================\n\n");
121
122 for (node_id, slices) in &self.distributions {
123 output.push_str(&format!("Node: {node_id}\n"));
124
125 let total_size_gb: f32 = slices.iter().map(|s| s.size_gb).sum();
126
127 output.push_str(&format!(" Total size: {total_size_gb:.1} GB\n"));
128 output.push_str(&format!(
129 " Layers: {}-{}\n",
130 slices.first().map(|s| s.layer_range.0).unwrap_or(0),
131 slices.last().map(|s| s.layer_range.1).unwrap_or(0)
132 ));
133 output.push('\n');
134 }
135
136 output.push_str(&format!("Total layers: {}\n", self.total_layers));
137 output.push_str(&format!("Nodes: {}\n", self.participating_nodes.join(", ")));
138
139 output
140 }
141}
142
143#[derive(Clone, Debug)]
145pub struct LoadBalancer {
146 cluster: Arc<ClusterState>,
148 config: Arc<std::sync::Mutex<LoadBalanceConfig>>,
150}
151
152impl LoadBalancer {
153 pub fn new(cluster: Arc<ClusterState>, config: LoadBalanceConfig) -> Self {
155 Self {
156 cluster,
157 config: Arc::new(std::sync::Mutex::new(config)),
158 }
159 }
160
161 pub fn with_runtime_profile(cluster: Arc<ClusterState>, profile: &RuntimeProfile) -> Self {
163 Self::new(cluster, LoadBalanceConfig::autotuned(profile))
164 }
165
166 pub fn config(&self) -> LoadBalanceConfig {
168 self.config
169 .lock()
170 .ok()
171 .as_deref()
172 .copied()
173 .unwrap_or_default()
174 }
175
176 pub fn distribute_layers(
183 &self,
184 layers: &[crate::planning::LayerSpec],
185 ) -> Result<LoadDistributionPlan, String> {
186 self.distribute_layers_internal(layers, None)
187 }
188
189 fn distribute_layers_internal(
190 &self,
191 layers: &[crate::planning::LayerSpec],
192 max_layers_per_slice: Option<usize>,
193 ) -> Result<LoadDistributionPlan, String> {
194 let nodes_snapshot = self.cluster.nodes_snapshot();
195 if nodes_snapshot.is_empty() {
196 return Err("no nodes available".into());
197 }
198
199 let mut sorted_nodes: Vec<&crate::protocol::NodeResources> =
201 nodes_snapshot.iter().collect();
202 sorted_nodes.sort_by(|a, b| {
203 b.vram_gb
204 .partial_cmp(&a.vram_gb)
205 .unwrap_or(std::cmp::Ordering::Equal)
206 });
207
208 let is_sorted = layers.windows(2).all(|w| w[0].index <= w[1].index);
211 let sorted_layers: std::borrow::Cow<'_, [crate::planning::LayerSpec]> = if is_sorted {
212 std::borrow::Cow::Borrowed(layers)
213 } else {
214 let mut all_layers = layers.to_vec();
215 all_layers.sort_by_key(|l| l.index);
216 std::borrow::Cow::Owned(all_layers)
217 };
218 let total_layer_count = sorted_layers.len();
219
220 let mut distributions = Vec::with_capacity(sorted_nodes.len());
222 let mut participating_nodes = Vec::with_capacity(sorted_nodes.len());
223 let mut current_layer_idx = 0usize;
224 let slice_limit = max_layers_per_slice.unwrap_or(usize::MAX).max(1);
225
226 for node in &sorted_nodes {
227 if current_layer_idx >= sorted_layers.len() {
228 break;
229 }
230
231 let mut used_vram = 0.0f32;
232 let start_idx = current_layer_idx;
233 let mut end_idx = current_layer_idx;
234
235 for layer in &sorted_layers[current_layer_idx..] {
236 if used_vram + layer.vram_gb > node.vram_gb {
237 break;
238 }
239 end_idx += 1;
240 used_vram += layer.vram_gb;
241 }
242
243 if end_idx > start_idx {
244 let total_node_layers = end_idx - start_idx;
245 let node_id = node.id.clone();
246 participating_nodes.push(node_id.clone());
247
248 if total_node_layers <= slice_limit {
249 let start_layer = sorted_layers[start_idx].index;
250 let end_layer = sorted_layers[end_idx - 1].index + 1;
251 let slice = TensorSlice::new((start_layer, end_layer), used_vram);
252 distributions.push((node_id, vec![slice]));
253 } else {
254 let chunks_count = total_node_layers.div_ceil(slice_limit);
255 let mut slices = Vec::with_capacity(chunks_count);
256 let avg_size = used_vram / total_node_layers as f32;
257
258 let mut chunk_start_idx = start_idx;
259 while chunk_start_idx < end_idx {
260 let chunk_end_idx = (chunk_start_idx + slice_limit).min(end_idx);
261 let chunk_layers = chunk_end_idx - chunk_start_idx;
262 let start_layer = sorted_layers[chunk_start_idx].index;
263 let end_layer = sorted_layers[chunk_end_idx - 1].index + 1;
264 slices.push(TensorSlice::new(
265 (start_layer, end_layer),
266 avg_size * chunk_layers as f32,
267 ));
268 chunk_start_idx = chunk_end_idx;
269 }
270 distributions.push((node_id, slices));
271 }
272
273 current_layer_idx = end_idx;
274 }
275 }
276
277 if current_layer_idx >= sorted_layers.len() {
278 Ok(LoadDistributionPlan {
279 distributions,
280 total_layers: total_layer_count,
281 participating_nodes,
282 })
283 } else {
284 Err(format!(
285 "insufficient VRAM: {} layers remain",
286 sorted_layers.len() - current_layer_idx
287 ))
288 }
289 }
290
291 pub fn distribute_layers_with_runtime_profile(
298 &self,
299 layers: &[crate::planning::LayerSpec],
300 profile: &RuntimeProfile,
301 ) -> Result<LoadDistributionPlan, String> {
302 let cfg = self.config();
303 let backend = ExecutionBackend::from_runtime_profile(profile);
304 let vector_bias = (backend.vector_width_bits / 128).max(1);
305 let max_layers_per_slice = cfg
306 .max_layers_per_assignment
307 .min(profile.recommended_workers.max(1).saturating_mul(2))
308 .min(backend.preferred_batch_size / vector_bias)
309 .max(1);
310
311 self.distribute_layers_internal(layers, Some(max_layers_per_slice))
312 }
313
314 pub fn rebalance(&self) -> bool {
316 let cfg = self.config();
317
318 let (min_available, max_available, has_nodes) = {
319 let metrics = self
320 .cluster
321 .metrics
322 .lock()
323 .unwrap_or_else(|poison| poison.into_inner());
324
325 let mut min_val = f32::MAX;
326 let mut max_val = 0.0_f32;
327 let mut count = 0usize;
328
329 for node in metrics.values() {
330 if node.status == crate::cluster::NodeStatus::Active {
331 min_val = min_val.min(node.available_vram_gb.max(0.0));
332 max_val = max_val.max(node.available_vram_gb.max(0.0));
333 count += 1;
334 }
335 }
336 (min_val, max_val, count > 0)
337 };
338
339 if !has_nodes {
340 return false;
341 }
342
343 let skew_ratio = if min_available <= f32::EPSILON {
345 if max_available > 0.0 {
346 f32::INFINITY
347 } else {
348 1.0
349 }
350 } else {
351 max_available / min_available
352 };
353
354 if skew_ratio >= cfg.min_load_threshold {
355 tracing::info!(
356 "Detected load skew ratio {:.2} (threshold {:.2})",
357 skew_ratio,
358 cfg.min_load_threshold
359 );
360 return true;
361 }
362
363 false
364 }
365
366 pub fn shed_load(&self) -> Vec<(String, String)> {
372 let cfg = self.config();
373 let mut transfers: Vec<(String, String)> = Vec::new();
374
375 let metrics = self
376 .cluster
377 .metrics
378 .lock()
379 .unwrap_or_else(|poison| poison.into_inner());
380
381 let mut overloaded_nodes: Vec<&String> = Vec::new();
382 let mut underloaded_nodes: Vec<(&String, f32)> = Vec::new();
383
384 for m in metrics.values() {
385 if m.status == crate::cluster::NodeStatus::Active {
386 if m.available_vram_gb < m.total_vram_gb * 0.2 {
387 overloaded_nodes.push(&m.name);
388 } else if m.available_vram_gb > m.total_vram_gb * 0.5 {
389 underloaded_nodes.push((&m.name, m.available_vram_gb));
390 }
391 }
392 }
393
394 for &overloaded_name in &overloaded_nodes {
395 if transfers.len() >= cfg.max_concurrent_rebalances {
396 break;
397 }
398
399 let mut best_target: Option<&String> = None;
400 let mut max_available = 0.0f32;
401
402 for &(name, available) in &underloaded_nodes {
403 if name != overloaded_name && available > max_available {
404 max_available = available;
405 best_target = Some(name);
406 }
407 }
408
409 if let Some(target_name) = best_target {
410 transfers.push((overloaded_name.clone(), target_name.clone()));
411 }
412 }
413
414 transfers
415 }
416
417 pub fn reconfigure_from_system_profile(&self, profile: &SystemProfile) {
423 let rp: RuntimeProfile = profile.into();
424 if let Ok(mut guard) = self.config.lock() {
425 *guard = LoadBalanceConfig::autotuned(&rp);
426 }
427 }
428
429 pub fn subscribe_to_watcher(
434 self: &Arc<Self>,
435 watcher: &crate::watcher::SystemProfileWatcher,
436 ) -> tokio::task::JoinHandle<()> {
437 let this = self.clone();
438 let mut rx = watcher.subscribe();
439 tokio::spawn(async move {
440 while let Ok(event) = rx.recv().await {
441 if let ProfileChange::Updated(profile) = event {
442 this.reconfigure_from_system_profile(&profile);
443 tracing::info!(
444 "load balancer re-tuned from profile: {} workers, {:?} accel",
445 profile.recommended_workers,
446 profile.acceleration_mode,
447 );
448 }
449 }
450 })
451 }
452
453 pub fn distribute_with_deadlock_prevention(
455 &self,
456 layers: &[crate::planning::LayerSpec],
457 ) -> Result<LoadDistributionPlan, String> {
458 let cfg = self.config();
459 let start_time = std::time::Instant::now();
461
462 while start_time.elapsed().as_micros() < cfg.lock_timeout_us as u128 {
463 match self.distribute_layers(layers) {
464 Ok(plan) => return Ok(plan),
465 Err(_) => {
466 std::thread::sleep(std::time::Duration::from_millis(10));
468 }
469 }
470 }
471
472 Err("deadlock prevention timeout".into())
473 }
474}
475
476pub fn chunk_distribution_plan(
478 plan: LoadDistributionPlan,
479 max_layers_per_slice: usize,
480) -> LoadDistributionPlan {
481 let slice_limit = max_layers_per_slice.max(1);
482
483 let needs_chunking = plan.distributions.iter().any(|(_, slices)| {
485 slices
486 .iter()
487 .any(|s| s.layer_range.1.saturating_sub(s.layer_range.0) > slice_limit)
488 });
489 if !needs_chunking {
490 return plan;
491 }
492
493 let distributions = plan
494 .distributions
495 .into_iter()
496 .map(|(node_id, slices)| {
497 let estimated_chunks = slices
498 .iter()
499 .map(|slice| {
500 let total_layers = slice.layer_range.1.saturating_sub(slice.layer_range.0);
501 total_layers.div_ceil(slice_limit).max(1)
502 })
503 .sum();
504 let mut chunked = Vec::with_capacity(estimated_chunks);
505 for slice in slices {
506 let total_layers = slice.layer_range.1.saturating_sub(slice.layer_range.0);
507 if total_layers <= slice_limit {
508 chunked.push(slice);
509 continue;
510 }
511
512 let avg_size = if total_layers == 0 {
513 0.0
514 } else {
515 slice.size_gb / total_layers as f32
516 };
517 let mut start = slice.layer_range.0;
518 while start < slice.layer_range.1 {
519 let end = (start + slice_limit).min(slice.layer_range.1);
520 let layers_in_chunk = end - start;
521 let mut chunk =
522 TensorSlice::new((start, end), avg_size * layers_in_chunk as f32);
523 chunk.num_weights = slice.num_weights;
524 chunked.push(chunk);
525 start = end;
526 }
527 }
528 (node_id, chunked)
529 })
530 .collect();
531
532 LoadDistributionPlan {
534 distributions,
535 total_layers: plan.total_layers,
536 participating_nodes: plan.participating_nodes,
537 }
538}
539
540#[derive(Clone, Debug, Default)]
542pub struct LoadStats {
543 pub total_layers_distributed: usize,
545 pub total_vram_used_gb: f32,
547 pub avg_load_balance_ratio: f32,
549 pub rebalancing_count: usize,
551 balance_ratio_initialized: bool,
553}
554
555impl LoadStats {
556 pub fn new() -> Self {
558 Self::default()
559 }
560
561 pub fn record_distribution(&mut self, num_layers: usize, vram_gb: f32) {
563 self.total_layers_distributed += num_layers;
564 self.total_vram_used_gb += vram_gb;
565 }
566
567 pub fn update_balance_ratio(&mut self, ratio: f32) {
569 if !self.balance_ratio_initialized {
570 self.avg_load_balance_ratio = ratio;
572 self.balance_ratio_initialized = true;
573 } else {
574 self.avg_load_balance_ratio = self.avg_load_balance_ratio * 0.9 + ratio * 0.1;
576 }
577 }
578
579 pub fn record_rebalancing(&mut self) {
581 self.rebalancing_count += 1;
582 }
583
584 pub fn report(&self) -> String {
586 format!(
587 "Load Statistics\n\
588 ==========\n\
589 Total layers distributed: {}\n\
590 Total VRAM used: {:.1} GB\n\
591 Avg load balance ratio: {:.2}\n\
592 Rebalancing operations: {}",
593 self.total_layers_distributed,
594 self.total_vram_used_gb,
595 self.avg_load_balance_ratio,
596 self.rebalancing_count
597 )
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604 use crate::cluster::ClusterState;
605 use crate::host::AccelerationMode;
606 use crate::protocol::NodeResources;
607 use std::sync::Arc;
608
609 fn sample_layers(count: usize, vram_gb: f32) -> Vec<crate::planning::LayerSpec> {
610 (0..count)
611 .map(|index| crate::planning::LayerSpec {
612 index,
613 vram_gb,
614 num_weights: 0,
615 })
616 .collect()
617 }
618
619 fn sample_nodes(count: usize, base_vram: f32) -> Vec<NodeResources> {
620 (0..count)
621 .map(|i| {
622 NodeResources::new(
623 format!("node-{i}"),
624 base_vram + (i as f32 * 6.0),
625 64.0,
626 "8.9".to_string(),
627 None,
628 )
629 })
630 .collect()
631 }
632
633 #[test]
634 fn load_balancer_distributes_layers() {
635 let cluster = ClusterState::new();
636 for node in sample_nodes(2, 24.0) {
637 cluster.register(node);
638 }
639
640 let layers = sample_layers(33, 1.0);
641 let balancer = LoadBalancer::new(Arc::new(cluster), LoadBalanceConfig::default());
642
643 let plan = balancer.distribute_layers(&layers).unwrap();
644 assert_eq!(plan.total_layers, 33);
645 }
646
647 #[test]
648 fn load_balancer_generates_summary() {
649 let cluster = ClusterState::new();
650 for node in sample_nodes(2, 24.0) {
651 cluster.register(node);
652 }
653
654 let layers = sample_layers(33, 1.0);
655 let balancer = LoadBalancer::new(Arc::new(cluster), LoadBalanceConfig::default());
656
657 let plan = balancer.distribute_layers(&layers).unwrap();
658 let summary = plan.summary();
659
660 assert!(summary.contains("Total layers: 33"));
661 }
662
663 #[test]
664 fn load_stats_records_distribution() {
665 let mut stats = LoadStats::new();
666
667 stats.record_distribution(24, 24.0);
668 stats.record_distribution(9, 9.0);
669
670 assert_eq!(stats.total_layers_distributed, 33);
671 assert!((stats.total_vram_used_gb - 33.0).abs() < 0.01);
672 }
673
674 #[test]
675 fn load_stats_updates_balance_ratio() {
676 let mut stats = LoadStats::new();
677
678 stats.update_balance_ratio(0.95);
679 assert!((stats.avg_load_balance_ratio - 0.95).abs() < 1e-6);
680
681 stats.update_balance_ratio(0.85);
682 assert!((stats.avg_load_balance_ratio - 0.94).abs() < 1e-6);
684 }
685
686 #[test]
687 fn load_stats_first_balance_ratio_not_diluted_by_prior_distribution() {
688 let mut stats = LoadStats::new();
696
697 stats.record_distribution(24, 24.0);
698 stats.update_balance_ratio(0.95);
699
700 assert!(
701 (stats.avg_load_balance_ratio - 0.95).abs() < 1e-6,
702 "first balance ratio sample must be set directly, got {}",
703 stats.avg_load_balance_ratio
704 );
705 }
706
707 #[test]
708 fn load_stats_reports() {
709 let mut stats = LoadStats::new();
710
711 stats.record_distribution(24, 24.0);
712 stats.update_balance_ratio(0.95);
713
714 let report = stats.report();
715 assert!(report.contains("Total layers distributed: 24"));
716 }
717
718 #[test]
719 fn autotuned_config_reflects_runtime_profile() {
720 let profile = RuntimeProfile {
721 node_resources: NodeResources::new("node-a", 24.0, 64.0, "8.9", None),
722 logical_cores: 16,
723 recommended_workers: 6,
724 acceleration_mode: AccelerationMode::Gpu,
725 gpu_backend: crate::host::GpuBackend::Cuda,
726 xdp_supported: true,
727 detection_source: String::from("test"),
728 probe_mode: crate::host::ProbeMode::Fast,
729 };
730
731 let config = LoadBalanceConfig::autotuned(&profile);
732 assert_eq!(config.lock_timeout_us, 500);
733 assert_eq!(config.max_layers_per_assignment, 12);
734 assert_eq!(config.max_concurrent_rebalances, 6);
735 assert!(config.min_load_threshold > 1.0);
736 }
737
738 #[test]
739 fn autotuned_cpu_threshold_stays_above_one() {
740 let profile = RuntimeProfile {
744 node_resources: NodeResources::new("node-a", 0.0, 16.0, "generic", None),
745 logical_cores: 4,
746 recommended_workers: 2,
747 acceleration_mode: AccelerationMode::Generic,
748 gpu_backend: crate::host::GpuBackend::Cpu,
749 xdp_supported: false,
750 detection_source: String::from("test"),
751 probe_mode: crate::host::ProbeMode::Fast,
752 };
753 let config = LoadBalanceConfig::autotuned(&profile);
754 assert!(
755 config.min_load_threshold > 1.0,
756 "CPU-tier threshold {} must exceed skew_ratio's mathematical floor of 1.0",
757 config.min_load_threshold
758 );
759 }
760
761 #[test]
762 fn rebalance_does_not_always_trigger_on_balanced_cpu_cluster() {
763 let cluster = Arc::new(ClusterState::new());
764 cluster.register(NodeResources::new("node-a", 0.0, 16.0, "generic", None));
765 cluster.register(NodeResources::new("node-b", 0.0, 16.0, "generic", None));
766
767 let profile = RuntimeProfile {
768 node_resources: NodeResources::new("node-a", 0.0, 16.0, "generic", None),
769 logical_cores: 4,
770 recommended_workers: 2,
771 acceleration_mode: AccelerationMode::Generic,
772 gpu_backend: crate::host::GpuBackend::Cpu,
773 xdp_supported: false,
774 detection_source: String::from("test"),
775 probe_mode: crate::host::ProbeMode::Fast,
776 };
777 let balancer = LoadBalancer::new(cluster, LoadBalanceConfig::autotuned(&profile));
778 assert!(
779 !balancer.rebalance(),
780 "a perfectly balanced (zero-VRAM) CPU cluster must not be reported as needing rebalance"
781 );
782 }
783
784 #[test]
785 fn runtime_profile_chunks_large_distribution_slices() {
786 let plan = LoadDistributionPlan::new(
787 vec![("node-a".into(), vec![TensorSlice::new((0, 10), 10.0)])],
788 10,
789 );
790
791 let chunked = chunk_distribution_plan(plan, 4);
792 assert_eq!(chunked.distributions[0].1.len(), 3);
793 assert_eq!(chunked.distributions[0].1[0].layer_range, (0, 4));
794 assert_eq!(chunked.distributions[0].1[2].layer_range, (8, 10));
795 }
796
797 #[test]
798 fn shed_load_moves_from_low_headroom_to_high_headroom_nodes() {
799 let cluster = ClusterState::new();
800 cluster.register(NodeResources::new("node-hot", 24.0, 64.0, "8.9", None));
801 cluster.register(NodeResources::new("node-cool", 24.0, 64.0, "8.9", None));
802
803 cluster.get_metrics_mut("node-hot", |m| {
805 m.available_vram_gb = 2.0;
806 m.total_vram_gb = 24.0;
807 });
808
809 cluster.get_metrics_mut("node-cool", |m| {
811 m.available_vram_gb = 20.0;
812 m.total_vram_gb = 24.0;
813 });
814
815 let balancer = LoadBalancer::new(Arc::new(cluster), LoadBalanceConfig::default());
816 let transfers = balancer.shed_load();
817
818 assert_eq!(transfers.len(), 1);
819 assert_eq!(transfers[0].0, "node-hot");
820 assert_eq!(transfers[0].1, "node-cool");
821 }
822}