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

Module framework for models built on max.tensor.

Provides the Module base class, the module_dataclass() decorator, and Module.compile(), which traces forward against symbolic inputs and returns an ahead-of-time-compiled CompiledCallable. The same forward body runs eagerly, traces to a Graph, or compiles, depending on the active realization context.

Example:

from max.driver import CPU
from max.dtype import DType
from max.tensor import Tensor, default_device
from max.nn import Module, module_dataclass
from max.graph import TensorType

@module_dataclass
class MyLayer(Module):
    weight: Tensor
    bias: Tensor

    def forward(self, x: Tensor) -> Tensor:
        return x @ self.weight.T + self.bias

with default_device(CPU()):
    model = MyLayer(weight=Tensor.zeros([10, 5]), bias=Tensor.zeros([10]))
    y = model(Tensor.ones([3, 5]))

    input_type = TensorType(DType.float32, ["batch", 5], device=model.device)
    compiled = model.compile(input_type)
    result = compiled(Tensor.ones([3, 5]))

Submodules​

max.nn.epExpert parallelism over a device mesh.
max.nn.kernelsMAX kernels as Tensor ops.
max.nn.kv_cacheKey-value cache types for MAX layers.
max.nn.legacyNeural network modules for MAX.
max.nn.normNormalization layers for MAX neural networks.
max.nn.ropePositional embedding modules and functions.

Base classes​

ModuleThe core unit of composition for modeling in MAX.
ModuleDictA Module subclass that stores child modules by string key.
ModuleListA Module subclass which is locally a list container.
PinnedDeviceTensorType alias for a Tensor parameter that Module.to will leave on its current device.
SequentialA Module that applies its children in sequence.
TransparentModuleA Module that drops its own name from its descendants' paths.

Linear layers​

ColumnParallelLinearA linear layer whose weight is sharded across its output features.
Conv2dA 2D convolution layer.
EmbeddingA vector embedding.
LinearA unary linear transformation over an input tensor.
QKVLinearA fused q/k/v projection with two checkpoint layouts.
RowParallelLinearA linear layer whose weight is sharded across its input features.
col_parallelShards a linear layer's weight across its output features.
row_parallelShards a linear layer's weight across its input features.

Attention and rotary embeddings​

AttentionWithRopeImplementation of attention that uses Rotary Position Embedding (RoPE).
RotaryEmbeddingRotaryEmbedding layer to calculate and apply the frequency tensor for complex exponentials.
YarnRotaryEmbeddingGeneric YaRN (Yet another RoPE eNhancement) Rotary Position Embedding layer.

LoRA​

LoRAWraps a projection module with an additive multi-adapter LoRA term.
lora_layersYields (qualified_name, layer) for every LoRA in model.
lora_parametersYields (qualified_name, slot) for every adapter stack in model.

Hyper-connection​

HyperConnectionMixes hc_mult parallel residual streams around a transformer sublayer.

Functions​

as_subgraphTraces a function into a subgraph once and calls it from every call site.
module_dataclassApplies dataclass() to a Module subclass.

Mesh axes​

DCPMesh axis name for decode context parallelism.
DPMesh axis name for data parallelism.
EPMesh axis name for expert parallelism.
TPMesh axis name for tensor parallelism.
dcp_axisReturns the index of the mesh axis a DCP group spans.

Context parallelism​

PCP_MAX_BATCH_CONTEXTA step takes the PCP path only while every replica's page-aligned summed context is at most this many tokens.
PCP_MIN_ROWS_PER_REQUESTA step takes the PCP path when its rows average more than this per request.
PCP_MIN_STEP_TOKENSA step takes the PCP path only with at least this many rows.
check_dcp_meshRaises unless DCP groups of dcp ranks tile the attention TP axis.
combine_partial_attentionMerges each rank's partial attention and returns its own heads.
dcp_group_headsReturns the query heads each DCP group of mesh attends.
dcp_rank_tensorReturns each device's DCP rank as an int32 [1] device tensor.
dcp_ranksReturns each device's rank in its DCP group, for call_on_mesh.
dcp_viewReturns mesh with its attention TP axis split into DCP groups.
gather_columnsAll-gathers each rank's [T, c] columns into [T, dcp * c].
merge_topkReturns each rank's share of the group-wide top-k as one selection.
split_selectionSplits a packed selection into its rows and [T] counts.
to_dcp_meshMoves t between a mesh and its DCP view, moving no data.

Mixture of experts​

SumsOverDevicesA feed-forward block whose devices may each hold a partial result.
moe_forwardRuns a feed-forward block on h and returns its output placed as h.

Quantized tensors​

FP8BlockActivationFP8 block-quantized activation tensor.
FP8BlockTensorFP8 block-scaled quantized tensor.
MXFP4TensorMXFP4 (OCP microscaling) block-scaled quantized tensor.
MXFP8ActivationMXFP8-quantized activation tensor, rows sorted by expert.
MXFP8TensorMXFP8 (OCP microscaling) block-scaled quantized tensor.
NVFP4ActivationNVFP4-quantized activation tensor.
NVFP4TensorNVFP4 (modelopt) block-scaled quantized tensor.
QTensorBase class for quantized tensor wrappers.
QuantAwareTensorA weight that a quantized layer accepts.

KV cache inputs​

PagedCacheValuesDistributed view of KV cache inputs.
TensorLikeOne device's shard of a cache field: a graph value, or a single-device tensor in the graph being built.
cache_tensorReturns one cache input's shards as a tensor, keeping real ones.
kv_input_valuesReturns a decoder's KV cache inputs for its params to unflatten.
per_device_cachesReturns a decoder's KV cache inputs as one record per device.