Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
77 commits
Select commit Hold shift + click to select a range
40d0e45
Add Metal GPU backend for accelerated compute
alok Nov 30, 2025
1e6d916
Add reusable benchmark infrastructure
alok Nov 30, 2025
025774f
feat: Add BLAS GEMM integration for Float matrix multiplication
alok Nov 30, 2025
4c6c015
feat: Upgrade to Lean 4.26.0-rc2
alok Nov 30, 2025
936a500
doc: add project philosophy to CLAUDE.md - priorities over proofs
alok Nov 30, 2025
7004850
Fix build errors for Lean v4.26.0-rc2
alok Nov 30, 2025
bcf8c1e
Fix v4.26 compatibility issues in proofs and examples
alok Nov 30, 2025
e1617e4
feat: Add MNIST demo with LeanPlot visualization and GitHub Pages
alok Dec 1, 2025
f76dea6
fix: Update test expected outputs for Lean 4.26 formatting changes
alok Dec 1, 2025
e88f42f
feat: Add Verso documentation site with type-safe neural network exam…
alok Dec 1, 2025
1583d20
Fix compile_inductive panic and upgrade to latest mathlib
alok Dec 2, 2025
baac981
Add explicit LeanBLAS FFI linking for DependentMNIST
alok Dec 2, 2025
11ec2f4
feat: Add NumPy .npy file format support
alok Dec 2, 2025
7483b2c
feat: Add TensorBackend typeclass for device abstraction
alok Dec 2, 2025
690b551
test: Add PyTorch→Lean MNIST verification pipeline
alok Dec 2, 2025
fab24c0
chore: Add test executables and fix DependentMNIST
alok Dec 2, 2025
204f8b9
doc: Add backend architecture notes to CLAUDE.md
alok Dec 2, 2025
29e6d3b
chore: Add Python project config for test scripts
alok Dec 2, 2025
d477ae1
chore: Update .gitignore for Python and test data
alok Dec 2, 2025
cfd2394
chore: Enable doc.verso option in lakefile
alok Dec 2, 2025
0d54ded
fix: Fix Verso doc.verso linting errors
alok Dec 2, 2025
7079fdc
fix: Make simp attributes compatible with doc.verso=true
alok Dec 2, 2025
c11390f
fix: DependentMNIST docstring syntax for doc.verso
alok Dec 2, 2025
a2e8822
feat: Add tinygrad-style ops (mean, argmax, argmin, relu, logSoftmax)
alok Dec 2, 2025
7310ee5
feat: Add LazyTensor compiler module inspired by tinygrad
alok Dec 3, 2025
25199a9
feat: Add movement ops, topological sort, and DataArrayN bridge
alok Dec 3, 2025
8cfb725
feat: Add CUDA backend with JIT compilation architecture
alok Dec 3, 2025
b1d8f49
fix: Clean up slop in LazyTensor and fix file typos
alok Dec 4, 2025
08a4041
fix: Clean up dead code and deprecated files
alok Dec 4, 2025
977e0e0
Add BLASBackend for LazyTensor using LeanBLAS
alok Dec 4, 2025
77013d1
Add LazyTensor interpreter with RTensor runtime type
alok Dec 4, 2025
0e0c95f
fix: Remove unused outSize variable in LazyTensor applyReduce
alok Dec 4, 2025
8e7b533
feat: MPS GEMM integration achieving 12.3 TFLOP/s
alok Dec 5, 2025
94a059f
refactor: AXPY/AXPBY use ByteArray for all params (zero-copy FFI)
alok Dec 5, 2025
1e27e7d
feat: Add Numpy100 exercises and Accelerate GEMM comparison
alok Dec 5, 2025
8a458bb
feat: Add CUDA backend scaffold for cloud GPU testing
alok Dec 6, 2025
1c6d9cd
perf: Add optimized simdgroup GEMM with shared memory prefetch
alok Dec 6, 2025
acda7cf
perf: Add M4-optimized GEMM kernel (experimental)
alok Dec 6, 2025
431549d
perf: Add fused softmax kernels (single memory pass)
alok Dec 6, 2025
f73af79
perf: Optimize Metal GEMM to 2.4+ TFLOP/s, add fused ML ops
alok Dec 6, 2025
d177bfc
perf: Add CPU fallback for small arrays, 25000x faster small ops
alok Dec 6, 2025
b38656c
feat: Add fused ML ops FFI bindings (biasRelu, biasGelu, layerNorm)
alok Dec 6, 2025
8b65913
fix: Remove Intel Mac OpenBLAS path to silence linker warning
alok Dec 6, 2025
b8e27ab
feat: Add fused attention kernels for Metal GPU
alok Dec 6, 2025
60de024
feat: Wire Metal ops into SciLean DataArrayN tensor types
alok Dec 7, 2025
70129c5
feat: Add comprehensive benchmark suite for Metal vs MLX/PyTorch
alok Dec 7, 2025
c6b46e3
feat: Add Conv2D/MaxPool2D/AvgPool2D Metal GPU kernels for CNN inference
alok Dec 11, 2025
9d3c53c
feat: Add optimized Conv2D kernels with 2x speedup for 3x3 convolutions
alok Dec 11, 2025
37e11ee
feat: Add im2col+GEMM Conv2D variant and benchmark comparison
alok Dec 11, 2025
7277bc7
Fix Lean 4.26 deprecations and Metal linking
alok Dec 12, 2025
0b9b2b0
Disable precompile on macOS; add Runge-Kutta steppers; fix deprecations
alok Dec 12, 2025
99cc2e7
Fix lake test on macOS; add einsum notation and smoke tests
alok Dec 14, 2025
3cdedd0
Fix FunctionArgument docs
alok Dec 14, 2025
a004362
Stabilize build + examples (LeanBLAS link, BFGS, WaveEquation)
alok Dec 15, 2025
3f0b1c6
Fix LBFGS line search (remove runtime sorry)
alok Dec 15, 2025
2b4da6b
Add Numpy-style DataArrayN helpers
alok Dec 15, 2025
adffc28
Add DataArrayN.rand and random benchmark
alok Dec 15, 2025
011cb66
Improve DataArray random fill and printing
alok Dec 15, 2025
4656499
Add RandT helper transformer
alok Dec 15, 2025
4a026a5
Use BLAS GEMM for DataArrayN matmul
alok Dec 15, 2025
0cfb4da
Add dtype-parametric C kernel with Lean integration
alok Dec 15, 2025
4289c3e
Add bf16/fp8 (e4m3/e5m2) support to dtype-parametric C kernel
alok Dec 15, 2025
1b6ddd3
Add GPU batching support and fused gemm_bias_relu kernel
alok Dec 16, 2025
59c2407
Fix Metal kernel names and add GPU fused kernel tests
alok Dec 16, 2025
5257bf4
Add batching-aware layer_norm, bias_gelu, avgpool2d to GpuBuffer
alok Dec 17, 2025
468508d
Add GPU batching benchmark
alok Dec 17, 2025
b8eee02
Add flash_attention and flash_attention_causal kernels
alok Dec 17, 2025
e22fd24
Add Metal shader code generator
alok Dec 17, 2025
0eda713
Add batchNorm2d with batching support to GpuBuffer
alok Dec 17, 2025
ca6bd31
Add GPU backward pass kernels for autodiff
alok Dec 17, 2025
91768cc
Optimize Metal GEMM with double-buffered tiling
alok Dec 17, 2025
b7bdf36
Add GPU-accelerated MNIST training example
alok Dec 17, 2025
54abcfe
Add tiled gemmTN and gemmNT kernels
alok Dec 17, 2025
ecf97f6
Add command buffer batching for GPU MNIST training
alok Dec 17, 2025
cb0b45d
Add GPU colSum kernel and optimize training
alok Dec 17, 2025
d3ea5f3
Fix large batch NaN bug with broadcast biasAdd kernel
alok Dec 17, 2025
43b1bc6
Add mini-batch training with GPU buffer slicing
alok Dec 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
perf: Optimize Metal GEMM to 2.4+ TFLOP/s, add fused ML ops
GEMM Optimizations:
- Add gemm_m4_pro: Software-pipelined kernel with register prefetch
- Add gemm_m4_max: Larger 128×64 tiles for better compute density
- Both require M, N, K multiples of 64

Bug Fixes:
- Fix GPU reduce_sum for large arrays (>1024 elements) via two-pass reduction
- Fix Accelerate GEMM: Replace broken cblas_sgemm with vDSP_mmul
- Add Accelerate framework to lakefile.lean linking

Fused Operations:
- Add fused softmax (single memory pass)
- Add bias_relu, bias_gelu kernels
- Add layer_norm kernel

Benchmarks at 2048×2048:
- MPS: 2.53 TFLOP/s
- M4Pro: 2.44 TFLOP/s
- M4: 2.42 TFLOP/s
- Accelerate: 2.19 TFLOP/s (CPU AMX)
  • Loading branch information
alok committed Dec 6, 2025
commit f73af791b0eee4e0f3d1cbaf5e3de7e9b7a7612e
443 changes: 389 additions & 54 deletions Metal/kmeans.metal

Large diffs are not rendered by default.

293 changes: 234 additions & 59 deletions Metal/metal_backend.mm

Large diffs are not rendered by default.

44 changes: 23 additions & 21 deletions SciLean/FFI/Metal.lean
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,24 @@ opaque gemmSimd (m k n : USize) (A B : @& ByteArray) : ByteArray
@[extern "scilean_metal_gemm_simd_opt_f32"]
opaque gemmSimdOpt (m k n : USize) (A B : @& ByteArray) : ByteArray

-- M4-optimized GEMM: float4 loads, 128×128 tiles, no bounds checks
-- REQUIRES: M, N, K are multiples of 128
-- 16 simdgroups (512 threads), 4×4 accumulator grid per simdgroup
-- M4-optimized GEMM: float4 loads, 64×64 tiles, no bounds checks
-- REQUIRES: M, N, K are multiples of 64
-- 8 simdgroups (256 threads), 4×2 accumulator grid per simdgroup
@[extern "scilean_metal_gemm_m4_f32"]
opaque gemmM4 (m k n : USize) (A B : @& ByteArray) : ByteArray

-- M4-Pro GEMM: Double-buffered with software pipelining
-- REQUIRES: M, N, K are multiples of 64
-- Prefetches next tile while computing current
@[extern "scilean_metal_gemm_m4_pro_f32"]
opaque gemmM4Pro (m k n : USize) (A B : @& ByteArray) : ByteArray

-- M4-Max GEMM: Larger tiles (128×64) for better compute density
-- REQUIRES: M multiple of 128, N, K multiples of 64
-- 16 simdgroups (512 threads), maximum occupancy
@[extern "scilean_metal_gemm_m4_max_f32"]
opaque gemmM4Max (m k n : USize) (A B : @& ByteArray) : ByteArray

-- MPS matrix multiply on GPU (Float32): Apple's Metal Performance Shaders
-- This uses Apple's highly optimized GEMM that leverages the Neural Engine and GPU
@[extern "scilean_metal_gemm_mps_f32"]
Expand Down Expand Up @@ -287,24 +299,14 @@ opaque fill (n : USize) (value : Float32) : ByteArray

-- Fused Operations

-- Softmax: softmax(x) = exp(x - max(x)) / sum(exp(x - max(x)))
-- Currently implemented using multiple GPU passes.
-- Fused Softmax: softmax(x) = exp(x - max(x)) / sum(exp(x - max(x)))
-- Single GPU dispatch with optimized memory access
@[extern "scilean_metal_softmax_f32"]
opaque softmaxFused (n : USize) (x : @& ByteArray) : ByteArray

-- Softmax (multi-pass fallback implementation)
def softmax (sz : USize) (x : ByteArray) : ByteArray :=
-- Find max for numerical stability
let maxVal := reduceMax sz x
-- Create array filled with max value
let maxArr := fill sz maxVal
-- Subtract max: x - max
let shifted := sub sz x maxArr
-- Compute exp using exp2: exp(x) = 2^(x * log2(e)), log2(e) ≈ 1.4427
let log2e : Float32 := (1.4426950408889634 : Float32) -- log2(e)
let log2eArr := fill sz log2e
let scaledShifted := mul sz shifted log2eArr
let expVals := exp2 sz scaledShifted
-- Sum the exp values
let sumVal := reduceSum sz expVals
-- Normalize: exp / sum
let sumArr := fill sz sumVal
div sz expVals sumArr
-- Use fused version if available
softmaxFused sz x

end SciLean.Metal.Float32
75 changes: 75 additions & 0 deletions examples/GEMMComparison.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import SciLean.FFI.Metal
import SciLean.FFI.Float32Array

open SciLean

def benchGemm (name : String) (gemm : USize → USize → USize → ByteArray → ByteArray → ByteArray)
(n : Nat) (numIters : Nat) : IO Unit := do
let amat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)
let bmat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)

-- Warmup
for _ in [:3] do
let _ := gemm n.toUSize n.toUSize n.toUSize amat bmat

-- Benchmark
let mut sizeAccum := 0
let start ← IO.monoNanosNow
for _ in [:numIters] do
let r := gemm n.toUSize n.toUSize n.toUSize amat bmat
sizeAccum := sizeAccum + r.size
let finish ← IO.monoNanosNow

let totalNs := finish - start
let avgNs := totalNs / numIters
let avgMs := avgNs.toFloat / 1_000_000.0
let flops := 2.0 * n.toFloat * n.toFloat * n.toFloat
let gflops := if avgNs > 0 then flops / avgNs.toFloat else 0.0
let tflops := gflops / 1000.0

if tflops >= 1.0 then
IO.println s!" {name}: {avgMs} ms, {tflops} TFLOP/s"
else
IO.println s!" {name}: {avgMs} ms, {gflops} GFLOP/s"

def main : IO Unit := do
IO.println "=== GEMM Kernel Comparison ==="
IO.println "Comparing all available GEMM implementations\n"

for n in [256, 512, 1024, 2048] do
let numIters := if n >= 2048 then 5 else if n >= 1024 then 10 else 20
IO.println s!"Matrix size: {n}×{n} (n={numIters} iterations)"

-- Basic naive GEMM
benchGemm "Naive " Metal.Float32.gemm n numIters

-- Tiled GEMM (32x32 tiles)
benchGemm "Tiled " Metal.Float32.gemmTiled n numIters

-- Simdgroup GEMM (hardware matrix units)
benchGemm "Simd " Metal.Float32.gemmSimd n numIters

-- Optimized simdgroup GEMM
benchGemm "SimdOpt " Metal.Float32.gemmSimdOpt n numIters

-- M4-optimized GEMM (if n is multiple of 64)
if n % 64 == 0 then
benchGemm "M4 " Metal.Float32.gemmM4 n numIters

-- M4-Pro: Double-buffered with software pipelining (if n is multiple of 64)
if n % 64 == 0 then
benchGemm "M4Pro " Metal.Float32.gemmM4Pro n numIters

-- M4-Max: Larger tiles (if m is multiple of 128)
if n % 128 == 0 then
benchGemm "M4Max " Metal.Float32.gemmM4Max n numIters

-- MPS (Metal Performance Shaders)
benchGemm "MPS " Metal.Float32.gemmMPS n numIters

-- Accelerate (CPU AMX)
benchGemm "Accelerate " Metal.Float32.gemmAccelerate n numIters

IO.println ""

IO.println "Done!"
51 changes: 51 additions & 0 deletions examples/GEMMCorrectness.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import SciLean.FFI.Metal
import SciLean.FFI.Float32Array

open SciLean

-- Check if GEMM result is correct using reduceSum
-- For all-ones matrices: C = A * B should have all entries = k, so sum = m*n*k
def checkGemm (name : String) (gemm : USize → USize → USize → ByteArray → ByteArray → ByteArray) (n : Nat) : IO Unit := do
let amat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)
let bmat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)
let cmat := gemm n.toUSize n.toUSize n.toUSize amat bmat

-- Check first element: C[0,0] should be n (dot product of n ones = n)
-- Read first 4 bytes and decode as Float32
let b0 := cmat.get! 0
let b1 := cmat.get! 1
let b2 := cmat.get! 2
let b3 := cmat.get! 3
let bits : UInt32 := b0.toUInt32 ||| (b1.toUInt32 <<< 8) ||| (b2.toUInt32 <<< 16) ||| (b3.toUInt32 <<< 24)

-- C should be n×n matrix with all entries = n, so sum = n*n*n = n³
let expectedSum := (n * n * n).toFloat
let actualSumF32 := Metal.Float32.reduceSum (n * n).toUSize cmat
let actualSum := actualSumF32.toFloat

let relError := if expectedSum > 0 then (actualSum - expectedSum).abs / expectedSum else actualSum.abs

if relError < 0.01 then
IO.println s!" {name}: CORRECT (sum = {actualSum}, expected = {expectedSum}, C[0,0] bits = {bits})"
else
IO.println s!" {name}: FAILED (sum = {actualSum}, expected = {expectedSum}, error = {relError * 100}%, C[0,0] bits = {bits})"

def main : IO Unit := do
IO.println "=== GEMM Correctness Check ==="
IO.println "Computing C = A * B where A, B are all 1s\n"

-- First, test that fill works
IO.println "Testing fill(4, 1.0)..."
let testFill := Metal.Float32.fill 4 (1.0 : Float32)
IO.println s!" Fill result size: {testFill.size} bytes"
IO.println s!" Fill bytes: [{testFill.get! 0}, {testFill.get! 1}, {testFill.get! 2}, {testFill.get! 3}]"
IO.println ""

for n in [4, 8, 64] do
IO.println s!"Matrix size: {n}×{n}"
checkGemm "M4Pro " Metal.Float32.gemmM4Pro n
checkGemm "MPS " Metal.Float32.gemmMPS n
checkGemm "Accelerate " Metal.Float32.gemmAccelerate n
IO.println ""

IO.println "Done!"
52 changes: 52 additions & 0 deletions examples/GEMMFocus.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import SciLean.FFI.Metal
import SciLean.FFI.Float32Array

open SciLean

def benchGemm (name : String) (gemm : USize → USize → USize → ByteArray → ByteArray → ByteArray)
(n : Nat) (numIters : Nat) : IO Unit := do
let amat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)
let bmat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)

-- Warmup
for _ in [:5] do
let _ := gemm n.toUSize n.toUSize n.toUSize amat bmat

-- Benchmark
let mut sizeAccum := 0
let start ← IO.monoNanosNow
for _ in [:numIters] do
let r := gemm n.toUSize n.toUSize n.toUSize amat bmat
sizeAccum := sizeAccum + r.size
let finish ← IO.monoNanosNow

let totalNs := finish - start
let avgNs := totalNs / numIters
let avgMs := avgNs.toFloat / 1_000_000.0
let flops := 2.0 * n.toFloat * n.toFloat * n.toFloat
let gflops := if avgNs > 0 then flops / avgNs.toFloat else 0.0
let tflops := gflops / 1000.0

if tflops >= 1.0 then
IO.println s!" {name}: {avgMs} ms, {tflops} TFLOP/s"
else
IO.println s!" {name}: {avgMs} ms, {gflops} GFLOP/s"

def main : IO Unit := do
IO.println "=== Focused GEMM Analysis ==="
IO.println "Testing M4Pro, MPS, and Accelerate at various sizes\n"

-- Test at power-of-2 sizes from 128 to 4096
for log2n in [7, 8, 9, 10, 11, 12] do
let n := 1 <<< log2n -- 128, 256, 512, 1024, 2048, 4096
let numIters := if n >= 2048 then 10 else if n >= 1024 then 20 else 50
IO.println s!"Matrix size: {n}×{n} ({numIters} iterations)"

-- Compare M4Pro with MPS and Accelerate
if n % 64 == 0 then
benchGemm "M4Pro " Metal.Float32.gemmM4Pro n numIters
benchGemm "MPS " Metal.Float32.gemmMPS n numIters
benchGemm "Accelerate " Metal.Float32.gemmAccelerate n numIters
IO.println ""

IO.println "Done!"
47 changes: 47 additions & 0 deletions examples/LargeGEMM.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import SciLean.FFI.Metal
import SciLean.FFI.Float32Array

open SciLean

def main : IO Unit := do
IO.println "=== Large GEMM Performance Benchmark ==="
IO.println "Warming up..."

-- Extended warmup
for _ in [:50] do
let a := Metal.Float32.fill 4096 (1.0 : Float32)
let b := Metal.Float32.fill 4096 (1.0 : Float32)
let _ := Metal.Float32.gemm 64 64 64 a b

IO.println "Running benchmarks..."

for n in [64, 128, 256, 512, 1024, 2048] do
let amat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)
let bmat := Metal.Float32.fill (n * n).toUSize (1.0 : Float32)

-- More iterations for smaller matrices
let numIters := if n >= 2048 then 5 else if n >= 1024 then 20 else if n >= 512 then 50 else 100

-- Warmup for this size
for _ in [:5] do
let _ := Metal.Float32.gemm n.toUSize n.toUSize n.toUSize amat bmat

-- Time entire loop (like OverheadTest that got realistic numbers)
let mut sizeAccum := 0
let start ← IO.monoNanosNow
for _ in [:numIters] do
let r := Metal.Float32.gemm n.toUSize n.toUSize n.toUSize amat bmat
sizeAccum := sizeAccum + r.size
let finish ← IO.monoNanosNow

let totalNs := finish - start
let avgNs := totalNs / numIters
let avgUs := avgNs.toFloat / 1000.0
let avgMs := avgUs / 1000.0
let flops := 2.0 * n.toFloat * n.toFloat * n.toFloat
let gflops := if avgNs > 0 then flops / avgNs.toFloat else 0.0

IO.println s!"gemm({n}×{n}): {avgMs} ms, {gflops} GFLOP/s (size={sizeAccum})"

IO.println ""
IO.println "Done!"
Loading