bhc-tensor-ir
Tensor Intermediate Representation for the Basel Haskell Compiler.
Overview
This crate defines the Tensor IR, a specialized representation for numeric computations that enables aggressive optimization of array and matrix operations. It implements the M9 tensor model from the H26-SPEC, providing guaranteed fusion and efficient memory layout.
Features
- Shape-indexed tensor types with compile-time dimension checking
- Guaranteed fusion for composable operations
- Memory layout optimization (row-major, column-major, strided)
- Automatic broadcasting semantics
- Element-wise, reduction, and contraction operations
- Fusion-friendly kernel representation
Key Types
| Type | Description |
|---|---|
TensorOp |
Tensor operation enum |
TensorMeta |
Tensor metadata (dtype, shape, strides, layout) |
Kernel |
Fused operation kernel |
Shape |
Tensor dimensions |
DType |
Element data type |
Strides |
Memory strides for each dimension |
Layout |
Memory layout (RowMajor, ColMajor, Strided) |
Usage
Creating Tensor Operations
use ;
// Create tensor metadata
let meta = TensorMeta ;
// Element-wise operation: a + b
let add = Binary ;
// Matrix multiplication
let matmul = Contraction ;
Tensor Metadata (H26-SPEC Section 7.3)
Operation Variants
Guaranteed Fusion (H26-SPEC Section 8)
The Tensor IR guarantees fusion for these patterns:
// Pattern 1: Element-wise chains
// a.map(f).map(g).map(h) → a.map(f ∘ g ∘ h)
// Pattern 2: Map-reduce
// a.map(f).reduce(+) → fused map-reduce kernel
// Pattern 3: Broadcast-binary
// a + broadcast(b) → single pass with inline broadcast
// Pattern 4: Transpose-matmul
// matmul(transpose(a), b) → single matmul with transposed access
Fusion in Practice
use ;
// Multiple operations fuse into a single kernel
let kernel = Kernel ;
Data Types
Memory Layouts
Design Notes
- Tensor IR operates on logical tensor operations, not loops
- Shape information enables static dimension checking
- Stride representation allows zero-copy views and slices
- Fusion decisions are made before lowering to Loop IR
- Alias analysis prevents incorrect optimizations
Related Crates
bhc-core- Input Core IRbhc-loop-ir- Output Loop IR for codegenbhc-types- Type-level shape representation (M9)bhc-gpu- GPU code generation from Tensor IRbhc-codegen- CPU code generation
Specification References
- H26-SPEC Section 7: Tensor Model (M9)
- H26-SPEC Section 7.3: TensorMeta Requirements
- H26-SPEC Section 8: Fusion Guarantees