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.pipelines.architectures.llama3

Llama 3 transformer architecture for text generation.

Llama3BatchProcessor​

class max.pipelines.architectures.llama3.Llama3BatchProcessor(config, runtime, inputs=())

source

Bases: Llama3BatchProcessorBase[Llama3Inputs]

Ragged batching for models whose inputs are Llama3Inputs.

Parameters:

Llama3Config​

class max.pipelines.architectures.llama3.Llama3Config(*, hidden_size, num_attention_heads, num_key_value_heads, num_hidden_layers, rope_theta, rope_scaling_params, max_seq_len, intermediate_size, interleaved_rope_weights, vocab_size, dtype, model_quantization_encoding, quantization_config, kv_params, return_logits=ReturnLogits.LAST_TOKEN, norm_method='rms_norm', norm_dtype=None, attention_bias=False, rms_norm_eps=None, tie_word_embeddings=False, stacked_mlp=False, stacked_qkv=False, attention_multiplier, embedding_multiplier, residual_multiplier, devices, clip_qkv, quant_config=None, longrope_scaling_params=None, logits_scaling=1.0, return_hidden_states=ReturnHiddenStates.NONE, target_layer_ids=None, use_subgraphs=True, data_parallel_degree=1, sliding_window=None, quantization_encoding=None)

source

Bases: ArchConfigWithStoredKVParams, ArchConfigWithKVCache

Model configuration for Llama3 graph construction/execution.

Parameters:

DEFAULT_ENCODING​

DEFAULT_ENCODING: ClassVar[SupportedEncoding] = 'q4_k'

source

SUPPORTED_ENCODINGS​

SUPPORTED_ENCODINGS: ClassVar[set[SupportedEncoding]] = {'bfloat16', 'float32', 'float4_e2m1fnx2', 'float8_e4m3fn', 'gptq', 'q4_0', 'q4_k', 'q6_k'}

source

attention_bias​

attention_bias: bool = False

source

attention_multiplier​

attention_multiplier: float

source

calculate_attention_multiplier()​

static calculate_attention_multiplier(huggingface_config)

source

The attention multiplier is a scalar that scales the attention scores.

It is used to control the variance of the attention scores.

This function is used to get the attention multiplier from the huggingface config. If the attention multiplier is not set, it will be calculated as the square root of 1.0 divided by the head dimension.

Parameters:

huggingface_config (AutoConfig)

Return type:

float

clip_qkv​

clip_qkv: float | None

source

construct_kv_params()​

classmethod construct_kv_params(huggingface_config, pipeline_config, devices, kv_cache_config, cache_dtype, *, allow_kv_head_replication=False)

source

Grouped-attention KV with EAGLE draft-token count when speculative is on.

allow_kv_head_replication lets subclasses with fewer KV heads than the tensor-parallel width replicate each head across a device group.

Parameters:

Return type:

KVCacheParams

data_parallel_degree​

data_parallel_degree: int = 1

source

devices​

devices: list[DeviceRef]

source

dtype​

dtype: DType

source

embedding_multiplier​

embedding_multiplier: float

source

finalize()​

finalize(huggingface_config, state_dict, return_logits, return_hidden_states=ReturnHiddenStates.NONE, norm_method='rms_norm', attention_bias=False)

source

Define parameters that can’t be determined just from the pipeline config.

Parameters:

Return type:

None

get_num_layers()​

static get_num_layers(huggingface_config)

source

The checkpoint’s hidden layer count.

Parameters:

huggingface_config (AutoConfig)

Return type:

int

hidden_size​

hidden_size: int

source

initialize()​

classmethod initialize(pipeline_config, model_config=None, *, max_seq_len)

source

Initialize the config from a PipelineConfig.

Parameters:

  • pipeline_config (PipelineConfig) – The pipeline configuration.
  • model_config (MAXModelConfig | None) – The model configuration to read from. When None (the default), pipeline_config.model is used. Pass an explicit config (such as pipeline_config.draft_model) to initialize the arch config for a different model.
  • max_seq_len (int) – The effective maximum sequence length to store on the config. The value is received, never derived here: the pipeline model passes the memory plan’s VRAM-clamped length, while memory planning (which runs before a plan exists) passes the construction-resolved model_config.max_length. Configs whose sequence length is pure model metadata (such as diffusion components) ignore it.

Return type:

Self

initialize_from_config()​

classmethod initialize_from_config(pipeline_config, huggingface_config, model_config=None, *, max_seq_len)

source

Builds the config from the pipeline and HF configs.

Parameters:

Return type:

Self

interleaved_rope_weights​

interleaved_rope_weights: bool

source

intermediate_size​

intermediate_size: int

source

kv_params​

kv_params: KVCacheParams

source

logits_scaling​

logits_scaling: float = 1.0

source

longrope_scaling_params​

longrope_scaling_params: LongRoPEScalingParams | None = None

source

max_seq_len​

max_seq_len: int

source

model_quantization_encoding​

model_quantization_encoding: QuantizationEncoding | None

source

norm_dtype​

norm_dtype: DType | None = None

source

norm_method​

norm_method: Literal['rms_norm', 'layer_norm'] = 'rms_norm'

source

num_attention_heads​

num_attention_heads: int

source

num_hidden_layers​

num_hidden_layers: int

source

num_key_value_heads​

num_key_value_heads: int

source

quant_config​

quant_config: QuantConfig | None = None

source

quantization_config​

quantization_config: QuantizationConfig | None

source

quantization_encoding​

quantization_encoding: SupportedEncoding | None = None

source

residual_multiplier​

residual_multiplier: float

source

return_hidden_states​

return_hidden_states: ReturnHiddenStates = 'none'

source

return_logits​

return_logits: ReturnLogits = 'last_token'

source

rms_norm_eps​

rms_norm_eps: float | None = None

source

rope_scaling_params​

rope_scaling_params: Llama3RopeScalingParams | None

source

rope_theta​

rope_theta: float

source

sliding_window​

sliding_window: int | None = None

source

stacked_mlp​

stacked_mlp: bool = False

source

stacked_qkv​

stacked_qkv: bool = False

source

target_layer_ids​

target_layer_ids: list[int] | None = None

source

tie_word_embeddings​

tie_word_embeddings: bool = False

source

use_subgraphs​

use_subgraphs: bool = True

source

vocab_size​

vocab_size: int

source

Llama3Inputs​

class max.pipelines.architectures.llama3.Llama3Inputs(tokens, input_row_offsets, signal_buffers, return_n_logits, data_parallel_splits=None, *, kv_cache_inputs=None, lora_buffers=(), vision_embeddings=<factory>, vision_scatter_indices=<factory>, hidden_states=None)

source

Bases: ModelInputs

A class representing inputs for the Llama3 model.

This class encapsulates the input tensors required for the Llama3 model execution.

Parameters:

buffers​

property buffers: tuple[Buffer, ...]

source

The step’s buffers, in the graph’s input order.

data_parallel_splits​

data_parallel_splits: Buffer | Sequence[Sequence[int]] | None = None

source

Tensor containing the data parallel splits.

input_row_offsets​

input_row_offsets: Buffer

source

Tensor containing the offsets for each row in the ragged input sequence.

return_n_logits​

return_n_logits: Buffer

source

signal_buffers​

signal_buffers: list[Buffer]

source

Device buffers used for synchronization in communication collectives.

tokens​

tokens: Buffer

source

Tensor containing the input token IDs.

LlamaModelBase​

class max.pipelines.architectures.llama3.LlamaModelBase(pipeline_config, session, devices, kv_cache_config, weights, *, memory_plan, adapter=None, return_logits=ReturnLogits.LAST_TOKEN, return_hidden_states=ReturnHiddenStates.NONE, max_batch_size=1)

source

Bases: LogProbabilitiesMixin, GraphPipelineModelWithKVCache[TextContext, Any]

Base Llama pipeline model implementation.

Initializes the pipeline model.

Parameters:

  • pipeline_config (PipelineConfig) – The configuration for this pipeline.
  • session (InferenceSession) – The container for the runtime for this model.
  • devices (list[Device]) – The devices the model runs on.
  • kv_cache_config (KVCacheConfig) – The KV cache configuration.
  • weights (Weights) – The checkpoint’s weights.
  • memory_plan (MemoryPlan) – The memory plan the model was sized against.
  • adapter (WeightsAdapter | None) – Rewrites the checkpoint’s weight names, when given.
  • return_logits (ReturnLogits) – Which logits the graph returns.
  • return_hidden_states (ReturnHiddenStates) – Which hidden states the graph returns.
  • max_batch_size (int) – The largest batch the graph handles.

attention_bias​

attention_bias: bool = False

source

Whether to use attention bias.

batch_processor_cls​

batch_processor_cls

source

alias of Llama3BatchProcessor

execute()​

execute(model_inputs)

source

Runs the model and returns its outputs.

Parameters:

model_inputs (ModelInputs)

Return type:

ModelOutputs

graph_specs()​

graph_specs(model_config)

source

Returns the decoder’s graph spec.

It is data-parallel when the config asks for it, tensor-parallel across several devices otherwise, or single-device.

Parameters:

model_config (Any)

Return type:

dict[str, GraphSpec]

load_graphs()​

load_graphs(session)

source

Compiles and initializes the graphs graph_specs() returns.

Sets up the distributed runtime with _init_distributed_runtime first, since the graphs depend on it, and wires the batch processor with _wire_batch_processor after.

Parameters:

session (InferenceSession) – The session that compiles and initializes the graphs.

Returns:

The initialized models, keyed by role.

Return type:

dict[str, Model]

load_model()​

load_model(session)

source

Loads the decoder graph graph_specs() returns.

A subclass that still overrides _build_graph_for_compile loads through that hook instead.

Parameters:

session (InferenceSession) – The session that compiles and initializes the graph.

Returns:

The initialized decoder.

Return type:

Model

model​

model: Model

source

Compiled and initialized model ready for inference.

model_config_cls​

model_config_cls

source

alias of Llama3Config

norm_method​

norm_method: Literal['rms_norm', 'layer_norm']

source

Normalization layer.

prepare_initial_token_inputs()​

prepare_initial_token_inputs(replica_batches, kv_cache_inputs=None, return_n_logits=1)

source

Delegates to the batch processor and narrows to Llama3Inputs.

Parameters:

Return type:

Llama3Inputs

state_dict​

state_dict: dict[str, Any]

source

Weights to load into the model.