Matrix Multiplication with Fusion Support #
Extends MatMul to support kernel fusion with subsequent element-wise operations.
Fusion Strategy #
MatMul itself is a complex operation requiring reduction across dimensions. However, the output of MatMul can be fused with subsequent element-wise ops:
-- This fuses the ReLU into the MatMul kernel's store phase
MatMul |> ReLU
Instead of:
- MatMul: compute C[i,j], write to VRAM
- ReLU: read C[i,j] from VRAM, apply ReLU, write back
We get:
- MatMul: compute C[i,j], apply ReLU, write to VRAM
Implementation Notes #
For now, this provides a placeholder kernel structure. A full implementation would:
- Use the existing subgroup matmul from
Examples/Compute/MainMatmul.lean - Allow fusion of element-wise operations into the output store phase
- Generate optimized WGSL with fused operations
The key insight: MatMul produces values that can flow through a composable kernel before being written to memory.
MatMul Kernel Abstraction #
Simplified MatMul kernel for demonstration.
In a full implementation, this would:
- Load tiles of A and B into shared memory
- Compute partial products using subgroup operations
- Apply any fused operations to the result
- Store to output buffer
For now, this is a placeholder showing the type structure.
Equations
- Hesper.Op.MatMulFusion.matmulKernel = { unKernel := fun (x : Unit) => pure (Hesper.WGSL.Exp.litF32 0.0) }
Instances For
Fusion Example: MatMul + Activation #
Fuse MatMul with an element-wise activation function.
This demonstrates the key pattern:
let fused = matmulKernel |> activationKernel
The activation is applied to each output element before storing, eliminating a memory roundtrip.
Equations
- Hesper.Op.MatMulFusion.matmulWithActivation activation = activation |> Hesper.Op.MatMulFusion.matmulKernel
Instances For
Common Fused Patterns #
MatMul + ReLU fusion
Equations
- One or more equations did not get rendered due to their size.
Instances For
MatMul + Sigmoid fusion
Equations
- One or more equations did not get rendered due to their size.
Instances For
MatMul + GELU fusion (Gaussian Error Linear Unit)
Equations
- One or more equations did not get rendered due to their size.
Instances For
Documentation & Examples #
Example: How to use fused MatMul + ReLU in a neural network layer.
Without fusion:
let C ← matmul A B -- GPU Kernel 1: compute matmul, write C
let R ← relu C -- GPU Kernel 2: read C, apply ReLU, write R
With fusion:
let R ← matmulReLU A B -- GPU Kernel 1: compute matmul, apply ReLU, write R
This saves one memory roundtrip and one kernel launch.