tenflowers-core 0.1.0

Core tensor operations and execution engine for TenfloweRS
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
# Dispatch Registry Integration Guide

**Version:** 0.1.0
**Audience:** TenfloweRS Core Contributors
**Status:** Active Reference Document

## Table of Contents

1. [Overview]#overview
2. [Quick Start]#quick-start
3. [Architecture]#architecture
4. [Registration Patterns]#registration-patterns
5. [Kernel Implementation]#kernel-implementation
6. [Best Practices]#best-practices
7. [Testing]#testing
8. [Common Pitfalls]#common-pitfalls

## Overview

The TenfloweRS dispatch registry provides a unified system for registering and executing tensor operations across multiple backends (CPU, SIMD, GPU, BLAS, etc.). It eliminates per-module logic duplication and provides automatic backend selection based on device, dtype, and availability.

### Key Benefits

- **Unified Interface**: Single dispatch path for all operations
- **Automatic Backend Selection**: Choose optimal implementation at runtime
- **Feature Gating**: Conditional compilation for optional backends
- **Type Safety**: Type-specific registries prevent runtime errors
- **Extensibility**: Easy to add new operations and backends

### Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│                   Operation Call                             │
│           (e.g., tensor.abs(), add(a, b))                   │
└───────────────────────┬─────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│              Dispatch Registry Query                         │
│         get_registry::<T>().dispatch_unary("abs", x)        │
└───────────────────────┬─────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│              Backend Selection Logic                         │
│  1. Check device → preferred backend                        │
│  2. Filter available backends                               │
│  3. Select highest priority                                 │
└───────────────────────┬─────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│              Kernel Execution                                │
│         Backend-specific implementation                      │
│    (CPU, SIMD, GPU, BLAS, CUDA, Metal, etc.)               │
└─────────────────────────────────────────────────────────────┘
```

## Quick Start

### 1. Basic Unary Operation Registration

```rust
use crate::dispatch_registry::{
    BackendType, KernelImplementation, OperationDescriptor, F32_REGISTRY
};
use crate::{DType, Tensor, Result};

// Step 1: Define CPU kernel
fn sqrt_f32_cpu(x: &Tensor<f32>) -> Result<Tensor<f32>> {
    let data = x.data();
    let result: Vec<f32> = data.iter().map(|v| v.sqrt()).collect();
    let array = scirs2_autograd::ndarray::ArrayD::from_shape_vec(
        x.shape().dims(),
        result
    )?;
    Ok(Tensor::from_array(array))
}

// Step 2: Register operation
pub fn register_sqrt() {
    let desc = OperationDescriptor::new("sqrt", "unary")
        .with_dtypes(vec![DType::Float32])
        .with_broadcast();

    F32_REGISTRY.register_operation(desc).unwrap();

    // Step 3: Register CPU kernel
    F32_REGISTRY.register_kernel(
        "sqrt",
        KernelImplementation::unary(BackendType::Cpu, sqrt_f32_cpu)
    ).unwrap();
}

// Step 4: Use in operation
pub fn sqrt(x: &Tensor<f32>) -> Result<Tensor<f32>> {
    F32_REGISTRY.dispatch_unary("sqrt", x)
}
```

### 2. Basic Binary Operation Registration

```rust
// Step 1: Define CPU kernel
fn add_f32_cpu(a: &Tensor<f32>, b: &Tensor<f32>) -> Result<Tensor<f32>> {
    if a.shape() != b.shape() {
        return Err(TensorError::shape_mismatch("add", a.shape(), b.shape()));
    }
    let a_data = a.data();
    let b_data = b.data();
    let result: Vec<f32> = a_data.iter()
        .zip(b_data.iter())
        .map(|(x, y)| x + y)
        .collect();
    let array = scirs2_autograd::ndarray::ArrayD::from_shape_vec(
        a.shape().dims(),
        result
    )?;
    Ok(Tensor::from_array(array))
}

// Step 2: Register operation
pub fn register_add() {
    let desc = OperationDescriptor::new("add", "binary")
        .with_dtypes(vec![DType::Float32])
        .with_broadcast();

    F32_REGISTRY.register_operation(desc).unwrap();

    // Step 3: Register CPU kernel
    F32_REGISTRY.register_kernel(
        "add",
        KernelImplementation::binary(BackendType::Cpu, add_f32_cpu)
    ).unwrap();
}

// Step 4: Use in operation
pub fn add(a: &Tensor<f32>, b: &Tensor<f32>) -> Result<Tensor<f32>> {
    F32_REGISTRY.dispatch_binary("add", a, b)
}
```

## Architecture

### Type-Specific Registries

TenfloweRS uses type-specific registries to ensure type safety:

```rust
// Global registries (lazy_static)
pub static ref F32_REGISTRY: DispatchRegistry<f32>;
pub static ref F64_REGISTRY: DispatchRegistry<f64>;
pub static ref I32_REGISTRY: DispatchRegistry<i32>;

// Access via helper function
let registry = get_registry::<f32>().unwrap();
```

### Backend Types

```rust
pub enum BackendType {
    Cpu,                    // Always available
    #[cfg(feature = "simd")]
    SimdCpu,                // SIMD-optimized CPU
    #[cfg(feature = "blas")]
    Blas,                   // BLAS library
    #[cfg(feature = "gpu")]
    Gpu,                    // WebGPU
    #[cfg(feature = "cuda")]
    Cuda,                   // NVIDIA CUDA
    #[cfg(feature = "metal")]
    Metal,                  // Apple Metal
    #[cfg(feature = "rocm")]
    Rocm,                   // AMD ROCm
}
```

### Backend Priority

Backends are selected by priority (higher = preferred):

| Backend | Priority | Typical Use Case |
|---------|----------|------------------|
| Cpu     | 0        | Fallback, small tensors |
| SimdCpu | 10       | Medium tensors, CPU-only |
| Blas    | 20       | Linear algebra on CPU |
| Gpu     | 30       | General GPU (WebGPU) |
| Cuda    | 40       | NVIDIA GPUs |
| Rocm    | 40       | AMD GPUs |
| Metal   | 50       | Apple Silicon |

## Registration Patterns

### Pattern 1: Multi-Backend Registration

Register an operation for multiple backends:

```rust
pub fn register_matmul() {
    let desc = OperationDescriptor::new("matmul", "linalg")
        .with_dtypes(vec![DType::Float32])
        .with_rank_range(Some(2), None); // At least 2D

    F32_REGISTRY.register_operation(desc).unwrap();

    // CPU implementation
    F32_REGISTRY.register_kernel(
        "matmul",
        KernelImplementation::binary(BackendType::Cpu, matmul_f32_cpu)
    ).unwrap();

    // BLAS implementation (if available)
    #[cfg(feature = "blas")]
    F32_REGISTRY.register_kernel(
        "matmul",
        KernelImplementation::binary(BackendType::Blas, matmul_f32_blas)
    ).unwrap();

    // GPU implementation (if available)
    #[cfg(feature = "gpu")]
    F32_REGISTRY.register_kernel(
        "matmul",
        KernelImplementation::binary(BackendType::Gpu, matmul_f32_gpu)
    ).unwrap();
}
```

### Pattern 2: Multi-Type Registration

Register an operation for multiple data types:

```rust
pub fn register_abs_all_types() {
    // F32
    {
        let desc = OperationDescriptor::new("abs", "unary")
            .with_dtypes(vec![DType::Float32]);
        F32_REGISTRY.register_operation(desc).unwrap();
        F32_REGISTRY.register_kernel(
            "abs",
            KernelImplementation::unary(BackendType::Cpu, abs_f32_cpu)
        ).unwrap();
    }

    // F64
    {
        let desc = OperationDescriptor::new("abs", "unary")
            .with_dtypes(vec![DType::Float64]);
        F64_REGISTRY.register_operation(desc).unwrap();
        F64_REGISTRY.register_kernel(
            "abs",
            KernelImplementation::unary(BackendType::Cpu, abs_f64_cpu)
        ).unwrap();
    }

    // I32
    {
        let desc = OperationDescriptor::new("abs", "unary")
            .with_dtypes(vec![DType::Int32]);
        I32_REGISTRY.register_operation(desc).unwrap();
        I32_REGISTRY.register_kernel(
            "abs",
            KernelImplementation::unary(BackendType::Cpu, abs_i32_cpu)
        ).unwrap();
    }
}
```

### Pattern 3: Lazy Registration with Macros

Use macros to simplify registration:

```rust
// In your module
pub fn init_operations() {
    register_operation!(F32_REGISTRY, "abs", "unary",
        dtypes: [DType::Float32]);

    register_unary_kernel!(F32_REGISTRY, "abs",
        BackendType::Cpu, abs_f32_cpu);

    #[cfg(feature = "simd")]
    register_unary_kernel!(F32_REGISTRY, "abs",
        BackendType::SimdCpu, abs_f32_simd);
}
```

## Kernel Implementation

### CPU Kernels

CPU kernels should be simple, correct, and serve as reference implementations:

```rust
fn operation_cpu(inputs...) -> Result<Tensor<T>> {
    // 1. Validate inputs (shapes, constraints)
    // 2. Extract data
    // 3. Perform computation
    // 4. Package result

    let data = input.data();
    let result: Vec<T> = data.iter()
        .map(|v| /* operation */)
        .collect();

    let array = ArrayD::from_shape_vec(input.shape().dims(), result)?;
    Ok(Tensor::from_array(array))
}
```

### SIMD Kernels

SIMD kernels should use scirs2_core SIMD abstractions:

```rust
#[cfg(feature = "simd")]
fn operation_simd(input: &Tensor<f32>) -> Result<Tensor<f32>> {
    use scirs2_core::simd::{SimdArray, SimdOps};

    // Use SIMD operations from scirs2_core
    // If not available, fallback to CPU

    operation_cpu(input) // Fallback for now
}
```

### GPU Kernels

GPU kernels should use WebGPU compute shaders:

```rust
#[cfg(feature = "gpu")]
fn operation_gpu(input: &Tensor<f32>) -> Result<Tensor<f32>> {
    use crate::gpu::{GpuContext, execute_kernel};

    // 1. Get GPU context
    let context = GpuContext::get_or_create()?;

    // 2. Create shader if needed
    let shader = context.get_or_create_shader("operation", SHADER_SOURCE)?;

    // 3. Execute kernel
    execute_kernel(&context, &shader, input)
}
```

### BLAS Kernels

BLAS kernels should leverage optimized libraries:

```rust
#[cfg(feature = "blas")]
fn matmul_blas(a: &Tensor<f32>, b: &Tensor<f32>) -> Result<Tensor<f32>> {
    use crate::ops::lapack::matmul_blas;

    // Delegate to BLAS implementation
    matmul_blas(a, b)
}
```

## Best Practices

### 1. Always Provide CPU Fallback

Every operation MUST have a CPU implementation:

```rust
✅ GOOD:
F32_REGISTRY.register_kernel("op",
    KernelImplementation::unary(BackendType::Cpu, op_cpu)).unwrap();
#[cfg(feature = "gpu")]
F32_REGISTRY.register_kernel("op",
    KernelImplementation::unary(BackendType::Gpu, op_gpu)).unwrap();

❌ BAD:
#[cfg(feature = "gpu")]
F32_REGISTRY.register_kernel("op",
    KernelImplementation::unary(BackendType::Gpu, op_gpu)).unwrap();
// No CPU fallback!
```

### 2. Use Shape Error Taxonomy

Use standardized error messages:

```rust
use crate::shape_error_taxonomy::{ShapeErrorBuilder, ShapeErrorCategory};

✅ GOOD:
return Err(ShapeErrorBuilder::new("matmul", ShapeErrorCategory::MatMulIncompatible)
    .expected(&format!("(..., m, k) and (..., k, n)"))
    .got(&format!("({:?}) and ({:?})", a.shape(), b.shape()))
    .detail(&format!("Inner dimensions must match: {} != {}", k1, k2))
    .build());

❌ BAD:
return Err(TensorError::invalid_argument("matmul shapes don't match"));
```

### 3. Validate Inputs Early

Check preconditions before computation:

```rust
fn operation(a: &Tensor<f32>, b: &Tensor<f32>) -> Result<Tensor<f32>> {
    // ✅ Validate early
    if a.shape() != b.shape() {
        return Err(ShapeErrorBuilder::new("op",
            ShapeErrorCategory::ElementwiseMismatch)
            .expected(&format!("{:?}", a.shape()))
            .got(&format!("{:?}", b.shape()))
            .build());
    }

    // Now dispatch
    F32_REGISTRY.dispatch_binary("op", a, b)
}
```

### 4. Register at Module Initialization

Register operations when the module loads:

```rust
// In ops/mod.rs or specific operation module
pub fn register_all_operations() {
    register_unary_ops();
    register_binary_ops();
    register_reduction_ops();
    // ...
}

// Call this in lib.rs or at first use
lazy_static! {
    static ref INIT: () = {
        crate::ops::register_all_operations();
    };
}
```

### 5. Document Operation Constraints

Use OperationDescriptor to document constraints:

```rust
let desc = OperationDescriptor::new("conv2d", "nn")
    .with_dtypes(vec![DType::Float32, DType::Float64])
    .with_rank_range(Some(4), Some(4))  // Exactly 4D
    .with_broadcast()
    .with_inplace();  // If in-place is possible
```

## Testing

### Unit Tests for Kernels

Test each kernel implementation:

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_autograd::ndarray::array;

    #[test]
    fn test_abs_f32_cpu() {
        let input = Tensor::from_array(
            array![-1.0f32, 2.0, -3.0].into_dyn()
        );
        let result = abs_f32_cpu(&input).unwrap();
        assert_eq!(result.data(), &[1.0f32, 2.0, 3.0]);
    }

    #[test]
    fn test_abs_dispatch() {
        crate::ops::register_all_operations();

        let input = Tensor::from_array(
            array![-1.0f32, 2.0, -3.0].into_dyn()
        );
        let result = F32_REGISTRY.dispatch_unary("abs", &input).unwrap();
        assert_eq!(result.data(), &[1.0f32, 2.0, 3.0]);
    }
}
```

### Cross-Backend Consistency Tests

Ensure all backends produce identical results:

```rust
#[test]
#[cfg(all(feature = "simd", feature = "gpu"))]
fn test_cross_backend_consistency() {
    let input = Tensor::from_array(/* ... */);

    let cpu_result = F32_REGISTRY.dispatch_unary_on_backend(
        "op", &input, BackendType::Cpu
    ).unwrap();

    let simd_result = F32_REGISTRY.dispatch_unary_on_backend(
        "op", &input, BackendType::SimdCpu
    ).unwrap();

    let gpu_result = F32_REGISTRY.dispatch_unary_on_backend(
        "op", &input, BackendType::Gpu
    ).unwrap();

    // Allow small numerical differences
    assert_tensors_close(&cpu_result, &simd_result, 1e-6);
    assert_tensors_close(&cpu_result, &gpu_result, 1e-5);
}
```

### Performance Tests

Benchmark different backends:

```rust
#[bench]
fn bench_abs_cpu(b: &mut Bencher) {
    let input = Tensor::<f32>::randn(&[1000, 1000]);
    b.iter(|| {
        F32_REGISTRY.dispatch_unary_on_backend(
            "abs", &input, BackendType::Cpu
        )
    });
}
```

## Common Pitfalls

### Pitfall 1: Forgetting to Register

```rust
❌ BAD:
pub fn sqrt(x: &Tensor<f32>) -> Result<Tensor<f32>> {
    F32_REGISTRY.dispatch_unary("sqrt", x)  // Not registered!
}

✅ GOOD:
lazy_static! {
    static ref INIT: () = { register_sqrt(); };
}

pub fn sqrt(x: &Tensor<f32>) -> Result<Tensor<f32>> {
    let _ = *INIT;  // Ensure registration
    F32_REGISTRY.dispatch_unary("sqrt", x)
}
```

### Pitfall 2: Wrong Registry for Type

```rust
❌ BAD:
pub fn abs(x: &Tensor<f64>) -> Result<Tensor<f64>> {
    F32_REGISTRY.dispatch_unary("abs", x)  // Wrong registry!
}

✅ GOOD:
pub fn abs(x: &Tensor<f64>) -> Result<Tensor<f64>> {
    F64_REGISTRY.dispatch_unary("abs", x)
}
```

### Pitfall 3: Duplicate Registration

```rust
❌ BAD:
register_operation!(F32_REGISTRY, "add", "binary");
register_operation!(F32_REGISTRY, "add", "binary");  // Error!

✅ GOOD:
register_operation!(F32_REGISTRY, "add", "binary");
// Only register once
```

### Pitfall 4: Missing Feature Gates

```rust
❌ BAD:
F32_REGISTRY.register_kernel("op",
    KernelImplementation::unary(BackendType::Gpu, op_gpu)).unwrap();
// Compilation error if GPU feature not enabled!

✅ GOOD:
#[cfg(feature = "gpu")]
F32_REGISTRY.register_kernel("op",
    KernelImplementation::unary(BackendType::Gpu, op_gpu)).unwrap();
```

## Migration Checklist

When migrating an existing operation to use the dispatch registry:

- [ ] Create CPU kernel implementation
- [ ] Register operation with OperationDescriptor
- [ ] Register CPU kernel
- [ ] Add SIMD kernel (if applicable)
- [ ] Add GPU kernel (if applicable)
- [ ] Add BLAS kernel (if applicable)
- [ ] Update public API to use dispatch
- [ ] Add unit tests for each backend
- [ ] Add cross-backend consistency test
- [ ] Add performance benchmark
- [ ] Update documentation
- [ ] Remove old dispatch code

## References

- [dispatch_registry.rs]/src/dispatch_registry.rs - Core registry implementation
- [dispatch_registry_examples.rs]/src/dispatch_registry_examples.rs - Example registrations
- [shape_error_taxonomy.rs]/src/shape_error_taxonomy.rs - Error message standards
- [GPU Kernel Priorities]GPU_KERNEL_PRIORITIES.md - GPU development roadmap

---

**Questions?** Ask in #tenflowers-dev or file an issue
**Contributions:** Please follow this guide when adding new operations
**Last Updated:** 2026-03-20