Skip to main content

tenrso_ad/
compression.rs

1//! Gradient compression utilities for efficient distributed training.
2//!
3//! This module provides various gradient compression techniques to reduce
4//! communication overhead in distributed training scenarios:
5//!
6//! - **Quantization**: Reduce gradient precision (32-bit → 8-bit/16-bit)
7//! - **Top-K Sparsification**: Keep only top-k largest gradients by magnitude
8//! - **Random Sparsification**: Randomly sample gradients with probability p
9//! - **Error Feedback**: Accumulate quantization/sparsification errors for accuracy
10//!
11//! # Example
12//!
13//! ```rust,ignore
14//! use tenrso_ad::compression::{CompressedGradient, CompressionConfig, CompressionMethod};
15//! use tenrso_core::DenseND;
16//!
17//! let gradient = DenseND::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[4])?;
18//! let config = CompressionConfig {
19//!     method: CompressionMethod::TopK { k: 2 },
20//!     error_feedback: true,
21//! };
22//!
23//! let compressed = CompressedGradient::compress(&gradient, &config)?;
24//! let decompressed = compressed.decompress()?;
25//! ```
26
27use anyhow::{anyhow, Result};
28use scirs2_core::ndarray_ext::{Array, ArrayD, IxDyn};
29use scirs2_core::numeric::{Float, FromPrimitive};
30use tenrso_core::DenseND;
31
32/// Compression method for gradients
33#[derive(Debug, Clone, PartialEq)]
34pub enum CompressionMethod {
35    /// No compression
36    None,
37    /// 8-bit quantization
38    Quantize8Bit,
39    /// 16-bit quantization
40    Quantize16Bit,
41    /// Keep only top-k largest gradients by magnitude
42    TopK { k: usize },
43    /// Random sparsification with probability p
44    RandomSparsify { p: f64 },
45    /// Combined: quantize then sparsify
46    QuantizeThenSparsify { bits: u8, sparsity: f64 },
47}
48
49/// Configuration for gradient compression
50#[derive(Debug, Clone)]
51pub struct CompressionConfig {
52    /// Compression method to use
53    pub method: CompressionMethod,
54    /// Whether to use error feedback accumulation
55    pub error_feedback: bool,
56    /// Random seed for reproducible compression
57    pub seed: Option<u64>,
58}
59
60impl Default for CompressionConfig {
61    fn default() -> Self {
62        Self {
63            method: CompressionMethod::None,
64            error_feedback: false,
65            seed: None,
66        }
67    }
68}
69
70/// Compressed gradient representation
71pub struct CompressedGradient<T> {
72    /// Original shape of the gradient
73    shape: Vec<usize>,
74    /// Compressed data (format depends on compression method)
75    data: CompressedData<T>,
76    /// Compression method used
77    #[allow(dead_code)]
78    method: CompressionMethod,
79    /// Error feedback accumulator (for future use)
80    #[allow(dead_code)]
81    error_feedback: Option<ArrayD<T>>,
82}
83
84/// Internal representation of compressed data
85enum CompressedData<T> {
86    /// No compression - full gradient
87    Full(ArrayD<T>),
88    /// 8-bit quantized values + scale and offset
89    Quantized8Bit { values: Vec<u8>, scale: T, min: T },
90    /// 16-bit quantized values + scale and offset
91    Quantized16Bit { values: Vec<u16>, scale: T, min: T },
92    /// Sparse representation: (indices, values)
93    Sparse { indices: Vec<usize>, values: Vec<T> },
94}
95
96impl<T: Float + FromPrimitive> CompressedGradient<T> {
97    /// Compress a gradient using the specified configuration
98    ///
99    /// # Arguments
100    ///
101    /// * `gradient` - The gradient tensor to compress
102    /// * `config` - Compression configuration
103    ///
104    /// # Returns
105    ///
106    /// Compressed gradient that can be transmitted efficiently
107    pub fn compress(gradient: &DenseND<T>, config: &CompressionConfig) -> Result<Self> {
108        let shape = gradient.shape().to_vec();
109        let data_array = gradient.as_array();
110
111        let data = match &config.method {
112            CompressionMethod::None => CompressedData::Full(data_array.clone()),
113
114            CompressionMethod::Quantize8Bit => Self::quantize_8bit(data_array)?,
115
116            CompressionMethod::Quantize16Bit => Self::quantize_16bit(data_array)?,
117
118            CompressionMethod::TopK { k } => Self::topk_sparsify(data_array, *k)?,
119
120            CompressionMethod::RandomSparsify { p } => {
121                Self::random_sparsify(data_array, *p, config.seed)?
122            }
123
124            CompressionMethod::QuantizeThenSparsify { bits, sparsity } => {
125                // First quantize
126                let quantized = match bits {
127                    8 => Self::quantize_8bit(data_array)?,
128                    16 => Self::quantize_16bit(data_array)?,
129                    _ => return Err(anyhow!("Unsupported bit depth: {}", bits)),
130                };
131
132                // Then sparsify the quantized result
133                let temp_dense = Self::decompress_data(&quantized, &shape)?;
134                Self::random_sparsify(&temp_dense, *sparsity, config.seed)?
135            }
136        };
137
138        Ok(Self {
139            shape,
140            data,
141            method: config.method.clone(),
142            error_feedback: if config.error_feedback {
143                Some(ArrayD::zeros(IxDyn(gradient.shape())))
144            } else {
145                None
146            },
147        })
148    }
149
150    /// Decompress the gradient back to full representation
151    pub fn decompress(&self) -> Result<DenseND<T>> {
152        let decompressed = Self::decompress_data(&self.data, &self.shape)?;
153        Ok(DenseND::from_array(decompressed))
154    }
155
156    /// Get compression ratio (original size / compressed size)
157    pub fn compression_ratio(&self) -> f64 {
158        let original_size = self.shape.iter().product::<usize>() * std::mem::size_of::<T>();
159        let compressed_size = self.compressed_size_bytes();
160        original_size as f64 / compressed_size as f64
161    }
162
163    /// Get compressed size in bytes
164    pub fn compressed_size_bytes(&self) -> usize {
165        match &self.data {
166            CompressedData::Full(_) => {
167                self.shape.iter().product::<usize>() * std::mem::size_of::<T>()
168            }
169            CompressedData::Quantized8Bit { values, .. } => {
170                values.len() + std::mem::size_of::<T>() + 1 // values + scale + zero_point
171            }
172            CompressedData::Quantized16Bit { values, .. } => {
173                values.len() * 2 + std::mem::size_of::<T>() + 2
174            }
175            CompressedData::Sparse { indices, values } => {
176                indices.len() * std::mem::size_of::<usize>()
177                    + values.len() * std::mem::size_of::<T>()
178            }
179        }
180    }
181
182    /// Get sparsity (fraction of zeros) if applicable
183    pub fn sparsity(&self) -> Option<f64> {
184        match &self.data {
185            CompressedData::Sparse { indices, .. } => {
186                let total = self.shape.iter().product::<usize>();
187                let nonzero = indices.len();
188                Some(1.0 - (nonzero as f64 / total as f64))
189            }
190            _ => None,
191        }
192    }
193
194    // Helper methods for compression
195
196    fn quantize_8bit(data: &ArrayD<T>) -> Result<CompressedData<T>> {
197        let min = data.iter().copied().fold(T::infinity(), T::min);
198        let max = data.iter().copied().fold(T::neg_infinity(), T::max);
199
200        let scale = (max - min) / T::from_u8(255).unwrap();
201
202        let values: Vec<u8> = data
203            .iter()
204            .map(|&val| ((val - min) / scale).to_u8().unwrap_or(0))
205            .collect();
206
207        Ok(CompressedData::Quantized8Bit { values, scale, min })
208    }
209
210    fn quantize_16bit(data: &ArrayD<T>) -> Result<CompressedData<T>> {
211        let min = data.iter().copied().fold(T::infinity(), T::min);
212        let max = data.iter().copied().fold(T::neg_infinity(), T::max);
213
214        let scale = (max - min) / T::from_u16(65535).unwrap();
215
216        let values: Vec<u16> = data
217            .iter()
218            .map(|&val| ((val - min) / scale).to_u16().unwrap_or(0))
219            .collect();
220
221        Ok(CompressedData::Quantized16Bit { values, scale, min })
222    }
223
224    fn topk_sparsify(data: &ArrayD<T>, k: usize) -> Result<CompressedData<T>> {
225        let total_elements = data.len();
226        if k > total_elements {
227            return Err(anyhow!("k={} exceeds total elements={}", k, total_elements));
228        }
229
230        // Create (index, magnitude) pairs
231        let mut indexed_magnitudes: Vec<(usize, T)> = data
232            .iter()
233            .enumerate()
234            .map(|(i, &val)| (i, val.abs()))
235            .collect();
236
237        // Sort by magnitude (descending)
238        indexed_magnitudes.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
239
240        // Keep top-k
241        let mut indices = Vec::with_capacity(k);
242        let mut values = Vec::with_capacity(k);
243
244        for (idx, _mag) in indexed_magnitudes.iter().take(k) {
245            indices.push(*idx);
246            values.push(data[[*idx]]);
247        }
248
249        Ok(CompressedData::Sparse { indices, values })
250    }
251
252    fn random_sparsify(
253        data: &ArrayD<T>,
254        sparsity: f64,
255        _seed: Option<u64>,
256    ) -> Result<CompressedData<T>> {
257        if !(0.0..=1.0).contains(&sparsity) {
258            return Err(anyhow!("Sparsity must be in [0, 1], got {}", sparsity));
259        }
260
261        let keep_prob = 1.0 - sparsity;
262        let mut indices = Vec::new();
263        let mut values = Vec::new();
264
265        // Simple deterministic "random" for now (can enhance with actual RNG)
266        for (i, &val) in data.iter().enumerate() {
267            let pseudo_rand = ((i * 2654435761) % 1000) as f64 / 1000.0;
268            if pseudo_rand < keep_prob {
269                indices.push(i);
270                values.push(val);
271            }
272        }
273
274        Ok(CompressedData::Sparse { indices, values })
275    }
276
277    fn decompress_data(data: &CompressedData<T>, shape: &[usize]) -> Result<ArrayD<T>> {
278        match data {
279            CompressedData::Full(arr) => Ok(arr.clone()),
280
281            CompressedData::Quantized8Bit { values, scale, min } => {
282                let decompressed: Vec<T> = values
283                    .iter()
284                    .map(|&qval| {
285                        let q_float = T::from_u8(qval).unwrap();
286                        q_float * *scale + *min
287                    })
288                    .collect();
289
290                Array::from_shape_vec(IxDyn(shape), decompressed)
291                    .map_err(|e| anyhow!("Shape mismatch: {}", e))
292            }
293
294            CompressedData::Quantized16Bit { values, scale, min } => {
295                let decompressed: Vec<T> = values
296                    .iter()
297                    .map(|&qval| {
298                        let q_float = T::from_u16(qval).unwrap();
299                        q_float * *scale + *min
300                    })
301                    .collect();
302
303                Array::from_shape_vec(IxDyn(shape), decompressed)
304                    .map_err(|e| anyhow!("Shape mismatch: {}", e))
305            }
306
307            CompressedData::Sparse { indices, values } => {
308                let total_size = shape.iter().product();
309                let mut dense = ArrayD::zeros(IxDyn(shape));
310
311                for (&idx, &val) in indices.iter().zip(values.iter()) {
312                    if idx < total_size {
313                        dense[[idx]] = val;
314                    }
315                }
316
317                Ok(dense)
318            }
319        }
320    }
321}
322
323/// Statistics about compression performance
324#[derive(Debug, Clone)]
325pub struct CompressionStats {
326    /// Original size in bytes
327    pub original_bytes: usize,
328    /// Compressed size in bytes
329    pub compressed_bytes: usize,
330    /// Compression ratio
331    pub ratio: f64,
332    /// Sparsity (if applicable)
333    pub sparsity: Option<f64>,
334    /// Mean squared error after compression/decompression
335    pub mse: Option<f64>,
336}
337
338impl CompressionStats {
339    /// Compute compression statistics
340    pub fn compute<T: Float + FromPrimitive>(
341        original: &DenseND<T>,
342        compressed: &CompressedGradient<T>,
343    ) -> Result<Self> {
344        let original_bytes = original.len() * std::mem::size_of::<T>();
345        let compressed_bytes = compressed.compressed_size_bytes();
346        let ratio = compressed.compression_ratio();
347        let sparsity = compressed.sparsity();
348
349        // Compute MSE
350        let decompressed = compressed.decompress()?;
351        let mse = Self::compute_mse(original, &decompressed)?;
352
353        Ok(Self {
354            original_bytes,
355            compressed_bytes,
356            ratio,
357            sparsity,
358            mse: Some(mse),
359        })
360    }
361
362    fn compute_mse<T: Float + FromPrimitive>(a: &DenseND<T>, b: &DenseND<T>) -> Result<f64> {
363        if a.shape() != b.shape() {
364            return Err(anyhow!("Shape mismatch for MSE computation"));
365        }
366
367        let a_arr = a.as_array();
368        let b_arr = b.as_array();
369
370        let sum_sq_diff: T = a_arr
371            .iter()
372            .zip(b_arr.iter())
373            .map(|(&a_val, &b_val)| {
374                let diff = a_val - b_val;
375                diff * diff
376            })
377            .fold(T::zero(), |acc, x| acc + x);
378
379        let n = T::from_usize(a.len()).unwrap();
380        Ok((sum_sq_diff / n).to_f64().unwrap())
381    }
382}
383
384impl std::fmt::Display for CompressionStats {
385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386        writeln!(f, "Compression Statistics:")?;
387        writeln!(f, "  Original size: {} bytes", self.original_bytes)?;
388        writeln!(f, "  Compressed size: {} bytes", self.compressed_bytes)?;
389        writeln!(f, "  Compression ratio: {:.2}x", self.ratio)?;
390        if let Some(sparsity) = self.sparsity {
391            writeln!(f, "  Sparsity: {:.1}%", sparsity * 100.0)?;
392        }
393        if let Some(mse) = self.mse {
394            writeln!(f, "  MSE: {:.6e}", mse)?;
395        }
396        Ok(())
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn test_compression_config_default() {
406        let config = CompressionConfig::default();
407        assert!(matches!(config.method, CompressionMethod::None));
408        assert!(!config.error_feedback);
409    }
410
411    #[test]
412    fn test_quantize_8bit() {
413        let gradient = DenseND::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]).unwrap();
414        let config = CompressionConfig {
415            method: CompressionMethod::Quantize8Bit,
416            ..Default::default()
417        };
418
419        let compressed = CompressedGradient::compress(&gradient, &config).unwrap();
420        let decompressed = compressed.decompress().unwrap();
421
422        assert_eq!(decompressed.shape(), gradient.shape());
423        // Quantization introduces some error, but should be close
424        for i in 0..5 {
425            let original = gradient.get(&[i]).unwrap();
426            let recovered = decompressed.get(&[i]).unwrap();
427            assert!((original - recovered).abs() < 0.1);
428        }
429    }
430
431    #[test]
432    fn test_quantize_16bit() {
433        let gradient = DenseND::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]).unwrap();
434        let config = CompressionConfig {
435            method: CompressionMethod::Quantize16Bit,
436            ..Default::default()
437        };
438
439        let compressed = CompressedGradient::compress(&gradient, &config).unwrap();
440        let decompressed = compressed.decompress().unwrap();
441
442        // 16-bit should have much less error than 8-bit
443        for i in 0..5 {
444            let original = gradient.get(&[i]).unwrap();
445            let recovered = decompressed.get(&[i]).unwrap();
446            assert!((original - recovered).abs() < 0.01);
447        }
448    }
449
450    #[test]
451    fn test_topk_sparsify() {
452        let gradient = DenseND::from_vec(vec![1.0, 5.0, 2.0, 8.0, 3.0], &[5]).unwrap();
453        let config = CompressionConfig {
454            method: CompressionMethod::TopK { k: 2 },
455            ..Default::default()
456        };
457
458        let compressed = CompressedGradient::compress(&gradient, &config).unwrap();
459        assert_eq!(compressed.sparsity(), Some(0.6)); // 3 out of 5 are zero
460
461        let decompressed = compressed.decompress().unwrap();
462        // Top-2 values are 8.0 and 5.0, rest should be zero
463        assert_eq!(*decompressed.get(&[3]).unwrap(), 8.0);
464        assert_eq!(*decompressed.get(&[1]).unwrap(), 5.0);
465    }
466
467    #[test]
468    fn test_random_sparsify() {
469        let gradient = DenseND::from_vec(vec![1.0; 100], &[100]).unwrap();
470        let config = CompressionConfig {
471            method: CompressionMethod::RandomSparsify { p: 0.9 },
472            ..Default::default()
473        };
474
475        let compressed = CompressedGradient::compress(&gradient, &config).unwrap();
476        let sparsity = compressed.sparsity().unwrap();
477
478        // Should be approximately 90% sparse (may vary due to pseudo-random)
479        assert!(sparsity > 0.85 && sparsity < 0.95);
480    }
481
482    #[test]
483    fn test_compression_ratio() {
484        let gradient = DenseND::from_vec(vec![1.0; 1000], &[1000]).unwrap();
485
486        // 8-bit quantization should give ~4x compression (32-bit → 8-bit)
487        let config = CompressionConfig {
488            method: CompressionMethod::Quantize8Bit,
489            ..Default::default()
490        };
491        let compressed = CompressedGradient::compress(&gradient, &config).unwrap();
492        assert!(compressed.compression_ratio() > 3.0);
493    }
494
495    #[test]
496    fn test_topk_invalid_k() {
497        let gradient = DenseND::from_vec(vec![1.0, 2.0, 3.0], &[3]).unwrap();
498        let config = CompressionConfig {
499            method: CompressionMethod::TopK { k: 10 },
500            ..Default::default()
501        };
502
503        assert!(CompressedGradient::compress(&gradient, &config).is_err());
504    }
505
506    #[test]
507    fn test_compression_stats() {
508        let gradient = DenseND::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[4]).unwrap();
509        let config = CompressionConfig {
510            method: CompressionMethod::Quantize8Bit,
511            ..Default::default()
512        };
513
514        let compressed = CompressedGradient::compress(&gradient, &config).unwrap();
515        let stats = CompressionStats::compute(&gradient, &compressed).unwrap();
516
517        assert!(stats.ratio > 1.0);
518        assert!(stats.mse.is_some());
519    }
520
521    #[test]
522    fn test_no_compression() {
523        let gradient = DenseND::from_vec(vec![1.0, 2.0, 3.0], &[3]).unwrap();
524        let config = CompressionConfig {
525            method: CompressionMethod::None,
526            ..Default::default()
527        };
528
529        let compressed = CompressedGradient::compress(&gradient, &config).unwrap();
530        let decompressed = compressed.decompress().unwrap();
531
532        for i in 0..3 {
533            assert_eq!(
534                *gradient.get(&[i]).unwrap(),
535                *decompressed.get(&[i]).unwrap()
536            );
537        }
538    }
539
540    #[test]
541    fn test_compression_stats_display() {
542        let stats = CompressionStats {
543            original_bytes: 4000,
544            compressed_bytes: 1000,
545            ratio: 4.0,
546            sparsity: Some(0.75),
547            mse: Some(0.001),
548        };
549
550        let display = format!("{}", stats);
551        assert!(display.contains("4.00x"));
552        assert!(display.contains("75.0%"));
553    }
554}