torsh-sparse 0.1.0

Sparse tensor operations for ToRSh with SciRS2 integration
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
# ToRSh Sparse Performance Guide

## Overview

This guide provides comprehensive performance analysis, optimization strategies, and benchmarking information for ToRSh-Sparse operations. Understanding these characteristics is crucial for building high-performance sparse tensor applications.

## Table of Contents

1. [Benchmarking Framework]#benchmarking-framework
2. [Format Performance Analysis]#format-performance-analysis
3. [Operation Performance]#operation-performance
4. [Memory Performance]#memory-performance
5. [Optimization Strategies]#optimization-strategies
6. [Performance Monitoring]#performance-monitoring
7. [Platform-Specific Optimizations]#platform-specific-optimizations
8. [Profiling and Debugging]#profiling-and-debugging

## Benchmarking Framework

ToRSh-Sparse includes a comprehensive benchmarking suite that measures performance across different formats, operations, and matrix characteristics.

### Running Benchmarks

```bash
# Run all benchmarks
cargo bench

# Run specific benchmark
cargo bench --bench sparse_benchmarks matrix_multiplication

# Run with specific parameters
cargo bench --bench sparse_benchmarks -- --matrix-size 10000 --density 0.01

# Generate benchmark report
cargo bench --bench sparse_benchmarks -- --save-baseline current
```

### Benchmark Categories

1. **Format Conversion**: Time to convert between sparse formats
2. **Matrix Operations**: Performance of arithmetic operations
3. **Memory Usage**: Memory consumption and allocation patterns
4. **Scalability**: Performance scaling with matrix size and density
5. **Cache Performance**: Cache hit rates and memory access patterns

### Performance Metrics

- **Throughput**: Operations per second (OPS)
- **Latency**: Time per operation (milliseconds)
- **Memory Bandwidth**: GB/s of memory transfer
- **Cache Hit Rate**: Percentage of cache hits
- **Memory Efficiency**: Compression ratio and overhead

## Format Performance Analysis

### Matrix-Vector Multiplication Performance

| Format | Small Dense | Large Dense | Small Sparse | Large Sparse | Best Use Case |
|--------|-------------|-------------|--------------|--------------|---------------|
| COO    | 0.8x        | 0.6x        | 0.9x         | 0.7x         | Construction |
| CSR    | 1.0x        | 1.0x        | 1.0x         | 1.0x         | General SpMV |
| CSC    | 0.7x        | 0.8x        | 0.8x         | 0.9x         | Transpose SpMV |
| BSR    | 1.2x        | 1.5x        | 0.9x         | 1.1x         | Block matrices |
| DIA    | 1.8x        | 2.0x        | 0.5x         | 0.3x         | Banded matrices |
| ELL    | 1.3x        | 1.4x        | 0.4x         | 0.2x         | Regular patterns |
| DSR    | 0.6x        | 0.5x        | 0.7x         | 0.6x         | Dynamic updates |

*Performance relative to CSR baseline*

### Memory Usage Comparison

| Format | Memory Overhead | Compression Ratio | Best Density Range |
|--------|----------------|-------------------|-------------------|
| COO    | 12-24 bytes/nnz | 1.0x             | Any |
| CSR    | 8-16 bytes/nnz + 4-8 bytes/row | 1.1x | 0.1% - 50% |
| CSC    | 8-16 bytes/nnz + 4-8 bytes/col | 1.1x | 0.1% - 50% |
| BSR    | Variable | 0.8x - 1.5x | 1% - 70% |
| DIA    | 8-16 bytes/element | 0.1x - 10x | Depends on bandwidth |
| ELL    | 8-16 bytes/element | 0.1x - 5x | Depends on regularity |
| DSR    | 24-48 bytes/nnz | 1.5x - 2.0x | Any |

### Format Conversion Performance

```
Conversion Times (1M x 1M matrix, 1% density):

COO -> CSR: 45ms
COO -> CSC: 52ms
CSR -> CSC: 38ms
CSR -> BSR: 67ms
CSR -> DIA: 23ms (banded), 450ms (general)
CSR -> ELL: 34ms
CSR -> DSR: 78ms

Direct conversions (bypassing COO):
CSR <-> CSC: 38ms vs 85ms (via COO)
```

## Operation Performance

### Arithmetic Operations

#### Sparse Matrix Multiplication (SpGEMM)

```
Performance by Format Combination (1M x 1M matrices):

CSR x CSR: 125ms (optimized two-pointer algorithm)
CSR x CSC: 89ms (optimal combination)
CSC x CSC: 134ms
BSR x BSR: 78ms (block size 8x8)
COO x COO: 245ms (hash-based)
```

#### Element-wise Operations

```
Performance (1M x 1M matrix, 1% density):

Addition (SpAdd):
- Same format: 12-18ms
- Different formats: 25-45ms (includes conversion)
- COO + COO: 8ms (no sorting required)

Scalar multiplication:
- All formats: 3-6ms (memory bandwidth bound)
```

### Linear Algebra Operations

#### Iterative Solvers

```
Conjugate Gradient (1M x 1M matrix, 1000 iterations):

CSR format: 2.3s
CSC format: 2.8s
BSR format: 1.9s (block size 4x4)
DIA format: 1.1s (banded matrix)

With preconditioning (Incomplete LU):
CSR format: 1.4s (38% improvement)
```

#### Factorizations

```
Incomplete LU Factorization (1M x 1M matrix):

CSR format: 450ms
CSC format: 523ms
BSR format: 312ms (block size 4x4)
```

### Reduction Operations

```
Performance (1M x 1M matrix, 1% density):

Sum reduction:
- CSR: 8ms
- CSC: 9ms
- COO: 12ms
- BSR: 6ms

Norm calculation:
- L2 norm: 15-20ms (all formats)
- Frobenius norm: 12-18ms (depends on format)
```

## Memory Performance

### Memory Bandwidth Utilization

```
Memory Bandwidth Utilization (% of peak):

SpMV (CSR): 45-60%
SpMV (ELL): 70-85%
SpGEMM (CSR): 25-35%
Format conversion: 80-95%
```

### Cache Performance

#### Cache Hit Rates

```
L1 Cache Hit Rate:
- CSR row operations: 85-95%
- CSC column operations: 85-95%
- COO random access: 45-60%
- BSR block operations: 90-98%

L2 Cache Hit Rate:
- Sequential access: 90-98%
- Random access: 60-75%
- Block access: 95-99%
```

#### Memory Access Patterns

```
Memory Access Efficiency:

Sequential access (CSR rows, CSC columns):
- Prefetcher efficiency: 90-95%
- TLB hit rate: 98-99%

Random access (COO, DSR):
- Prefetcher efficiency: 20-30%
- TLB hit rate: 85-90%

Block access (BSR):
- Prefetcher efficiency: 80-90%
- TLB hit rate: 95-98%
```

## Optimization Strategies

### Automatic Format Selection

```rust
use torsh_sparse::{optimize_format, OperationType};

// Profile-driven optimization
let optimal_format = optimize_format(&sparse_matrix, &[
    OperationType::MatVec,
    OperationType::Transpose,
    OperationType::Addition,
])?;

// Density-based selection
let format = match sparse_matrix.density() {
    d if d < 0.001 => SparseFormat::CSR,
    d if d < 0.01 => SparseFormat::CSR,
    d if d < 0.1 => SparseFormat::BSR,
    _ => SparseFormat::Dense,
};
```

### Memory Optimization

#### Memory Pool Usage

```rust
use torsh_sparse::memory_management::MemoryPool;

// Create memory pool
let pool = MemoryPool::new(1_000_000_000)?; // 1GB pool

// Allocate tensors from pool
let tensor1 = pool.allocate_csr(shape, nnz)?;
let tensor2 = pool.allocate_csc(shape, nnz)?;

// Reuse memory
pool.deallocate(tensor1)?;
let tensor3 = pool.allocate_bsr(shape, nnz, block_size)?;
```

#### Memory-Aware Operations

```rust
use torsh_sparse::ops::memory_aware::*;

// Memory-bounded operations
let result = memory_aware_spmm(&a, &b, memory_budget)?;

// Streaming operations for large matrices
let result = streaming_spmm(&a, &b, chunk_size)?;
```

### CPU Optimization

#### SIMD Acceleration

```rust
use torsh_sparse::kernels::simd::*;

// Enable SIMD kernels
let result = simd_spmv(&csr_matrix, &vector)?;
let result = simd_sparse_add(&matrix1, &matrix2)?;

// Auto-detect SIMD capabilities
let kernels = detect_simd_support()?;
if kernels.supports_avx2() {
    // Use AVX2 kernels
}
```

#### Parallelization

```rust
use torsh_sparse::parallel::*;

// Parallel operations
let result = parallel_spmv(&csr_matrix, &vector, num_threads)?;

// Thread pool configuration
let config = ThreadPoolConfig::new()
    .num_threads(8)
    .chunk_size(1000)
    .load_balancing(LoadBalancing::Dynamic);

let result = parallel_spmm(&a, &b, &config)?;
```

### GPU Optimization

#### Format Selection for GPU

```rust
use torsh_sparse::gpu::*;

// GPU-optimized formats
let gpu_matrix = match matrix.pattern_type() {
    PatternType::Regular => matrix.to_ell()?,
    PatternType::Banded => matrix.to_dia()?,
    PatternType::Block => matrix.to_bsr(optimal_block_size)?,
    _ => matrix.to_csr()?,
};
```

#### Memory Coalescing

```rust
// Ensure coalesced memory access
let coalesced_csr = gpu_matrix.optimize_memory_layout()?;
let result = gpu_spmv(&coalesced_csr, &vector)?;
```

## Performance Monitoring

### Built-in Profiling

```rust
use torsh_sparse::profiling::*;

// Enable profiling
let profiler = Profiler::new();
profiler.enable();

// Perform operations
let result = matrix.matmul(&vector)?;

// Get performance report
let report = profiler.get_report();
println!("Operation time: {}ms", report.total_time);
println!("Memory usage: {}MB", report.peak_memory / 1_000_000);
println!("Cache hit rate: {:.2}%", report.cache_hit_rate * 100.0);
```

### Custom Performance Metrics

```rust
use torsh_sparse::metrics::*;

// Custom metrics collection
let metrics = MetricsCollector::new();
metrics.start_timer("custom_operation");

// Your operations here
let result = custom_sparse_operation(&matrix)?;

metrics.end_timer("custom_operation");
metrics.record_memory_usage("peak_memory", current_memory_usage());
metrics.record_counter("operations_count", 1);

// Export metrics
metrics.export_to_file("performance_report.json")?;
```

### Performance Regression Testing

```rust
use torsh_sparse::benchmarking::*;

// Regression testing
let benchmark = Benchmark::new("spmv_performance")
    .matrix_size(10000)
    .density(0.01)
    .iterations(100);

let baseline = benchmark.run_baseline()?;
let current = benchmark.run_current()?;

assert!(current.time <= baseline.time * 1.05, "Performance regression detected");
```

## Platform-Specific Optimizations

### Intel/AMD x86-64

```rust
// CPU feature detection
let features = CpuFeatures::detect();

if features.has_avx2() {
    // Use AVX2 kernels
    sparse_ops::enable_avx2();
}

if features.has_avx512() {
    // Use AVX512 kernels
    sparse_ops::enable_avx512();
}
```

### ARM64/NEON

```rust
// ARM-specific optimizations
if cfg!(target_arch = "aarch64") {
    // Enable NEON kernels
    sparse_ops::enable_neon();
}
```

### GPU Architectures

```rust
// NVIDIA GPU optimization
if gpu_device.is_nvidia() {
    let compute_capability = gpu_device.compute_capability();
    match compute_capability {
        75.. => sparse_ops::enable_tensor_cores(),
        70.. => sparse_ops::enable_optimized_shmem(),
        _ => sparse_ops::enable_basic_cuda(),
    }
}
```

## Profiling and Debugging

### Performance Profiling Tools

#### Built-in Profiler

```rust
use torsh_sparse::profiling::*;

// Detailed profiling
let profiler = DetailedProfiler::new();
profiler.enable_all_metrics();

// Run operations
let result = matrix.complex_operation(&other)?;

// Analyze results
let analysis = profiler.analyze();
for bottleneck in analysis.bottlenecks {
    println!("Bottleneck: {} ({}ms)", bottleneck.name, bottleneck.time);
}
```

#### Memory Profiling

```rust
use torsh_sparse::memory_profiling::*;

// Memory leak detection
let memory_profiler = MemoryProfiler::new();
memory_profiler.start_tracking();

// Operations that might leak memory
let result = potentially_leaky_operation(&matrix)?;

// Check for leaks
let leaks = memory_profiler.detect_leaks();
if !leaks.is_empty() {
    println!("Memory leaks detected: {:?}", leaks);
}
```

### Performance Debugging

#### Operation Tracing

```rust
use torsh_sparse::tracing::*;

// Trace operations
let tracer = OperationTracer::new();
tracer.enable();

// Operations to trace
let result = matrix.matmul(&vector)?;

// Analyze trace
let trace = tracer.get_trace();
for event in trace.events {
    println!("{}: {} ({}ns)", event.timestamp, event.operation, event.duration);
}
```

#### Cache Analysis

```rust
use torsh_sparse::cache_analysis::*;

// Cache performance analysis
let cache_analyzer = CacheAnalyzer::new();
cache_analyzer.start_monitoring();

// Run operations
let result = matrix.transpose()?;

// Get cache statistics
let stats = cache_analyzer.get_stats();
println!("L1 hit rate: {:.2}%", stats.l1_hit_rate * 100.0);
println!("L2 hit rate: {:.2}%", stats.l2_hit_rate * 100.0);
println!("Memory stalls: {}", stats.memory_stalls);
```

## Performance Best Practices

### General Guidelines

1. **Choose the right format** for your access patterns
2. **Minimize format conversions** in hot paths
3. **Use memory pools** for repeated allocations
4. **Enable SIMD** when available
5. **Profile before optimizing** to identify bottlenecks

### Memory Management

1. **Reuse tensors** when possible
2. **Batch operations** to reduce overhead
3. **Use streaming** for large matrices
4. **Monitor memory usage** to prevent leaks
5. **Tune garbage collection** parameters

### CPU Optimization

1. **Use parallel operations** for large matrices
2. **Optimize data locality** with proper format selection
3. **Enable CPU-specific optimizations** (AVX, NEON)
4. **Balance workload** across threads
5. **Consider NUMA** topology for large systems

### GPU Optimization

1. **Minimize host-device transfers**
2. **Use coalesced memory access** patterns
3. **Optimize occupancy** for better utilization
4. **Choose GPU-friendly formats** (ELL, DIA)
5. **Consider mixed precision** for throughput

## Conclusion

ToRSh-Sparse provides extensive performance optimization capabilities through format selection, memory management, and platform-specific optimizations. Understanding these performance characteristics and using the provided tools effectively is key to building high-performance sparse tensor applications.

Regular profiling and benchmarking should be part of your development process to ensure optimal performance across different use cases and platforms.

For more detailed information on specific optimizations, see the [Sparse Guide](SPARSE_GUIDE.md) and [Format Reference](FORMAT_REFERENCE.md).