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
Fix large batch NaN bug with broadcast biasAdd kernel
Root cause: GpuBuffer.add was reading batchSize*10 elements from
a 10-element bias buffer, causing garbage memory reads and NaN.

Changes:
- Add bias_add Metal kernel with proper broadcast semantics (gid % stride)
- Add type-safe CpuBuffer/GpuBuffer API (no implicit coercions)
- Add Float.inf/negInf definitions via IEEE 754 division by zero
- Update GpuMNIST to use biasAdd for output layer bias

Training now achieves 92.1% accuracy on 10k samples.
  • Loading branch information
alok committed Dec 17, 2025
commit d3ea5f322bd34b591ed10deeabc507eca22b9edb
16 changes: 16 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,19 @@ SciLean uses dependent types (`Float^[784]`, `Float^[128, 784]`) wrapping comput
- Make heavy use of metaprogramming for tactics and automation
- Clear distinction between forward and reverse mode differentiation in naming
- Add existing imports as comments when disabling them

## TODO (for future sessions)
- Reenable doc.verso

## Lean 4 Tips
- **Float infinity**: Lean 4 stdlib doesn't have `Float.inf`. Define as:
```lean
def Float.inf : Float := 1.0 / 0.0
def Float.negInf : Float := -1.0 / 0.0
```
These are proper IEEE 754 infinity values for min/max tracking.

---

use lean-lsp-mcp hover on nested src code after writing it to ENSURE its in
the right namespace. like `Float.inf` may need to be `_root_.Float.inf`.
16 changes: 16 additions & 0 deletions Metal/kmeans.metal
Original file line number Diff line number Diff line change
Expand Up @@ -1366,6 +1366,22 @@ kernel void bias_gelu(
}
}

// Add bias only (no activation) - for output layer before softmax
// Broadcasts bias across batch dimension: output[i] = input[i] + bias[i % stride]
kernel void bias_add(
device const float* input [[buffer(0)]],
device const float* bias [[buffer(1)]],
device float* output [[buffer(2)]],
constant uint& n [[buffer(3)]],
constant uint& stride [[buffer(4)]],
uint gid [[thread_position_in_grid]]
) {
if (gid < n) {
uint bias_idx = gid % stride;
output[gid] = input[gid] + bias[bias_idx];
}
}

// Fused layer norm: y = (x - mean) / sqrt(var + eps) * gamma + beta
// This is a simplified version for vectors (no batch dimension)
kernel void layer_norm(
Expand Down
64 changes: 64 additions & 0 deletions Metal/metal_backend.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1192,6 +1192,70 @@ LEAN_EXPORT lean_obj_res scilean_gpu_bias_gelu_f32(
}
}

// Bias add (no activation) on GPU buffers
// Broadcasts bias across batch dimension: output[i] = input[i] + bias[i % stride]
// Used for output layer before softmax where we don't want activation
LEAN_EXPORT lean_obj_res scilean_gpu_bias_add_f32(
b_lean_obj_arg X_buf,
b_lean_obj_arg bias_buf,
size_t n,
size_t stride,
lean_obj_arg /* world */
) {
if (!ensure_metal_initialized()) {
return lean_io_result_mk_error(lean_mk_string("Metal not available"));
}

id<MTLBuffer> X = get_mtl_buffer(X_buf);
id<MTLBuffer> bias = get_mtl_buffer(bias_buf);
if (!X || !bias) {
return lean_io_result_mk_error(lean_mk_string("Invalid GpuBuffer"));
}

@autoreleasepool {
id<MTLComputePipelineState> pipeline = get_pipeline(@"bias_add");
if (!pipeline) {
return lean_io_result_mk_error(lean_mk_string("Failed to get bias_add pipeline"));
}

size_t output_size = n * sizeof(float);
id<MTLBuffer> Y = get_pooled_buffer(output_size);
if (!Y) {
Y = [device newBufferWithLength:output_size options:MTLResourceStorageModeShared];
}

uint32_t n32 = (uint32_t)n;
uint32_t stride32 = (uint32_t)stride;

// Use batch encoder if in batch mode
bool batched = is_batch_mode();
id<MTLCommandBuffer> commandBuffer = batched ? g_batch_command_buffer : [commandQueue commandBuffer];
id<MTLComputeCommandEncoder> encoder = batched ? g_batch_encoder : [commandBuffer computeCommandEncoder];

[encoder setComputePipelineState:pipeline];
[encoder setBuffer:X offset:0 atIndex:0];
[encoder setBuffer:bias offset:0 atIndex:1];
[encoder setBuffer:Y offset:0 atIndex:2];
[encoder setBytes:&n32 length:sizeof(n32) atIndex:3];
[encoder setBytes:&stride32 length:sizeof(stride32) atIndex:4];

MTLSize gridSize = MTLSizeMake(n, 1, 1);
NSUInteger tgSize = MIN(pipeline.maxTotalThreadsPerThreadgroup, n);
[encoder dispatchThreads:gridSize threadsPerThreadgroup:MTLSizeMake(tgSize, 1, 1)];

if (!batched) {
[encoder endEncoding];
[commandBuffer commit];
[commandBuffer waitUntilCompleted];
} else {
[g_batch_outputs addObject:Y];
}

lean_obj_res result = wrap_gpu_buffer(Y, output_size);
return lean_io_result_mk_ok(result);
}
}

// Average pooling 2D on GPU buffers
// Supports batching: when in batch mode, queues to shared command buffer
LEAN_EXPORT lean_obj_res scilean_gpu_avgpool2d_f32(
Expand Down
110 changes: 88 additions & 22 deletions SciLean/FFI/Metal.lean
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ matrix (gemv, gemm variants), fill, kmeans.
Performance on M4: gemmSimd ~10 TFLOP/s, gemmTiled ~6 TFLOP/s at 2048x2048.
-/

import SciLean.FFI.Float32Array
import SciLean.Util.Float

namespace SciLean.Metal

/-! ## Core -/
Expand All @@ -22,26 +25,7 @@ opaque isAvailable : Unit → Bool
def withGPU [Inhabited α] (gpuFn cpuFn : Unit → α) : α :=
if isAvailable () then gpuFn () else cpuFn ()

/-! ## GPU-Resident Buffers

GPU-resident buffers stay on the GPU between operations, eliminating the overhead
of copying data to/from CPU memory on every operation. This is critical for
performance in ML workloads where data flows through many operations.

Usage pattern:
```
-- Upload once
let weights ← GpuBuffer.fromByteArray weightData
let input ← GpuBuffer.fromByteArray inputData

-- Chain operations on GPU (no copies!)
let h1 ← GpuBuffer.gemm weights input m k n
let h2 ← GpuBuffer.relu h1

-- Download only final result
let output ← h2.toByteArray
```
-/
/-! ## GPU-Resident Buffers -/

/-! ## Command Buffer Batching

Expand Down Expand Up @@ -99,11 +83,11 @@ namespace GpuBuffer
@[extern "scilean_gpu_alloc_f32"]
opaque alloc (numFloats : USize) : IO GpuBuffer

/-- Upload ByteArray (Float32 data) to GPU -/
/-- Upload ByteArray (Float32 data) to GPU (low-level, prefer `CpuBuffer.upload` for type safety) -/
@[extern "scilean_gpu_upload_f32"]
opaque fromByteArray (data : @& ByteArray) : IO GpuBuffer

/-- Download GPU buffer to ByteArray -/
/-- Download GPU buffer to ByteArray (low-level, prefer `GpuBuffer.download` for type safety) -/
@[extern "scilean_gpu_download_f32"]
opaque toByteArray (buf : @& GpuBuffer) : IO ByteArray

Expand Down Expand Up @@ -185,6 +169,13 @@ opaque layerNorm (x gamma beta : @& GpuBuffer) (n hiddenSize : USize) : IO GpuBu
@[extern "scilean_gpu_bias_gelu_f32"]
opaque biasGelu (x bias : @& GpuBuffer) (n stride : USize) : IO GpuBuffer

/-- Bias + add (no activation): y = x + bias (broadcast)
For output layer before softmax where we don't want activation.
n = total elements, stride = bias size (broadcast across batch).
Supports batching. -/
@[extern "scilean_gpu_bias_add_f32"]
opaque biasAdd (x bias : @& GpuBuffer) (n stride : USize) : IO GpuBuffer

/-- Average pooling 2D
Supports batching. -/
@[extern "scilean_gpu_avgpool2d_f32"]
Expand Down Expand Up @@ -286,6 +277,81 @@ opaque colSum (x : @& GpuBuffer) (rows cols : USize) : IO GpuBuffer

end GpuBuffer

/-! ## Type-Safe CPU/GPU Buffer System

Data transfer between CPU and GPU is a major performance bottleneck. This type system
makes transfers **explicit** at the type level - no implicit coercions allowed!

- `CpuBuffer` - CPU-resident data (wrapper around ByteArray)
- `GpuBuffer` - GPU-resident data (opaque Metal buffer handle)

To transfer data, you MUST use explicit functions:
- `CpuBuffer.upload : CpuBuffer → IO GpuBuffer` (CPU → GPU)
- `GpuBuffer.download : GpuBuffer → IO CpuBuffer` (GPU → CPU)

This prevents accidental data transfers that kill performance. GPU operations only
accept `GpuBuffer`, CPU operations only accept `CpuBuffer`.

Usage pattern:
```lean
-- Load data on CPU
let cpuWeights : CpuBuffer := ⟨weightData⟩
let cpuInput : CpuBuffer := ⟨inputData⟩

-- Explicit upload to GPU
let gpuWeights ← cpuWeights.upload
let gpuInput ← cpuInput.upload

-- Chain operations on GPU (no copies! type system enforces this)
let h1 ← GpuBuffer.gemm gpuWeights gpuInput m k n
let h2 ← GpuBuffer.relu h1

-- Explicit download when needed
let cpuOutput ← h2.download
let outputBytes := cpuOutput.data -- access underlying ByteArray
```
-/

/-- CPU-resident buffer. Wrapper around ByteArray that prevents implicit conversion to GpuBuffer.
Use `.upload` to explicitly move data to GPU. -/
structure CpuBuffer where
/-- The underlying raw byte data (Float32 format) -/
data : ByteArray
deriving Inhabited

namespace CpuBuffer

/-- Size in bytes -/
@[inline] def sizeBytes (buf : CpuBuffer) : Nat := buf.data.size

/-- Size in Float32 elements -/
@[inline] def numFloats (buf : CpuBuffer) : Nat := buf.data.size / 4

/-- Create a zero-initialized CPU buffer with n Float32 elements -/
def zeros (n : Nat) : CpuBuffer :=
⟨ByteArray.replicateFloat32 n 0.0⟩

/-- Upload CPU buffer to GPU. This is an EXPLICIT transfer operation. -/
def upload (buf : CpuBuffer) : IO GpuBuffer :=
GpuBuffer.fromByteArray buf.data

end CpuBuffer

namespace GpuBuffer

/-- Download GPU buffer to CPU. This is an EXPLICIT transfer operation.
Returns a type-safe CpuBuffer wrapper. -/
def download (buf : GpuBuffer) : IO CpuBuffer := do
let data ← toByteArray buf
return ⟨data⟩

end GpuBuffer

-- IMPORTANT: No `Coe CpuBuffer GpuBuffer` instance!
-- IMPORTANT: No `Coe CpuBuffer ByteArray` instance!
-- IMPORTANT: No `Coe ByteArray CpuBuffer` instance!
-- All transfers must be explicit.

/-! ## Matrix Operations -/

-- Matrix-vector multiply on GPU: y = A * x. A is m x n, x is n-dim, returns m-dim y
Expand Down
12 changes: 12 additions & 0 deletions SciLean/Util/Float.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/-
Float utilities for SciLean

Lean 4 stdlib doesn't provide Float.inf/negInf, so we define them here
using IEEE 754 division by zero semantics.
-/

/-- IEEE 754 positive infinity -/
def Float.inf : Float := 1.0 / 0.0

/-- IEEE 754 negative infinity -/
def Float.negInf : Float := -1.0 / 0.0
Loading