interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / max-api-surface.md

398 lines · 14836 bytes Raw Blame History Rendered
1# MAX API Surface: Candle/CUDA Replacement Mapping for MojoLlama
2
3## Overview
4
5This document catalogs the MAX framework API surface found in the Modular repository at `/tmp/modular/max/`. It maps Candle/PyTorch/CUDA patterns to their MAX equivalents across the inference engine, graph runtime, kernel compilation, tensor operations, device management, and quantization.
6
7## 1. Inference Engine (`max.engine`)
8
9**File:** `max/python/max/engine/`
10
11| MAX API | Candle/PyTorch Equivalent | Description |
12|---------|---------------------------|-------------|
13| `InferenceSession(devices=[...])` | — | Session manager, analogous to `candle::Device` ownership |
14| `session.load(model_path)` | `torch.jit.load()` | Load + compile a model for inference |
15| `session.compile(model)` | — | Separate compilation from weight binding |
16| `session.init(compiled, weights_registry=...)` | — | Bind weights to compiled model |
17| `Model.execute(*args)` | `model.forward()` | Synchronous inference; returns `list[Buffer]` |
18| `Model.__call__(*args, **kwargs)` | `model(x)` | Python-callable wrapper |
19| `Model.capture(graph_keys, *inputs)` | `torch.cuda.CUDAGraph.capture_begin/end()` | Capture execution as device graph (CUDA Graph) |
20| `Model.replay(graph_keys, *inputs)` | `CUDAGraph.replay()` | Replay captured device graph |
21| `session.gpu_profiling("detailed")` | `nsys profile` | Nsight Systems/Nsight Compute profiling |
22| `TensorSpec(shape, dtype, name)` | — | Describes tensor metadata in graph |
23
24**Candle/CUDA Pattern → MAX:**
25
26```python
27# Candle
28let xs: Tensor = ...
29let ws = candle::nn::Linear::new(...)
30
31# MAX
32session = InferenceSession(devices=[Accelerator()])
33model = session.load("model.mof")
34outputs = model.execute(input_buffer)
35```
36
37## 2. Graph Runtime (`max.graph`)
38
39**File:** `max/python/max/graph/`
40
41### 2.1 Graph Construction
42
43| MAX API | Candle/PyTorch Equivalent |
44|---------|---------------------------|
45| `Graph(name, input_types=..., forward=...)` | `nn.Module.__init__` + `forward()` |
46| `Graph.__enter__()` / `__exit__()` | Context manager for graph building |
47| `graph.inputs[i].tensor` | Model input tensor |
48| `graph.output(...)` | Sets graph output |
49| `graph.add_weight(Weight(...))` | `nn.Parameter` |
50| `graph.add_subgraph(name, ...)` | Subgraph / function-like block |
51| `ops.custom(name, device, values, out_types)` | `torch.ops.custom_op` |
52| `ops.call(subgraph, ...)` | Call a subgraph |
53| `Module` | Multi-graph container for compilation |
54
55### 2.2 Graph Operations (`max.graph.ops`)
56
57#### Linear Algebra
58
59| MAX Graph Op | Candle Op | PyTorch Op |
60|---|---|---|
61| `ops.matmul` | `candle::Tensor::matmul` | `torch.matmul` / `@` |
62| `ops.add`, `ops.sub`, `ops.mul`, `ops.div` | Element-wise arithmetic | `+`, `-`, `*`, `/` |
63| `ops.transpose` | `.t()` | `torch.transpose` |
64| `ops.permute` | `.permute()` | `torch.permute` |
65| `ops.reshape` | `.reshape()` | `torch.reshape` |
66| `ops.broadcast_to` | `.broadcast()` | `torch.broadcast_to` |
67| `ops.cast` | `.to_dtype()` | `.to(dtype)` |
68| `ops.concat` | `candle::Tensor::cat` | `torch.cat` |
69| `ops.stack` | — | `torch.stack` |
70| `ops.split` | `.split()` | `torch.split` |
71| `ops.squeeze`/`ops.unsqueeze` | `.squeeze()`/`.unsqueeze()` | `torch.squeeze/unsqueeze` |
72
73#### Neural Network
74
75| MAX Graph Op | Candle/PyTorch |
76|---|---|
77| `ops.softmax` | `F.softmax` |
78| `ops.gelu` | `F.gelu` |
79| `ops.silu` | `F.silu` (SwiGLU) |
80| `ops.sigmoid` | `F.sigmoid` |
81| `ops.tanh` | `F.tanh` |
82| `ops.relu` (via `maximum(x,0)`) | `F.relu` |
83| `ops.layer_norm` | `F.layer_norm` |
84| `ops.rms_norm` | Custom RMSNorm |
85| `ops.group_norm` | `F.group_norm` |
86| `ops.sum`, `ops.mean`, `ops.prod` | reductions |
87| `ops.argmax`, `ops.argmin` | `argmax`/`argmin` |
88| `ops.top_k` | `torch.topk` |
89| `ops.where` | `torch.where` |
90| `ops.gather` | `torch.gather` |
91| `ops.scatter` | `torch.scatter` |
92| `ops.pad` | `F.pad` |
93| `ops.concat` | `torch.cat` |
94| `ops.conv2d`, `ops.conv3d` | `F.conv2d/3d` |
95| `ops.avg_pool2d`, `ops.max_pool2d` | `F.avg/max_pool2d` |
96| `ops.repeat_interleave` | `torch.repeat_interleave` |
97
98#### Quantized Operations
99
100| MAX Graph Op | Description |
101|---|---|
102| `ops.qmatmul(encoding, config, lhs, *rhs)` | Quantized matrix multiply (Q4_0, Q4_K, Q6_K, GPTQ) |
103| `ops.dequantize(encoding, quantized)` | Dequantize GGUF-style weights |
104| `repack_gguf_quantized_weights(weight, encoding)` | Repack GGUF weights for optimized matmul |
105
106## 3. Neural Network Layers (`max.nn`)
107
108**File:** `max/python/max/nn/`
109
110| MAX Layer | Candle/PyTorch Equivalent |
111|-----------|---------------------------|
112| `nn.Linear(in_dim, out_dim, ...)` | `candle::nn::Linear` / `nn.Linear` |
113| `nn.Embedding(vocab_size, hidden_dim)` | `candle::nn::Embedding` / `nn.Embedding` |
114| `nn.RMSNorm(dim, eps, ...)` | Llama RMSNorm |
115| `nn.LayerNorm(dims, eps, ...)` | `nn.LayerNorm` |
116| `nn.GroupNorm` | `nn.GroupNorm` |
117| `nn.RotaryEmbedding` | RoPE |
118| `nn.AttentionWithRope(...)` | MHA + RoPE (Llama-style) |
119| `nn.MultiheadAttention` | `nn.MultiheadAttention` |
120| `nn.GPTQAttentionWithRope` | GPTQ-quantized attention |
121| `nn.KVCacheParams` | KV cache config |
122| `nn.VocabParallelEmbedding` | Distributed embedding |
123| `nn.ColumnParallelLinear` | Tensor parallelism linear |
124| `nn.MoE`, `nn.MoEGate` | Mixture-of-Experts |
125| `nn.MLP` | MLP block |
126| `Module` (base class) | `nn.Module` |
127| `LayerList` / `Sequential` | `nn.Sequential` |
128
129### KV Cache
130
131| MAX Component | Description |
132|---|---|
133| `KVCacheParams` | Configuration (dtype, nheads, cache_size) |
134| `KVCacheInputs` | Input types for cache operations |
135| `PagedCacheValues` | Paged cache implementation |
136| `KVCacheMetrics` | Cache hit/miss statistics |
137
138## 4. Device Management (`max.driver`)
139
140**File:** `max/python/max/driver/`
141
142| MAX API | Candle/PyTorch | Description |
143|---------|-----------------|-------------|
144| `CPU()` | `Device::Cpu` | Host device |
145| `Accelerator(id=0)` | `Device::Cuda(0)` | GPU accelerator device |
146| `DeviceStream(device)` | `cudaStream_t` | Device execution stream |
147| `Buffer(dtype, shape, device)` | `candle::Tensor` storage | Device buffer / tensor storage |
148| `Buffer.to(device)` | `.to_device()` | Device transfer |
149| `Buffer.from_numpy(arr)` | `Tensor::from_slice` | Import numpy data |
150| `Buffer.to_numpy()` | `.to_vec2()` | Export to numpy |
151| `Buffer.from_dlpack(obj)` | DLPack interop | Import via DLPack |
152| `Buffer.mmap(path, ...)` | — | Memory-map file as buffer |
153| `DeviceSpec(id, device_type)` | — | Device specification tuple |
154| `accelerator_count()` | — | Count available GPUs |
155| `scan_available_devices()` | — | Enumerate devices |
156
157**Candle → MAX Device Pattern:**
158
159```python
160# Candle
161let device = Device::Cuda(0);
162
163# MAX
164from max.driver import Accelerator, Buffer, CPU
165device = Accelerator(0)
166cpu = CPU()
167buffer_on_gpu = Buffer(dtype, shape, device)
168buffer_on_cpu = buffer_on_gpu.to(cpu)
169```
170
171## 5. Mojo Kernels (`max/kernels/src/`)
172
173### 5.1 Linear Algebra Kernels
174
175**Directory:** `max/kernels/src/linalg/`
176
177| Kernel File | Functionality |
178|-------------|---------------|
179| `matmul/` | High-performance GEMM (CPU: vnni/neon/apple, GPU: sm80/sm90/sm100, AMD) |
180| `bmm.mojo` | Batched matrix multiply |
181| `gemv.mojo` | Matrix-vector multiply |
182| `grouped_matmul.mojo` | Grouped batched matmul (MoE dispatch) |
183| `transpose.mojo` | Matrix transpose |
184| `fp8_quantization.mojo` | FP8 quantization/dequantization |
185| `fp4_quantization.mojo` | FP4 quantization (MXFP4) |
186| `accumulate.mojo` | Accumulation operations |
187| `packing.mojo` | Weight packing utilities |
188| `lora.mojo` | LoRA matrix operations |
189
190### 5.2 Neural Network Kernels
191
192**Directory:** `max/kernels/src/nn/`
193
194| Kernel File | Candle/CUDA Equivalent |
195|-------------|------------------------|
196| `softmax.mojo` | `candle::ops::softmax` |
197| `normalization.mojo` | Layer/RMS norm |
198| `activations.mojo` | GELU, SiLU, etc. |
199| `rope.mojo` | RoPE implementation |
200| `topk.mojo` | Top-K sampling |
201| `sampling.mojo` | Token sampling (top-p, min-p) |
202| `moe.mojo` | Mixture-of-Experts |
203| `kv_cache.mojo` | KV cache operations |
204| `kv_cache_ragged.mojo` | Ragged (variable-length) KV cache |
205| `attention/` | Flash attention kernels (MHA, MLA) |
206| `conv/` | Convolution (2D, 3D, transposed) |
207| `broadcast.mojo` | Tensor broadcasting |
208| `concat.mojo` | Concatenation |
209| `slice.mojo` | Slicing |
210| `split.mojo` | Splitting |
211| `reshape.mojo` | Reshaping |
212| `pad.mojo` | Padding |
213| `pool.mojo` | Pooling |
214
215### 5.3 Quantization Kernels
216
217**Directory:** `max/kernels/src/quantization/`
218
219| Kernel | Description |
220|--------|-------------|
221| `per_channel_grouped_4bit.mojo` | Per-channel grouped 4-bit quant matmul |
222| `qmatmul.mojo` | Q4_0 quantized matmul (CPU) |
223| `qmatmul_gpu.mojo` | Q4_0 quantized matmul (GPU) |
224| `qmatmul_k.mojo` | Q4_K/Q6_K quantized matmul |
225
226### 5.4 Attention Kernels
227
228**Directory:** `max/kernels/src/nn/attention/gpu/`
229
230| Kernel | Description |
231|--------|-------------|
232| `nvidia/sm90/mha.mojo` | Multi-head attention SM90 (H100) |
233| `nvidia/sm100/attention.mojo` | Flash attention SM100 (B200) |
234| `nvidia/sm100/mla_decode.mojo` | Multi-head Latent Attention decode (DeepSeek) |
235| `nvidia/sm100/mla_prefill.mojo` | MLA prefill |
236| `nvidia/sm100/mha_depth512/` | Depth-512 flash attention |
237| `amd_rdna/mha_decode.mojo` | AMD attention decode |
238| `amd_structured/mha_decode.mojo` | AMD structured attention |
239
240### 5.5 Vendor Library Bindings
241
242| Directory | Vendor Library |
243|-----------|---------------|
244| `_cublas/` | NVIDIA cuBLAS + cuBLASLt |
245| `_cudnn/` | NVIDIA cuDNN |
246| `_cufft/` | NVIDIA cuFFT |
247| `_curand/` | NVIDIA cuRAND |
248| `_rocblas/` | AMD rocBLAS + hipBLASLt |
249| `_miopen/` | AMD MIOpen |
250
251### 5.6 Communication Kernels
252
253**Directory:** `max/kernels/src/comm/`
254
255| Kernel | Description |
256|--------|-------------|
257| `allreduce.mojo` | All-reduce |
258| `allgather.mojo` | All-gather |
259| `reducescatter.mojo` | Reduce-scatter |
260| `broadcast.mojo` | Broadcast |
261| `scatter.mojo` | Scatter |
262| `sync.mojo` | Synchronization |
263| `device_query.mojo` | Device property query |
264
265### 5.7 State Space Model Kernels
266
267**Directory:** `max/kernels/src/state_space/`
268
269| Kernel | Description |
270|--------|-------------|
271| `selective_scan.mojo` | Mamba selective scan |
272| `causal_conv1d.mojo` | Causal 1D convolution (Mamba) |
273| `rms_norm_fused_residual.mojo` | Fused RMSNorm + residual |
274
275## 6. Custom Ops / Kernel Compilation
276
277### 6.1 Python: `max.graph.ops.custom`
278
279Register and call custom Mojo kernels from Python graphs:
280
281```python
282result = ops.custom(
283 name="my_kernel", # matches @compiler.register("my_kernel")
284 device=Accelerator(0),
285 values=[input_tensor],
286 out_types=[TensorType(DType.float32, [M, N], device=Accelerator(0))],
287 parameters={"param": 42},
288)
289```
290
291### 6.2 Mojo: `@compiler.register` (Kernel Authoring)
292
293Custom kernels are written in Mojo and registered with the compiler:
294
295```mojo
296from compiler import register
297
298@register("my_kernel")
299fn my_kernel[
300 dtype: DType,
301 rank: Int,
302](input: ManagedTensorSlice[dtype, rank], output: ManagedTensorSlice[dtype, rank]):
303 # Kernel body
304 ...
305```
306
307Located in: `max/examples/custom_ops/kernels/`
308
309### 6.3 Mojo Tensor Extensibility API
310
311**Directory:** `max/kernels/src/extensibility/tensor/`
312
313| API | Description |
314|-----|-------------|
315| `RuntimeTensorSpec[dtype, rank]` | Compile-time tensor spec |
316| `ManagedTensorSlice[dtype, rank]` | Managed tensor view for custom ops |
317| `InputTensor`, `OutputTensor` | Input/output tensor declarations |
318| `ElementwiseUnaryOp`, `ElementwiseBinaryOp` | Operation traits for auto-generated kernels |
319| `IOSpec`, `Input`, `Output`, `FusedInput`, `FusedOutput` | I/O specification for custom ops |
320| `StaticTensorSpec`, `StaticTensorSpecList` | Static tensor specs |
321
322### 6.4 Kernel Library Loading
323
324```python
325from max.graph import KernelLibrary
326
327kernels = KernelLibrary([Path("my_kernels.mojoc")])
328# Or from source
329kernels.load_paths([Path("kernels/")])
330```
331
332## 7. DType Support (`max.dtype`)
333
334| `DType` Enum | NumPy Equivalent | Description |
335|---|---|---|
336| `DType.bool` | `np.bool_` | Boolean |
337| `DType.int8` .. `DType.int64` | `np.int*` | Signed integers |
338| `DType.uint8` .. `DType.uint64` | `np.uint*` | Unsigned integers |
339| `DType.float8_e4m3fn` | — | FP8 (E4M3) |
340| `DType.float8_e5m2` | — | FP8 (E5M2) |
341| `DType.float16` | `np.float16` | FP16 |
342| `DType.bfloat16` | — | BF16 |
343| `DType.float32` | `np.float32` | FP32 (default) |
344| `DType.float64` | `np.float64` | FP64 |
345
346## 8. C API (`max/include/max/c/`)
347
348For C/C++ integration (e.g., from Rust via FFI):
349
350| Header | Key Functions |
351|--------|---------------|
352| `tensor.h` | `M_newTensorSpec()`, `M_borrowTensorInto()`, `M_getTensorByNameFrom()`, `M_copyTensorToDevice()` |
353| `device.h` | `M_newDevice()`, `M_getAcceleratorCount()`, `M_synchronizeDevice()` |
354| `context.h` | `M_newRuntimeContext()`, `M_newRuntimeConfig()` |
355| `model.h` | `M_compileModel()`, `M_executeModelSync()`, `M_captureModelSync()`, `M_replayModelSync()` |
356| `weights.h` | `M_newWeightsRegistry()` |
357
358## 9. Pipeline Architectures (`max/pipelines/architectures/`)
359
360Pre-built model architectures (analogous to HuggingFace `transformers`):
361
362| Architecture | Models |
363|---|---|
364| `llama3/` | Llama 3, Llama 3.1, Llama 3.2 |
365| `qwen3/`, `qwen2/` | Qwen 3, Qwen 2.5 |
366| `deepseekV2/`, `deepseekV3/` | DeepSeek V2, V3, R1 |
367| `mistral/`, `mistral3/` | Mistral v0.1, v0.2, v0.3, Mistral 3 |
368| `gemma3/`, `gemma4/` | Gemma 3, Gemma 4 |
369| `phi3/` | Phi-3 |
370| `olmo/`, `olmo2/`, `olmo3/` | OLMo family |
371| `bert/` | BERT |
372| `clip/` | CLIP |
373| `whisper/` | Whisper |
374| `mamba/` | Mamba SSM |
375| `flux2/` | Flux image generation |
376| `wan/` | Video generation |
377
378## 10. Key Replacements Summary
379
380| Candle/CUDA Pattern | MAX Replacement | Where |
381|---------------------|----------------|-------|
382| `candle::Tensor::from_slice` | `Buffer.from_numpy()` | `max.driver` |
383| `tensor.to_device()` | `Buffer.to()` | `max.driver` |
384| `candle::nn::Linear` | `nn.Linear` | `max.nn` |
385| `candle::nn::Embedding` | `nn.Embedding` | `max.nn` |
386| `tensor.matmul()` | `ops.matmul` | `max.graph.ops` |
387| `candle::quantized::Q4Matmul` | `ops.qmatmul` | `max.graph.ops` |
388| `candle::attention::Attention` | `nn.AttentionWithRope` | `max.nn` |
389| `CUDA kernels` | Mojo `@compiler.register` | `max/kernels/src/` |
390| `nvcc / CUDA C++` | Mojo `gpu` module | `max/kernels/src/` |
391| `cudaStream_t` | `DeviceStream` | `max.driver` |
392| `torch.cuda.CUDAGraph` | `Model.capture`/`Model.replay` | `max.engine` |
393| `ggml` quant types (Q4_0..Q6_K) | `QuantizationEncoding` | `max.graph.quantization` |
394| `cudaMemcpy` | `Buffer.inplace_copy_from` | `max.driver` |
395| `torch.jit.script` | `Graph` + compile | `max.graph` + `max.engine` |
396| NCCL all-reduce | `ops.allreduce` | `max.graph.ops` |
397
398**File created:** `/onedev-workspace/work/max-api-surface.md`