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 Source

MAX API Surface: Candle/CUDA Replacement Mapping for MojoLlama

Overview

This 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.

1. Inference Engine (max.engine)

File: max/python/max/engine/

MAX APICandle/PyTorch EquivalentDescription
InferenceSession(devices=[...])—Session manager, analogous to candle::Device ownership
session.load(model_path)torch.jit.load()Load + compile a model for inference
session.compile(model)—Separate compilation from weight binding
session.init(compiled, weights_registry=...)—Bind weights to compiled model
Model.execute(*args)model.forward()Synchronous inference; returns list[Buffer]
Model.__call__(*args, **kwargs)model(x)Python-callable wrapper
Model.capture(graph_keys, *inputs)torch.cuda.CUDAGraph.capture_begin/end()Capture execution as device graph (CUDA Graph)
Model.replay(graph_keys, *inputs)CUDAGraph.replay()Replay captured device graph
session.gpu_profiling("detailed")nsys profileNsight Systems/Nsight Compute profiling
TensorSpec(shape, dtype, name)—Describes tensor metadata in graph

Candle/CUDA Pattern → MAX:

# Candle
let xs: Tensor = ...
let ws = candle::nn::Linear::new(...)

# MAX
session = InferenceSession(devices=[Accelerator()])
model = session.load("model.mof")
outputs = model.execute(input_buffer)

2. Graph Runtime (max.graph)

File: max/python/max/graph/

2.1 Graph Construction

MAX APICandle/PyTorch Equivalent
Graph(name, input_types=..., forward=...)nn.Module.__init__ + forward()
Graph.__enter__() / __exit__()Context manager for graph building
graph.inputs[i].tensorModel input tensor
graph.output(...)Sets graph output
graph.add_weight(Weight(...))nn.Parameter
graph.add_subgraph(name, ...)Subgraph / function-like block
ops.custom(name, device, values, out_types)torch.ops.custom_op
ops.call(subgraph, ...)Call a subgraph
ModuleMulti-graph container for compilation

2.2 Graph Operations (max.graph.ops)

Linear Algebra

MAX Graph OpCandle OpPyTorch Op
ops.matmulcandle::Tensor::matmultorch.matmul / @
ops.add, ops.sub, ops.mul, ops.divElement-wise arithmetic+, -, *, /
ops.transpose.t()torch.transpose
ops.permute.permute()torch.permute
ops.reshape.reshape()torch.reshape
ops.broadcast_to.broadcast()torch.broadcast_to
ops.cast.to_dtype().to(dtype)
ops.concatcandle::Tensor::cattorch.cat
ops.stack—torch.stack
ops.split.split()torch.split
ops.squeeze/ops.unsqueeze.squeeze()/.unsqueeze()torch.squeeze/unsqueeze

Neural Network

MAX Graph OpCandle/PyTorch
ops.softmaxF.softmax
ops.geluF.gelu
ops.siluF.silu (SwiGLU)
ops.sigmoidF.sigmoid
ops.tanhF.tanh
ops.relu (via maximum(x,0))F.relu
ops.layer_normF.layer_norm
ops.rms_normCustom RMSNorm
ops.group_normF.group_norm
ops.sum, ops.mean, ops.prodreductions
ops.argmax, ops.argminargmax/argmin
ops.top_ktorch.topk
ops.wheretorch.where
ops.gathertorch.gather
ops.scattertorch.scatter
ops.padF.pad
ops.concattorch.cat
ops.conv2d, ops.conv3dF.conv2d/3d
ops.avg_pool2d, ops.max_pool2dF.avg/max_pool2d
ops.repeat_interleavetorch.repeat_interleave

Quantized Operations

MAX Graph OpDescription
ops.qmatmul(encoding, config, lhs, *rhs)Quantized matrix multiply (Q4_0, Q4_K, Q6_K, GPTQ)
ops.dequantize(encoding, quantized)Dequantize GGUF-style weights
repack_gguf_quantized_weights(weight, encoding)Repack GGUF weights for optimized matmul

3. Neural Network Layers (max.nn)

File: max/python/max/nn/

MAX LayerCandle/PyTorch Equivalent
nn.Linear(in_dim, out_dim, ...)candle::nn::Linear / nn.Linear
nn.Embedding(vocab_size, hidden_dim)candle::nn::Embedding / nn.Embedding
nn.RMSNorm(dim, eps, ...)Llama RMSNorm
nn.LayerNorm(dims, eps, ...)nn.LayerNorm
nn.GroupNormnn.GroupNorm
nn.RotaryEmbeddingRoPE
nn.AttentionWithRope(...)MHA + RoPE (Llama-style)
nn.MultiheadAttentionnn.MultiheadAttention
nn.GPTQAttentionWithRopeGPTQ-quantized attention
nn.KVCacheParamsKV cache config
nn.VocabParallelEmbeddingDistributed embedding
nn.ColumnParallelLinearTensor parallelism linear
nn.MoE, nn.MoEGateMixture-of-Experts
nn.MLPMLP block
Module (base class)nn.Module
LayerList / Sequentialnn.Sequential

KV Cache

MAX ComponentDescription
KVCacheParamsConfiguration (dtype, nheads, cache_size)
KVCacheInputsInput types for cache operations
PagedCacheValuesPaged cache implementation
KVCacheMetricsCache hit/miss statistics

4. Device Management (max.driver)

File: max/python/max/driver/

MAX APICandle/PyTorchDescription
CPU()Device::CpuHost device
Accelerator(id=0)Device::Cuda(0)GPU accelerator device
DeviceStream(device)cudaStream_tDevice execution stream
Buffer(dtype, shape, device)candle::Tensor storageDevice buffer / tensor storage
Buffer.to(device).to_device()Device transfer
Buffer.from_numpy(arr)Tensor::from_sliceImport numpy data
Buffer.to_numpy().to_vec2()Export to numpy
Buffer.from_dlpack(obj)DLPack interopImport via DLPack
Buffer.mmap(path, ...)—Memory-map file as buffer
DeviceSpec(id, device_type)—Device specification tuple
accelerator_count()—Count available GPUs
scan_available_devices()—Enumerate devices

Candle → MAX Device Pattern:

# Candle
let device = Device::Cuda(0);

# MAX
from max.driver import Accelerator, Buffer, CPU
device = Accelerator(0)
cpu = CPU()
buffer_on_gpu = Buffer(dtype, shape, device)
buffer_on_cpu = buffer_on_gpu.to(cpu)

5. Mojo Kernels (max/kernels/src/)

5.1 Linear Algebra Kernels

Directory: max/kernels/src/linalg/

Kernel FileFunctionality
matmul/High-performance GEMM (CPU: vnni/neon/apple, GPU: sm80/sm90/sm100, AMD)
bmm.mojoBatched matrix multiply
gemv.mojoMatrix-vector multiply
grouped_matmul.mojoGrouped batched matmul (MoE dispatch)
transpose.mojoMatrix transpose
fp8_quantization.mojoFP8 quantization/dequantization
fp4_quantization.mojoFP4 quantization (MXFP4)
accumulate.mojoAccumulation operations
packing.mojoWeight packing utilities
lora.mojoLoRA matrix operations

5.2 Neural Network Kernels

Directory: max/kernels/src/nn/

Kernel FileCandle/CUDA Equivalent
softmax.mojocandle::ops::softmax
normalization.mojoLayer/RMS norm
activations.mojoGELU, SiLU, etc.
rope.mojoRoPE implementation
topk.mojoTop-K sampling
sampling.mojoToken sampling (top-p, min-p)
moe.mojoMixture-of-Experts
kv_cache.mojoKV cache operations
kv_cache_ragged.mojoRagged (variable-length) KV cache
attention/Flash attention kernels (MHA, MLA)
conv/Convolution (2D, 3D, transposed)
broadcast.mojoTensor broadcasting
concat.mojoConcatenation
slice.mojoSlicing
split.mojoSplitting
reshape.mojoReshaping
pad.mojoPadding
pool.mojoPooling

5.3 Quantization Kernels

Directory: max/kernels/src/quantization/

KernelDescription
per_channel_grouped_4bit.mojoPer-channel grouped 4-bit quant matmul
qmatmul.mojoQ4_0 quantized matmul (CPU)
qmatmul_gpu.mojoQ4_0 quantized matmul (GPU)
qmatmul_k.mojoQ4_K/Q6_K quantized matmul

5.4 Attention Kernels

Directory: max/kernels/src/nn/attention/gpu/

KernelDescription
nvidia/sm90/mha.mojoMulti-head attention SM90 (H100)
nvidia/sm100/attention.mojoFlash attention SM100 (B200)
nvidia/sm100/mla_decode.mojoMulti-head Latent Attention decode (DeepSeek)
nvidia/sm100/mla_prefill.mojoMLA prefill
nvidia/sm100/mha_depth512/Depth-512 flash attention
amd_rdna/mha_decode.mojoAMD attention decode
amd_structured/mha_decode.mojoAMD structured attention

5.5 Vendor Library Bindings

DirectoryVendor Library
_cublas/NVIDIA cuBLAS + cuBLASLt
_cudnn/NVIDIA cuDNN
_cufft/NVIDIA cuFFT
_curand/NVIDIA cuRAND
_rocblas/AMD rocBLAS + hipBLASLt
_miopen/AMD MIOpen

5.6 Communication Kernels

Directory: max/kernels/src/comm/

KernelDescription
allreduce.mojoAll-reduce
allgather.mojoAll-gather
reducescatter.mojoReduce-scatter
broadcast.mojoBroadcast
scatter.mojoScatter
sync.mojoSynchronization
device_query.mojoDevice property query

5.7 State Space Model Kernels

Directory: max/kernels/src/state_space/

KernelDescription
selective_scan.mojoMamba selective scan
causal_conv1d.mojoCausal 1D convolution (Mamba)
rms_norm_fused_residual.mojoFused RMSNorm + residual

6. Custom Ops / Kernel Compilation

6.1 Python: max.graph.ops.custom

Register and call custom Mojo kernels from Python graphs:

result = ops.custom(
    name="my_kernel",           # matches @compiler.register("my_kernel")
    device=Accelerator(0),
    values=[input_tensor],
    out_types=[TensorType(DType.float32, [M, N], device=Accelerator(0))],
    parameters={"param": 42},
)

6.2 Mojo: @compiler.register (Kernel Authoring)

Custom kernels are written in Mojo and registered with the compiler:

from compiler import register

@register("my_kernel")
fn my_kernel[
    dtype: DType,
    rank: Int,
](input: ManagedTensorSlice[dtype, rank], output: ManagedTensorSlice[dtype, rank]):
    # Kernel body
    ...

Located in: max/examples/custom_ops/kernels/

6.3 Mojo Tensor Extensibility API

Directory: max/kernels/src/extensibility/tensor/

APIDescription
RuntimeTensorSpec[dtype, rank]Compile-time tensor spec
ManagedTensorSlice[dtype, rank]Managed tensor view for custom ops
InputTensor, OutputTensorInput/output tensor declarations
ElementwiseUnaryOp, ElementwiseBinaryOpOperation traits for auto-generated kernels
IOSpec, Input, Output, FusedInput, FusedOutputI/O specification for custom ops
StaticTensorSpec, StaticTensorSpecListStatic tensor specs

6.4 Kernel Library Loading

from max.graph import KernelLibrary

kernels = KernelLibrary([Path("my_kernels.mojoc")])
# Or from source
kernels.load_paths([Path("kernels/")])

7. DType Support (max.dtype)

DType EnumNumPy EquivalentDescription
DType.boolnp.bool_Boolean
DType.int8 .. DType.int64np.int*Signed integers
DType.uint8 .. DType.uint64np.uint*Unsigned integers
DType.float8_e4m3fn—FP8 (E4M3)
DType.float8_e5m2—FP8 (E5M2)
DType.float16np.float16FP16
DType.bfloat16—BF16
DType.float32np.float32FP32 (default)
DType.float64np.float64FP64

8. C API (max/include/max/c/)

For C/C++ integration (e.g., from Rust via FFI):

HeaderKey Functions
tensor.hM_newTensorSpec(), M_borrowTensorInto(), M_getTensorByNameFrom(), M_copyTensorToDevice()
device.hM_newDevice(), M_getAcceleratorCount(), M_synchronizeDevice()
context.hM_newRuntimeContext(), M_newRuntimeConfig()
model.hM_compileModel(), M_executeModelSync(), M_captureModelSync(), M_replayModelSync()
weights.hM_newWeightsRegistry()

9. Pipeline Architectures (max/pipelines/architectures/)

Pre-built model architectures (analogous to HuggingFace transformers):

ArchitectureModels
llama3/Llama 3, Llama 3.1, Llama 3.2
qwen3/, qwen2/Qwen 3, Qwen 2.5
deepseekV2/, deepseekV3/DeepSeek V2, V3, R1
mistral/, mistral3/Mistral v0.1, v0.2, v0.3, Mistral 3
gemma3/, gemma4/Gemma 3, Gemma 4
phi3/Phi-3
olmo/, olmo2/, olmo3/OLMo family
bert/BERT
clip/CLIP
whisper/Whisper
mamba/Mamba SSM
flux2/Flux image generation
wan/Video generation

10. Key Replacements Summary

Candle/CUDA PatternMAX ReplacementWhere
candle::Tensor::from_sliceBuffer.from_numpy()max.driver
tensor.to_device()Buffer.to()max.driver
candle::nn::Linearnn.Linearmax.nn
candle::nn::Embeddingnn.Embeddingmax.nn
tensor.matmul()ops.matmulmax.graph.ops
candle::quantized::Q4Matmulops.qmatmulmax.graph.ops
candle::attention::Attentionnn.AttentionWithRopemax.nn
CUDA kernelsMojo @compiler.registermax/kernels/src/
nvcc / CUDA C++Mojo gpu modulemax/kernels/src/
cudaStream_tDeviceStreammax.driver
torch.cuda.CUDAGraphModel.capture/Model.replaymax.engine
ggml quant types (Q4_0..Q6_K)QuantizationEncodingmax.graph.quantization
cudaMemcpyBuffer.inplace_copy_frommax.driver
torch.jit.scriptGraph + compilemax.graph + max.engine
NCCL all-reduceops.allreducemax.graph.ops

File created: /onedev-workspace/work/max-api-surface.md