For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /max/get-started.md).
Python module
max.pipelines.architectures.qwen3_5
Qwen3_5Configβ
class max.pipelines.architectures.qwen3_5.Qwen3_5Config(*, 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, lora_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, layer_types=<factory>, full_attention_interval=4, linear_key_head_dim=128, linear_value_head_dim=128, linear_num_key_heads=16, linear_num_value_heads=48, linear_conv_kernel_dim=4, partial_rotary_factor=0.25, attn_output_gate=True, mamba_ssm_dtype=float32, vision_config=None, image_token_id=None, video_token_id=None, vision_start_token_id=None, mrope_section=None)
Bases: Llama3Config
Configuration for Qwen3.5 hybrid attention models.
Qwen3.5 uses a hybrid architecture with both full (standard) attention and linear attention (Gated DeltaNet) layers. Every full_attention_interval-th layer uses full attention, and the rest use linear attention.
-
Parameters:
-
- hidden_size (int)
- num_attention_heads (int)
- num_key_value_heads (int)
- num_hidden_layers (int)
- rope_theta (float)
- rope_scaling_params (Llama3RopeScalingParams | None)
- max_seq_len (int)
- intermediate_size (int)
- interleaved_rope_weights (bool)
- vocab_size (int)
- dtype (DType)
- model_quantization_encoding (QuantizationEncoding | None)
- quantization_config (QuantizationConfig | None)
- kv_params (KVCacheParams)
- return_logits (ReturnLogits)
- norm_method (Literal['rms_norm', 'layer_norm'])
- norm_dtype (DType | None)
- attention_bias (bool)
- rms_norm_eps (float | None)
- tie_word_embeddings (bool)
- stacked_mlp (bool)
- stacked_qkv (bool)
- attention_multiplier (float)
- embedding_multiplier (float)
- residual_multiplier (float)
- devices (list[DeviceRef])
- clip_qkv (float | None)
- quant_config (QuantConfig | None)
- lora_config (LoRAConfig | None)
- longrope_scaling_params (LongRoPEScalingParams | None)
- logits_scaling (float)
- return_hidden_states (ReturnHiddenStates)
- target_layer_ids (list[int] | None)
- use_subgraphs (bool)
- data_parallel_degree (int)
- sliding_window (int | None)
- layer_types (list[str])
- full_attention_interval (int)
- linear_key_head_dim (int)
- linear_value_head_dim (int)
- linear_num_key_heads (int)
- linear_num_value_heads (int)
- linear_conv_kernel_dim (int)
- partial_rotary_factor (float)
- attn_output_gate (bool)
- mamba_ssm_dtype (DType)
- vision_config (VisionConfig | None)
- image_token_id (int | None)
- video_token_id (int | None)
- vision_start_token_id (int | None)
- mrope_section (list[int] | None)
attn_output_gateβ
attn_output_gate: bool = True
Whether full attention layers use a sigmoid output gate.
calculate_attention_multiplier()β
static calculate_attention_multiplier(huggingface_config)
Compute attention scaling factor using explicit head_dim.
-
Parameters:
-
huggingface_config (AutoConfig)
-
Return type:
construct_kv_params()β
static construct_kv_params(huggingface_config, pipeline_config, devices, kv_cache_config, cache_dtype)
Construct KV cache parameters for full attention layers only.
Only allocates KV cache entries for full-attention layers; linear attention layers use separate conv/recurrent state buffers instead. The forward pass maps each full-attention layer to a sequential KV cache index (0, 1, 2, β¦) independent of the absolute layer index.
-
Parameters:
-
- huggingface_config (AutoConfig)
- pipeline_config (PipelineConfig)
- devices (list[DeviceRef])
- kv_cache_config (KVCacheConfig)
- cache_dtype (DType)
-
Return type:
full_attention_intervalβ
full_attention_interval: int = 4
Every N-th layer uses full attention.
get_num_layers()β
static get_num_layers(huggingface_config)
Layer count for the decoder stack (override when HF uses a different field).
-
Parameters:
-
huggingface_config (AutoConfig)
-
Return type:
image_token_idβ
Token ID used for image placeholders in the input sequence.
infer_optimal_batch_size()β
infer_optimal_batch_size(devices, *, weights_size, device_memory_utilization)
Return a memory-safe default max_batch_size for this architecture.
Qwen3.5 stores GatedDeltaNet conv and recurrent state in a single
max_batch x per_req pool that the slot-indexed SSM kernels
mutate in place. There are no working copies, so peak footprint is
max_batch x per_req bytes.
We split the post-weights utilization budget evenly: the state pool
gets up to half, the KV cache absorbs the rest. This uses the same
device_memory_utilization headroom factor as the rest of the
pipeline, and matches the estimate_activation_memory() reservation.
Falls back to 32βsafe for the 27B model on H100/A100 (80 GB)βwhen the device query fails.
initialize()β
classmethod initialize(pipeline_config, model_config=None)
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.modelis used. Pass an explicit config (e.g.pipeline_config.draft_model) to initialize the arch config for a different model.
-
Return type:
initialize_from_config()β
classmethod initialize_from_config(pipeline_config, huggingface_config, model_config=None)
Initialize config from pipeline and HuggingFace configurations.
Handles both multimodal (Qwen3_5ForConditionalGeneration) and text-only (Qwen3_5ForCausalLM) configs by extracting the text config.
-
Parameters:
-
- pipeline_config (PipelineConfig)
- huggingface_config (AutoConfig)
- model_config (MAXModelConfig | None)
-
Return type:
layer_typesβ
βfull_attentionβ or βlinear_attentionβ.
-
Type:
-
Per-layer attention type
linear_conv_kernel_dimβ
linear_conv_kernel_dim: int = 4
Causal conv1d kernel size for linear attention layers.
linear_key_head_dimβ
linear_key_head_dim: int = 128
Key head dimension for linear attention layers.
linear_num_key_headsβ
linear_num_key_heads: int = 16
Number of key heads for linear attention layers.
linear_num_value_headsβ
linear_num_value_heads: int = 48
Number of value heads for linear attention layers.
linear_value_head_dimβ
linear_value_head_dim: int = 128
Value head dimension for linear attention layers.
mamba_ssm_dtypeβ
mamba_ssm_dtype: DType = 81
Dtype for SSM (state space model) computations in linear attention layers.
mrope_sectionβ
MRoPE section lengths for multimodal rotary position encoding.
partial_rotary_factorβ
partial_rotary_factor: float = 0.25
Fraction of head_dim that gets rotary position embedding.
video_token_idβ
Token ID used for video placeholders in the input sequence.
vision_configβ
vision_config: VisionConfig | None = None
Vision encoder configuration; None for text-only models.
vision_start_token_idβ
Token ID that marks the start of vision content.
Qwen3_5Inputsβ
class max.pipelines.architectures.qwen3_5.Qwen3_5Inputs(tokens, input_row_offsets, signal_buffers, return_n_logits, data_parallel_splits=None, slot_idx=None, conv_pools=None, recurrent_pools=None, request_ids=None, image_token_indices=None, pixel_values=None, vision_position_ids=None, weights=None, indices=None, max_grid_size=None, grid_thw=None, cu_seqlens=None, max_seqlen=None, lm_image_embeddings=None, *, kv_cache_inputs=None, lora=None, hidden_states=None)
Bases: Llama3Inputs
Inputs for Qwen3.5 including linear attention states and optional vision inputs.
-
Parameters:
-
- tokens (Buffer)
- input_row_offsets (Buffer)
- signal_buffers (list[Buffer])
- return_n_logits (Buffer)
- data_parallel_splits (Buffer | Sequence[Sequence[int]] | None)
- slot_idx (Buffer | None)
- conv_pools (list[Buffer] | None)
- recurrent_pools (list[Buffer] | None)
- request_ids (list[RequestID] | None)
- image_token_indices (Buffer | None)
- pixel_values (Buffer | None)
- vision_position_ids (Buffer | None)
- weights (Buffer | None)
- indices (Buffer | None)
- max_grid_size (Buffer | None)
- grid_thw (Buffer | None)
- cu_seqlens (Buffer | None)
- max_seqlen (Buffer | None)
- lm_image_embeddings (Buffer | None)
- kv_cache_inputs (KVCacheInputs[Buffer, Buffer] | None)
- lora (LoRAInputs | None)
- hidden_states (Buffer | list[Buffer] | None)
buffersβ
Returns positional Buffer inputs for model ABI calls.
conv_poolsβ
Per-layer mutable conv pool, [max_slots, conv_dim, K-1].
cu_seqlensβ
Cumulative sequence lengths for vision full attention.
grid_thwβ
Grid dimensions (temporal, height, width) per image, shape (n_images, 3).
has_vision_inputsβ
property has_vision_inputs: bool
True when pixel values are available for vision encoding.
image_token_indicesβ
Pre-computed scatter indices for image embeddings.
indicesβ
Bilinear interpolation indices for vision position embeddings.
lm_image_embeddingsβ
Image embeddings for the LM graph (empty [0, H] buffer for decode/text-only steps, real embeddings for prefill steps with images). Must be non-None for multimodal models.
max_grid_sizeβ
Maximum grid size (CPU scalar) for vision attention.
max_seqlenβ
Maximum sequence length (CPU scalar) for vision attention.
pixel_valuesβ
Raw pixel values for vision encoding.
recurrent_poolsβ
Per-layer mutable recurrent pool, [max_slots, nv, KD, VD].
request_idsβ
Request IDs for this batch, used to manage per-request state cache slots.
slot_idxβ
Per-batch [B] uint32 slot indices into the linear-attention pools.
vision_position_idsβ
Rotary position IDs for the vision encoder.
weightsβ
Bilinear interpolation weights for vision position embeddings.
Qwen3_5Modelβ
class max.pipelines.architectures.qwen3_5.Qwen3_5Model(pipeline_config, session, devices, kv_cache_config, weights, adapter=None, return_logits=ReturnLogits.LAST_TOKEN, return_hidden_states=ReturnHiddenStates.NONE)
Bases: AlwaysSignalBuffersMixin, LlamaModelBase
Qwen3.5 pipeline model implementation.
Supports the hybrid linear/full attention architecture with KV cache for full attention layers and conv/recurrent states for linear layers.
-
Parameters:
-
- pipeline_config (PipelineConfig) β The configuration for this pipeline.
- session (InferenceSession) β The container for the runtime for this model.
- devices (list[Device])
- kv_cache_config (KVCacheConfig)
- weights (Weights)
- adapter (WeightsAdapter | None)
- return_logits (ReturnLogits)
- return_hidden_states (ReturnHiddenStates)
attention_biasβ
attention_bias: bool = False
Whether to use attention bias.
calculate_max_seq_len()β
classmethod calculate_max_seq_len(pipeline_config, huggingface_config)
Calculates the optimal max sequence length for the model.
Default implementation delegates to model_config_cls. Override when
pipeline-model semantics differ from the config (for example, bounding
max_length where the config is permissive).
-
Parameters:
-
- pipeline_config (PipelineConfig) β Configuration for the pipeline.
- huggingface_config (AutoConfig) β Hugging Face model configuration.
-
Returns:
-
The maximum sequence length to use.
-
Return type:
execute()β
execute(model_inputs)
Executes the graph with the given inputs.
-
Parameters:
-
model_inputs (ModelInputs) β The model inputs to execute, containing tensors and any other required data for model execution.
-
Returns:
-
ModelOutputs containing the pipelineβs output tensors.
-
Return type:
This is an abstract method that must be implemented by concrete PipelineModels to define their specific execution logic.
load_model()β
load_model(session)
-
Parameters:
-
session (InferenceSession)
-
Return type:
modelβ
model: Model
Compiled and initialized model ready for inference.
model_config_clsβ
model_config_cls
alias of Qwen3_5Config
norm_methodβ
norm_method: Literal['rms_norm'] | Literal['layer_norm'] = 'rms_norm'
Normalization layer.
prepare_initial_token_inputs()β
prepare_initial_token_inputs(replica_batches, kv_cache_inputs=None, return_n_logits=1)
Prepare the inputs for the first pass in multistep execution.
-
Parameters:
-
- replica_batches (Sequence[Sequence[TextContext]])
- kv_cache_inputs (KVCacheInputs[Buffer, Buffer] | None)
- return_n_logits (int)
-
Return type:
release()β
release(request_id)
Release per-request state cache slot when a request completes.
-
Parameters:
-
request_id (RequestID)
-
Return type:
-
None
state_dictβ
Weights to load into the model.
vision_modelβ
Qwen3_5ReasoningParserβ
class max.pipelines.architectures.qwen3_5.Qwen3_5ReasoningParser(think_start_token_id, think_end_token_id, tool_call_start_token_id=None)
Bases: ReasoningParser
Qwen 3.5 / 3.6 reasoning parser for <think>...</think> sections.
Qwen 3.5/3.6βs chat template prepends <think>\n to every assistant
turn when enable_thinking is true (the default), so reasoning
begins implicitly without an explicit <think> token in the model
output stream. Reasoning ends explicitly at </think>, or
implicitly when a tool call begins (<tool_call>) β the tool-call
marker is left in the content region for the tool parser to consume.
-
Parameters:
from_tokenizer()β
async classmethod from_tokenizer(tokenizer)
Construct a reasoning parser from a tokenizer.
-
Parameters:
-
tokenizer (PipelineTokenizer[Any, Any, Any])
-
Return type:
reasoning_end_token_id()β
async classmethod reasoning_end_token_id(tokenizer)
Returns the </think> token id that closes a reasoning span.
-
Parameters:
-
tokenizer (PipelineTokenizer[Any, Any, Any])
-
Return type:
-
int | None
stream()β
stream(delta_token_ids, is_currently_reasoning=True)
Identify a reasoning span within a streaming delta chunk.
When is_currently_reasoning=False and the chunk contains no
<think> opener, returns an empty span so post-reasoning content
chunks arenβt misclassified as reasoning.
-
Parameters:
-
Return type:
will_reason_after_prompt()β
will_reason_after_prompt(prompt_token_ids)
Decide whether the next generated token continues a reasoning span.
Overrides the ABC default (which delegates to stream scanning
left-to-right). That default is wrong for Qwen: the chat template
embeds a literal <tool_call> example in the tool instructions,
and <tool_call> is a reasoning-end delimiter β so a left-to-right
scan hits the example and falsely concludes reasoning already ended,
leaking the modelβs <think> block into content.
Multi-turn prompts can also contain <think>/</think> tokens
from prior assistant turns; only the most-recently-emitted delimiter
describes the current state. Scan right-to-left: the last delimiter
before generation is the chat templateβs prefilled <think>.
Qwen3_5ToolParserβ
class max.pipelines.architectures.qwen3_5.Qwen3_5ToolParser
Bases: object
Parser for Qwen 3.5 / 3.6 tool calls.
parse_complete()β
parse_complete(response)
Parse a complete model response into tool calls.
-
Parameters:
-
response (str)
-
Return type:
parse_delta()β
parse_delta(delta)
Incrementally process one decoded-token delta.
Returns content text to forward to the client and any tool-call
increments to emit, in the order they were produced. Content
deltas have content set; tool-call deltas have one or more of
id / name / arguments set.
-
Parameters:
-
delta (str)
-
Return type:
-
list[ParsedToolCallDelta] | None
reset()β
reset()
Reset internal state for a new streaming session.
-
Return type:
-
None
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!