IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /get-started.md). For the complete documentation index, see llms.txt.
Skip to main content
For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /get-started.md).

Python module

max.nn

Neural network modules for MAX.

max.nn layers come in two modes. In graph-based execution, a layer’s __call__ stages its operations into a Graph, and MAX compiles the finished graph into an optimized executable that runs on Buffer inputs:

import numpy as np

from max.dtype import DType
from max.engine import InferenceSession
from max.graph import DeviceRef, Graph, TensorType
from max.nn import Linear

input_type = TensorType(DType.float32, ["batch", 64], device=DeviceRef.CPU())
with Graph("layer", input_types=[input_type]) as graph:
    x = graph.inputs[0].tensor
    graph.output(Linear(64, 32, DType.float32, DeviceRef.CPU())(x))

model = InferenceSession().load(
    graph,
    weights_registry={"weight": np.zeros((32, 64), dtype=np.float32)},
)

In eager execution, max.experimental.nn runs the same layer abstractions directly on Tensor values, executing each operation immediately, PyTorch-style.

Submodules​

max.nn.attentionThe attention mechanism used within the model.
max.nn.comm
max.nn.kernelsHelper functions for wrapping custom kv cache/attention related ops.
max.nn.kv_cacheKey-value cache types for MAX layers.
max.nn.moeMixture of Experts (MoE) module.
max.nn.samplingSampling custom ops.
max.nn.state_spacePython wrappers for the state_space Mojo kernel package.

Base classes​

IdentityIdentity layer that passes through input unchanged.
LayerBase class for neural network components.
LayerListStores a list of layers.
MissingLayerHolds the place of a decoder layer another pipeline stage builds.
ModuleBase class for model components with weight management.
SequentialA sequential stack of layers.
ShardableProtocol for objects that support sharding across multiple devices.
SignalsSignal buffers used for peer-to-peer communication in allreduce.

Linear layers​

ColumnParallelLinearA Linear layer where the weight and bias are sharded onto multiple devices.
EmbeddingA lookup table for embedding integer indices into dense vectors.
FusedMLPStores the gate and up projections as one pre-fused weight.
GPTQLinearA Linear layer for GPTQ encoding.
LinearApplies a linear transformation to incoming data: y=xWT+by = xW^T + b.
MLPSimple multi-layer perceptron composed of three Linear layers.
StackedLinearA module that manages multiple linear projections as a stacked weight.
VocabParallelEmbeddingA lookup table for embedding integer indices into dense vectors.

Normalization​

ConstantLayerNormLayer normalization block with constant gamma and beta values.
GroupNormGroup normalization block.
LayerNormLayer normalization over the last dimension.
RMSNormComputes the root mean square normalization on inputs.

Rotary embeddings​

DynamicRotaryEmbeddingApplies RoPE with dynamic scaling for long-context inference.
LinearScalingParamsScaling parameters for linear RoPE frequency scaling.
Llama3RopeScalingParamsScaling parameters for Llama3's frequency-based context extension.
Llama3RotaryEmbeddingApplies RoPE with Llama3-style frequency scaling for extended context lengths.
LongRoPERotaryEmbeddingApplies RoPE with LongRoPE scaling for Phi-3.5 models.
LongRoPEScalingParamsParameters for LongRoPE scaling as used in Phi-3.5 models.
RotaryEmbeddingApplies Rotary Position Embedding (RoPE) to transformer activations.
YarnRotaryEmbeddingApplies generic YaRN (Yet another RoPE eNhancement) Rotary Position Embedding.
YarnScalingParamsScaling parameters for YaRN (Yet another RoPE eNhancement) frequency interpolation.

Transformer​

DistributedTransformerTransformer model consisting for TransformerBlock layers.
DistributedTransformerBlockStack of Attention, FeedForward, and RMSNorm layers.
HyperConnectionMixes hc_mult parallel residual streams around a transformer sublayer.
ReturnHiddenStatesWhich hidden states a transformer model returns per sequence.
ReturnLogitsWhich logits a transformer model returns per sequence.
TransformerA transformer model consisting of TransformerBlock layers.
TransformerBlockStack of Attention, FeedForward, and RMSNorm layers.
DistributedLogitsPostprocessMixinMixin providing logits postprocessing for multi-device sharded models.
LogitsPostprocessMixinMixin providing logits postprocessing for single-device models.
distributed_logits_postprocessCommon logits postprocessing for multi-device sharded models.
forward_sequential_layersForward pass through sequential layers with optional subgraph groups.
logits_postprocessPerforms common logits postprocessing for single-device models.

Convolution​

Conv1DA 1D convolution over an input signal composed of several input planes.
Conv2dA 2D convolution over an input signal composed of several input planes.
Conv3DA 3D convolution over an input signal composed of several input planes.
ConvTranspose1dA 1D transposed convolution operator over an input image composed of several input planes.
WeightNormConvTranspose1dA 1D transposed convolution operator over an input image composed of several input planes.

Mixture of experts​

AllreduceLayer to perform allreduce operation with automatic implementation selection.
EPCommBuffersSHMEM communication buffers for one Expert Parallelism MoE forward pass.
MoEImplementation of Mixture of Experts (MoE).
MoEGateGate module for MoE.
MoEQuantizedMixture of Experts with FP8 or NVFP4 quantization.

Parallelism​

ParallelArrayOpsParallelized numpy array operations for performance-critical data processing.

Sampling​

MinPSamplerA min_p sampler.
RejectionSamplerRejection sampler for speculative decoding verification.
RejectionSamplerWithResidualsA simple rejection sampler.

Quantization​

QuantConfigConfigures scaled quantization settings for a layer or model section.
QuantFormatIdentifies the quantization format of a model checkpoint.
InputScaleSpecSpecifies how input activations are scaled for scaled quantization.
ScaleGranularitySpecifies the granularity of the quantization scale factor.
ScaleOriginSpecifies whether the quantization scale is determined statically or dynamically.
WeightScaleSpecSpecifies how weights are scaled for scaled quantization.

Hooks​

PrintHookHook that prints layer tensor inputs and outputs.
add_layer_hookAdds a hook to call a function after each layer's __call__.
clear_hooksRemove all hooks.

Functions​

build_max_lengths_tensorsBuilds two [1] uint32 scalar buffers of maximum lengths.
clampClamps values in x to [min, max].
forward_moe_sharded_layersForward pass through DP-sharded layers (EP MoE or replicated MLP/MoE).
split_batchSplit a ragged input batch into data parallel batches.
split_batch_replicatedSplit a ragged token batch into data parallel batches.