axonml-distributed 0.4.2

Distributed training utilities for the Axonml ML framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! FSDP - Fully Sharded Data Parallel
//!
//! # File
//! `crates/axonml-distributed/src/fsdp.rs`
//!
//! # Author
//! Andrew Jewell Sr - AutomataNexus
//!
//! # Updated
//! March 8, 2026
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

use crate::backend::ReduceOp;
use crate::process_group::ProcessGroup;
use axonml_autograd::Variable;
use axonml_nn::{Module, Parameter};
use axonml_tensor::Tensor;

// =============================================================================
// Sharding Strategy
// =============================================================================

/// Strategy for sharding parameters in FSDP.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ShardingStrategy {
    /// Shard parameters, gradients, and optimizer state (ZeRO-3)
    #[default]
    FullShard,
    /// Shard gradients and optimizer state only (ZeRO-2)
    ShardGradOp,
    /// No sharding, replicate across ranks (DDP-like)
    NoShard,
    /// Hybrid sharding within node, replicate across nodes
    HybridShard,
}

// =============================================================================
// FSDP State
// =============================================================================

/// State for a sharded parameter.
#[derive(Debug)]
#[allow(dead_code)]
struct ShardedParam {
    /// Local shard of the parameter
    local_shard: Tensor<f32>,
    /// Original shape before sharding
    original_shape: Vec<usize>,
    /// Number of elements in original parameter
    numel: usize,
    /// Padding added for even sharding (for uneven divisions)
    padding: usize,
}

/// CPU offload configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CPUOffload {
    /// No CPU offloading
    #[default]
    None,
    /// Offload parameters to CPU when not in use
    Params,
    /// Offload both parameters and gradients
    Full,
}

// =============================================================================
// Fully Sharded Data Parallel
// =============================================================================

/// Fully Sharded Data Parallel wrapper for memory-efficient distributed training.
///
/// FSDP shards model parameters across devices, gathering them only when needed
/// for computation and sharding them again afterward.
pub struct FullyShardedDataParallel<M: Module> {
    /// Wrapped module
    module: M,
    /// Process group for communication
    process_group: ProcessGroup,
    /// Sharding strategy
    sharding_strategy: ShardingStrategy,
    /// CPU offload configuration
    cpu_offload: CPUOffload,
    /// Sharded parameter states
    sharded_params: Vec<ShardedParam>,
    /// Whether module is currently gathered (unsharded)
    is_gathered: bool,
    /// Mixed precision compute dtype
    mixed_precision: bool,
}

impl<M: Module> FullyShardedDataParallel<M> {
    /// Creates a new FSDP wrapper.
    pub fn new(module: M, process_group: ProcessGroup) -> Self {
        let mut fsdp = Self {
            module,
            process_group,
            sharding_strategy: ShardingStrategy::default(),
            cpu_offload: CPUOffload::default(),
            sharded_params: Vec::new(),
            is_gathered: true,
            mixed_precision: false,
        };

        // Initialize sharding
        fsdp.shard_parameters();
        fsdp
    }

    /// Builder: set sharding strategy.
    pub fn sharding_strategy(mut self, strategy: ShardingStrategy) -> Self {
        self.sharding_strategy = strategy;
        self.shard_parameters();
        self
    }

    /// Builder: set CPU offload configuration.
    pub fn cpu_offload(mut self, offload: CPUOffload) -> Self {
        self.cpu_offload = offload;
        self
    }

    /// Builder: enable mixed precision.
    pub fn mixed_precision(mut self, enabled: bool) -> Self {
        self.mixed_precision = enabled;
        self
    }

    /// Returns reference to wrapped module.
    pub fn module(&self) -> &M {
        &self.module
    }

    /// Returns mutable reference to wrapped module.
    pub fn module_mut(&mut self) -> &mut M {
        &mut self.module
    }

    /// Returns the process group.
    pub fn process_group(&self) -> &ProcessGroup {
        &self.process_group
    }

    /// Returns the sharding strategy.
    pub fn strategy(&self) -> ShardingStrategy {
        self.sharding_strategy
    }

    /// Shards parameters across devices.
    fn shard_parameters(&mut self) {
        if self.sharding_strategy == ShardingStrategy::NoShard {
            return;
        }

        let world_size = self.process_group.world_size();
        let rank = self.process_group.rank();

        self.sharded_params.clear();

        for param in self.module.parameters() {
            let data = param.data();
            let shape = data.shape().to_vec();
            let numel = data.numel();

            // Calculate shard size with padding for even division
            let shard_size = numel.div_ceil(world_size);
            let padding = shard_size * world_size - numel;

            // Get local shard
            let flat_data = data.to_vec();
            let start = rank * shard_size;
            let end = ((rank + 1) * shard_size).min(flat_data.len());

            let mut shard_data: Vec<f32> = if start < flat_data.len() {
                flat_data[start..end].to_vec()
            } else {
                vec![0.0; shard_size]
            };

            // Pad to shard_size
            while shard_data.len() < shard_size {
                shard_data.push(0.0);
            }

            self.sharded_params.push(ShardedParam {
                local_shard: Tensor::from_vec(shard_data, &[shard_size]).unwrap(),
                original_shape: shape,
                numel,
                padding,
            });
        }

        self.is_gathered = false;
    }

    /// Gathers all parameter shards before forward pass.
    pub fn gather_parameters(&mut self) {
        if self.is_gathered || self.sharding_strategy == ShardingStrategy::NoShard {
            return;
        }

        let _world_size = self.process_group.world_size();
        let params = self.module.parameters();

        for (param, sharded) in params.iter().zip(self.sharded_params.iter()) {
            // All-gather the shards
            let gathered = self.process_group.all_gather_tensor(&sharded.local_shard);

            // Reshape back to original shape (removing padding)
            let flat: Vec<f32> = gathered.to_vec().into_iter().take(sharded.numel).collect();
            let restored = Tensor::from_vec(flat, &sharded.original_shape).unwrap();

            param.update_data(restored);
        }

        self.is_gathered = true;
    }

    /// Shards parameters after forward/backward pass.
    pub fn reshard_parameters(&mut self) {
        if !self.is_gathered || self.sharding_strategy == ShardingStrategy::NoShard {
            return;
        }

        self.shard_parameters();
    }

    /// Synchronizes gradients across all ranks.
    pub fn sync_gradients(&self) {
        match self.sharding_strategy {
            ShardingStrategy::NoShard => {
                // Full all-reduce like DDP
                for param in self.module.parameters() {
                    if let Some(grad) = param.grad() {
                        let mut grad_tensor = grad.clone();
                        self.process_group
                            .all_reduce_tensor(&mut grad_tensor, ReduceOp::Average);
                    }
                }
            }
            ShardingStrategy::ShardGradOp | ShardingStrategy::FullShard => {
                // Reduce-scatter gradients to get sharded gradients
                for param in self.module.parameters() {
                    if let Some(grad) = param.grad() {
                        let _reduced = self
                            .process_group
                            .reduce_scatter_tensor(&grad, ReduceOp::Average);
                        // In full implementation, would update parameter's gradient shard
                    }
                }
            }
            ShardingStrategy::HybridShard => {
                // All-reduce within node, reduce-scatter across nodes
                for param in self.module.parameters() {
                    if let Some(grad) = param.grad() {
                        let mut grad_tensor = grad.clone();
                        self.process_group
                            .all_reduce_tensor(&mut grad_tensor, ReduceOp::Average);
                    }
                }
            }
        }
    }

    /// Clips gradients by global norm.
    pub fn clip_grad_norm(&self, max_norm: f32) -> f32 {
        let mut total_norm_sq = 0.0f32;

        for param in self.module.parameters() {
            if let Some(grad) = param.grad() {
                let grad_vec = grad.to_vec();
                let norm_sq: f32 = grad_vec.iter().map(|x| x * x).sum();
                total_norm_sq += norm_sq;
            }
        }

        // All-reduce total norm across ranks
        let mut norm_tensor = Tensor::from_vec(vec![total_norm_sq], &[1]).unwrap();
        self.process_group
            .all_reduce_tensor(&mut norm_tensor, ReduceOp::Sum);
        let global_norm = norm_tensor.to_vec()[0].sqrt();

        // Clip if necessary
        if global_norm > max_norm {
            let clip_coef = max_norm / (global_norm + 1e-6);
            for param in self.module.parameters() {
                if let Some(grad) = param.grad() {
                    let clipped: Vec<f32> = grad.to_vec().iter().map(|x| x * clip_coef).collect();
                    let clipped_tensor = Tensor::from_vec(clipped, grad.shape()).unwrap();
                    param.variable().set_grad(clipped_tensor);
                }
            }
        }

        global_norm
    }

    /// Estimates memory usage with different sharding strategies.
    pub fn memory_estimate(&self) -> FSDPMemoryStats {
        let params = self.module.parameters();
        let total_params: usize = params.iter().map(|p| p.numel()).sum();
        let world_size = self.process_group.world_size();

        let bytes_per_param = 4; // f32
        let param_memory = total_params * bytes_per_param;

        let (sharded_params, sharded_grads, sharded_optim) = match self.sharding_strategy {
            ShardingStrategy::NoShard => (param_memory, param_memory, param_memory * 2),
            ShardingStrategy::ShardGradOp => (
                param_memory,
                param_memory / world_size,
                param_memory * 2 / world_size,
            ),
            ShardingStrategy::FullShard | ShardingStrategy::HybridShard => (
                param_memory / world_size,
                param_memory / world_size,
                param_memory * 2 / world_size,
            ),
        };

        FSDPMemoryStats {
            total_params,
            param_memory_bytes: sharded_params,
            grad_memory_bytes: sharded_grads,
            optim_memory_bytes: sharded_optim,
            world_size,
        }
    }
}

impl<M: Module> Module for FullyShardedDataParallel<M> {
    fn forward(&self, input: &Variable) -> Variable {
        // Note: In a real implementation, gather would be called automatically
        // through hooks before forward and reshard after
        self.module.forward(input)
    }

    fn parameters(&self) -> Vec<Parameter> {
        self.module.parameters()
    }

    fn train(&mut self) {
        self.module.train();
    }

    fn eval(&mut self) {
        self.module.eval();
    }

    fn is_training(&self) -> bool {
        self.module.is_training()
    }
}

/// Memory statistics for FSDP.
#[derive(Debug, Clone)]
pub struct FSDPMemoryStats {
    /// Total number of parameters
    pub total_params: usize,
    /// Memory for parameters (bytes)
    pub param_memory_bytes: usize,
    /// Memory for gradients (bytes)
    pub grad_memory_bytes: usize,
    /// Memory for optimizer state (bytes)
    pub optim_memory_bytes: usize,
    /// World size (number of ranks)
    pub world_size: usize,
}

impl FSDPMemoryStats {
    /// Total memory per rank in MB.
    pub fn total_memory_mb(&self) -> f32 {
        (self.param_memory_bytes + self.grad_memory_bytes + self.optim_memory_bytes) as f32
            / (1024.0 * 1024.0)
    }

    /// Memory savings compared to no sharding.
    pub fn memory_savings(&self) -> f32 {
        if self.world_size > 1 {
            1.0 - (1.0 / self.world_size as f32)
        } else {
            0.0
        }
    }
}

// =============================================================================
// Tensor Parallelism
// =============================================================================

/// Column-parallel linear layer.
///
/// Splits the weight matrix along the column dimension across ranks.
/// Each rank computes a portion of the output features.
#[allow(dead_code)]
pub struct ColumnParallelLinear {
    /// Local weight shard
    weight: Parameter,
    /// Bias (replicated on all ranks)
    bias: Option<Parameter>,
    /// Process group
    process_group: ProcessGroup,
    /// Input features
    in_features: usize,
    /// Output features (total across all ranks)
    out_features: usize,
    /// Whether to gather output
    gather_output: bool,
}

impl ColumnParallelLinear {
    /// Creates a new column-parallel linear layer.
    pub fn new(
        in_features: usize,
        out_features: usize,
        bias: bool,
        process_group: ProcessGroup,
        gather_output: bool,
    ) -> Self {
        let world_size = process_group.world_size();
        let local_out_features = out_features / world_size;

        let weight_data = Tensor::randn(&[local_out_features, in_features]);
        let weight = Parameter::new(weight_data, true);

        let bias = if bias {
            let bias_data = Tensor::zeros(&[local_out_features]);
            Some(Parameter::new(bias_data, true))
        } else {
            None
        };

        Self {
            weight,
            bias,
            process_group,
            in_features,
            out_features,
            gather_output,
        }
    }
}

impl Module for ColumnParallelLinear {
    fn forward(&self, input: &Variable) -> Variable {
        // Local matmul: input @ weight.T
        let weight_var = Variable::new(self.weight.data(), false);
        let output = input.matmul(&weight_var.transpose(0, 1));

        // Add bias
        let output = if let Some(ref bias) = self.bias {
            let bias_var = Variable::new(bias.data(), false);
            output.add(&bias_var)
        } else {
            output
        };

        // Optionally gather output across ranks
        if self.gather_output {
            let gathered = self.process_group.all_gather_tensor(&output.data());
            Variable::new(gathered, output.requires_grad())
        } else {
            output
        }
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut params = vec![self.weight.clone()];
        if let Some(ref bias) = self.bias {
            params.push(bias.clone());
        }
        params
    }
}

/// Row-parallel linear layer.
///
/// Splits the weight matrix along the row dimension across ranks.
/// Each rank has a portion of the input features.
#[allow(dead_code)]
pub struct RowParallelLinear {
    /// Local weight shard
    weight: Parameter,
    /// Bias (only on rank 0)
    bias: Option<Parameter>,
    /// Process group
    process_group: ProcessGroup,
    /// Input features (total across all ranks)
    in_features: usize,
    /// Output features
    out_features: usize,
    /// Whether input is already split
    input_is_parallel: bool,
}

impl RowParallelLinear {
    /// Creates a new row-parallel linear layer.
    pub fn new(
        in_features: usize,
        out_features: usize,
        bias: bool,
        process_group: ProcessGroup,
        input_is_parallel: bool,
    ) -> Self {
        let world_size = process_group.world_size();
        let rank = process_group.rank();
        let local_in_features = in_features / world_size;

        let weight_data = Tensor::randn(&[out_features, local_in_features]);
        let weight = Parameter::new(weight_data, true);

        // Only rank 0 has bias
        let bias = if bias && rank == 0 {
            let bias_data = Tensor::zeros(&[out_features]);
            Some(Parameter::new(bias_data, true))
        } else {
            None
        };

        Self {
            weight,
            bias,
            process_group,
            in_features,
            out_features,
            input_is_parallel,
        }
    }
}

impl Module for RowParallelLinear {
    fn forward(&self, input: &Variable) -> Variable {
        // If input is not parallel, take local shard
        let local_input = if self.input_is_parallel {
            input.clone()
        } else {
            // Split input along feature dimension for row parallelism
            let world_size = self.process_group.world_size();
            let rank = self.process_group.rank();
            let data = input.data();
            let shape = data.shape();
            let feature_dim = shape[shape.len() - 1];
            let local_features = feature_dim / world_size;
            let start = rank * local_features;
            let end = start + local_features;

            // Slice the last dimension
            let sliced = if shape.len() == 2 {
                data.slice(&[0..shape[0], start..end])
            } else {
                data.clone() // Fallback for other shapes
            };
            Variable::new(sliced, input.requires_grad())
        };

        // Local matmul
        let weight_var = Variable::new(self.weight.data(), false);
        let local_output = local_input.matmul(&weight_var.transpose(0, 1));

        // All-reduce to combine partial outputs
        let mut output_data = local_output.data().clone();
        self.process_group
            .all_reduce_tensor(&mut output_data, ReduceOp::Sum);
        let output = Variable::new(output_data, local_output.requires_grad());

        // Add bias (only on rank 0, then broadcast)
        if let Some(ref bias) = self.bias {
            let bias_var = Variable::new(bias.data(), false);
            output.add(&bias_var)
        } else {
            output
        }
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut params = vec![self.weight.clone()];
        if let Some(ref bias) = self.bias {
            params.push(bias.clone());
        }
        params
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use axonml_nn::Linear;

    #[test]
    fn test_sharding_strategy_default() {
        assert_eq!(ShardingStrategy::default(), ShardingStrategy::FullShard);
    }

    #[test]
    fn test_fsdp_creation() {
        let model = Linear::new(10, 5);
        let pg = ProcessGroup::mock();
        let fsdp = FullyShardedDataParallel::new(model, pg);

        assert_eq!(fsdp.strategy(), ShardingStrategy::FullShard);
    }

    #[test]
    fn test_fsdp_forward() {
        let model = Linear::new(4, 2);
        let pg = ProcessGroup::mock();
        let mut fsdp = FullyShardedDataParallel::new(model, pg);

        // Gather before forward
        fsdp.gather_parameters();

        let input = Variable::new(Tensor::from_vec(vec![1.0; 4], &[1, 4]).unwrap(), false);
        let output = fsdp.forward(&input);

        assert_eq!(output.data().shape(), &[1, 2]);
    }

    #[test]
    fn test_fsdp_builder() {
        let model = Linear::new(10, 5);
        let pg = ProcessGroup::mock();

        let fsdp = FullyShardedDataParallel::new(model, pg)
            .sharding_strategy(ShardingStrategy::ShardGradOp)
            .cpu_offload(CPUOffload::Params)
            .mixed_precision(true);

        assert_eq!(fsdp.strategy(), ShardingStrategy::ShardGradOp);
    }

    #[test]
    fn test_fsdp_memory_stats() {
        let model = Linear::new(100, 50);
        let pg = ProcessGroup::mock();
        let fsdp = FullyShardedDataParallel::new(model, pg);

        let stats = fsdp.memory_estimate();
        assert!(stats.total_params > 0);
        assert!(stats.total_memory_mb() > 0.0);
    }

    #[test]
    fn test_fsdp_no_shard() {
        let model = Linear::new(10, 5);
        let pg = ProcessGroup::mock();
        let fsdp =
            FullyShardedDataParallel::new(model, pg).sharding_strategy(ShardingStrategy::NoShard);

        assert_eq!(fsdp.strategy(), ShardingStrategy::NoShard);
    }

    #[test]
    fn test_column_parallel_linear() {
        let pg = ProcessGroup::mock();
        // With world_size=1, local_out_features = out_features / 1 = 4
        let layer = ColumnParallelLinear::new(8, 4, true, pg, false); // Don't gather for simple test

        let input = Variable::new(Tensor::randn(&[2, 8]), false);
        let output = layer.forward(&input);

        // Output shape should be [batch, local_out_features] = [2, 4]
        assert_eq!(output.data().shape(), &[2, 4]);
    }

    #[test]
    fn test_row_parallel_linear() {
        let pg = ProcessGroup::mock();
        let layer = RowParallelLinear::new(8, 4, true, pg, false);

        let input = Variable::new(Tensor::randn(&[2, 8]), false);
        let output = layer.forward(&input);

        assert_eq!(output.data().shape(), &[2, 4]);
    }
}