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.kimik2_5
Kimi K2.5 mixture-of-experts architecture for text generation.
KimiK2_5Config
class max.pipelines.architectures.kimik2_5.KimiK2_5Config(*, devices, dtype, quantization_encoding=None, bos_token_id, eos_token_id, ignore_index, media_placeholder_token_id, pad_token_id, tie_word_embeddings, use_unified_vision_chunk, video_placeholder, vision_config, llm_config)
Bases: _KimiK2_5VisionCacheConfig, ArchVLConfigWithTextSubconfig, ArchConfigWithKVCache, ArchConfigWithVisionCache
Configuration for Kimi-K2.5 models.
-
Parameters:
-
- devices (list[DeviceRef])
- dtype (DType)
- quantization_encoding (SupportedEncoding | None)
- bos_token_id (int)
- eos_token_id (int)
- ignore_index (int)
- media_placeholder_token_id (int)
- pad_token_id (int)
- tie_word_embeddings (bool)
- use_unified_vision_chunk (bool | None)
- video_placeholder (str | None)
- vision_config (VisionConfig)
- llm_config (KimiK2_5TextConfig)
DEFAULT_ENCODING
DEFAULT_ENCODING: ClassVar[SupportedEncoding] = 'bfloat16'
SUPPORTED_ENCODINGS
SUPPORTED_ENCODINGS: ClassVar[set[SupportedEncoding]] = {'bfloat16', 'float4_e2m1fnx2', 'float8_e4m3fn'}
bos_token_id
bos_token_id: int
ID of the beginning-of-sequence (BOS) token.
devices
Devices that the Kimi-K2.5 model is parallelized over.
dtype
dtype: DType
DType of the Kimi-K2.5 model weights.
eos_token_id
eos_token_id: int
ID of the end-of-sequence (EOS) token.
get_kv_params()
get_kv_params()
Returns the KV cache parameters from the embedded LLM config.
-
Return type:
get_num_layers()
static get_num_layers(huggingface_config)
-
Parameters:
-
huggingface_config (AutoConfig)
-
Return type:
ignore_index
ignore_index: int
Index that should be ignored when calculating loss (e.g., for padding).
initialize()
classmethod initialize(pipeline_config, model_config=None, *, max_seq_len)
Initializes a Qwen3VLConfig instance from pipeline configuration.
-
Parameters:
-
- pipeline_config (PipelineConfig) – The MAX Engine pipeline configuration.
- model_config (MAXModelConfig | None)
- max_seq_len (int)
-
Returns:
-
A Qwen3VLConfig instance with fields initialized from config.
-
Return type:
initialize_from_config()
classmethod initialize_from_config(pipeline_config, huggingface_config, llm_config=None, *, max_seq_len)
Initializes a KimiK2_5Config from pipeline and HuggingFace configs.
This method creates a config instance with all fields that can be determined from the pipeline and HuggingFace configurations, without needing the state_dict. Fields that depend on the state_dict should be set via the finalize() method.
-
Parameters:
-
- pipeline_config (PipelineConfig) – The MAX Engine pipeline configuration.
- huggingface_config (AutoConfig) – HuggingFace model configuration.
- llm_config (KimiK2_5TextConfig | None) – Pre-initialized DeepseekV3 configuration.
- max_seq_len (int)
-
Returns:
-
A KimiK2_5Config instance ready for finalization.
-
Return type:
llm_config
llm_config: KimiK2_5TextConfig
Language model configuration using DeepseekV3 architecture.
media_placeholder_token_id
media_placeholder_token_id: int
Token ID used as a placeholder for media (e.g., images, video frames) within sequences.
pad_token_id
pad_token_id: int
Token ID used for padding sequences to uniform length.
quantization_encoding
quantization_encoding: SupportedEncoding | None = None
The resolved weight encoding the model runs with.
tie_word_embeddings
tie_word_embeddings: bool
Whether to share (tie) the input and output word embeddings in the language model.
use_unified_vision_chunk
Whether to use a unified chunk for vision inputs.
video_placeholder
Placeholder string used to represent video segments in input text.
vision_config
vision_config: VisionConfig
Vision encoder configuration.
KimiK2_5Model
class max.pipelines.architectures.kimik2_5.KimiK2_5Model(pipeline_config, session, devices, kv_cache_config, weights, *, memory_plan, adapter=None, return_logits=ReturnLogits.ALL, return_hidden_states=ReturnHiddenStates.NONE, max_batch_size=1)
Bases: AlwaysSignalBuffersMixin, MultiGraphPipelineModelWithKVCache[KimiK2_5TextAndVisionContext]
A Kimi-K2.5 pipeline model for multimodal text generation.
-
Parameters:
-
- pipeline_config (PipelineConfig)
- session (InferenceSession)
- devices (list[Device])
- kv_cache_config (KVCacheConfig)
- weights (Weights)
- memory_plan (MemoryPlan)
- adapter (WeightsAdapter | None)
- return_logits (ReturnLogits)
- return_hidden_states (ReturnHiddenStates)
- max_batch_size (int)
batch_processor_cls
batch_processor_cls
alias of KimiK2_5BatchProcessor
empty_vision_embeddings()
empty_vision_embeddings(devices)
Per-device [0, hidden] image embeddings for non-vision steps.
Cached: this is hit on every text-only / decode step, so it must not allocate per call.
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.
get_kv_params()
classmethod get_kv_params(huggingface_config, pipeline_config, devices, kv_cache_config, cache_dtype)
Returns the KV cache params for the pipeline model.
Delegates to model_config_cls.construct_kv_params(...).
Subclasses with custom KV behavior should override this method.
-
Parameters:
-
- huggingface_config (AutoConfig)
- pipeline_config (PipelineConfig)
- devices (list[DeviceRef])
- kv_cache_config (KVCacheConfig)
- cache_dtype (DType)
-
Return type:
language_model
language_model: Model
The compiled language model for text generation.
load_model()
load_model(session)
Build, compile, and load vision and language graphs into session.
-
Parameters:
-
session (InferenceSession)
-
Return type:
model
property model: Model
Expose language model for graph capture/replay.
Only the language model is captured since vision runs during prefill
model_config_cls
model_config_cls
alias of KimiK2_5Config
pack_vision_inputs()
pack_vision_inputs(selection, devices)
Kimi packs inline in vision_execute() (chunked encode).
prepare_initial_token_inputs()
prepare_initial_token_inputs(replica_batches, kv_cache_inputs=None, return_n_logits=1)
Delegates to the batch processor; typed for Eagle subclasses.
vision_execute()
vision_execute(selection, devices, packed)
Run the chunked vision encoder over the cache-selected images.
The chunked encode (packing + per-chunk graph runs + re-concatenation to per-image order) stays encapsulated in the batch processor; the cache only ever sees the per-image-ordered output.
vision_model
The compiled vision model for processing images.
KimiK2_5ModelInputs
class max.pipelines.architectures.kimik2_5.KimiK2_5ModelInputs(tokens, input_row_offsets, signal_buffers, host_input_row_offsets, batch_context_lengths, image_token_indices=None, precomputed_image_embeddings=None, pixel_values=None, grid_thws=None, cu_seqlens=None, max_seqlen=None, vision_position_ids=None, eplb_counter_buffers=<factory>, *, kv_cache_inputs=None, lora_buffers=(), vision_embeddings=<factory>, vision_scatter_indices=<factory>, hidden_states=None, return_n_logits, data_parallel_splits, ep_inputs=())
Bases: DeepseekV3Inputs
A class representing inputs for the KimiK2_5M model.
This class encapsulates the input tensors required for the KimiK2_5M model execution, including both text and vision inputs. Vision inputs are optional and can be None for text-only processing.
-
Parameters:
-
- tokens (Buffer)
- input_row_offsets (Buffer)
- signal_buffers (list[Buffer])
- host_input_row_offsets (Buffer)
- batch_context_lengths (list[Buffer])
- image_token_indices (list[Buffer] | None)
- precomputed_image_embeddings (list[Buffer] | None)
- pixel_values (list[Buffer] | None)
- grid_thws (list[Buffer] | None)
- cu_seqlens (list[Buffer] | None)
- max_seqlen (list[Buffer] | None)
- vision_position_ids (list[Buffer] | None)
- eplb_counter_buffers (list[Buffer])
- kv_cache_inputs (KVCacheInputsInterface[Buffer, Buffer] | None)
- lora_buffers (tuple[Buffer, ...])
- vision_embeddings (list[Buffer])
- vision_scatter_indices (list[Buffer])
- hidden_states (Buffer | list[Buffer] | None)
- return_n_logits (Buffer)
- data_parallel_splits (Buffer)
- ep_inputs (tuple[Buffer, ...])
buffers
Returns the language model input ABI tuple.
cu_seqlens
Cumulative sequence lengths for full attention per device.
eplb_counter_buffers
Per-device EP counter buffers for the language model graph.
grid_thws
Grid dimensions (temporal, height, width) for each image/video, shape (n_images, 3) per device.
has_vision_inputs
property has_vision_inputs: bool
Check if this input contains vision data.
image_token_indices
Per-device pre-computed multimodal merge indices for the image embeddings.
These are the locations of the image_token_id in the inputs fed to the model.
Some indices may be negative, which means that they are ignored by the multimodal merge.
max_seqlen
Maximum sequence length for full attention for vision inputs per device.
pixel_values
Pixel values for vision inputs.
precomputed_image_embeddings
Pre-computed image embeddings from VisionEncoderCache.
vision_position_ids
Vision rotary position IDs per device.
KimiK2_5ReasoningParser
class max.pipelines.architectures.kimik2_5.KimiK2_5ReasoningParser(think_start_token_id, think_end_token_id, tool_section_start_token_id=None)
Bases: ReasoningParser
Kimi K2.5 reasoning parser for
Per Moonshot’s “Interleaved Thinking” design (see
https://platform.moonshot.ai/docs/guide/use-kimi-k2-thinking-model and
https://huggingface.co/moonshotai/Kimi-K2.5), a single assistant turn
can interleave multiple <think>...</think> blocks with
<|tool_calls_section_begin|>...<|tool_calls_section_end|> blocks.
A reasoning span ends on </think> or <|tool_calls_section_begin|>;
the model may open the tool-call section directly from inside the
prefilled <think> block without a closing </think>. The section
marker is left as content rather than consumed as a delimiter, so the
tool parser (which only sees content) receives the whole section.
Reasoning may begin implicitly, without an explicit <think>
token, when the chat template prefilled the assistant turn already
inside a thinking block.
Reasoning can be disabled through the chat template by including a
</think> token at the end of the prompt; this is detected by
will_reason_after_prompt().
-
Parameters:
REASONING_END
Text delimiter that closes a reasoning span (e.g. "</think>").
See REASONING_START for the declaration contract.
REASONING_START
Text delimiter that opens a reasoning span (e.g. "<think>").
Subclasses declare their delimiters here and resolve token ids from them, so each model’s delimiters are written down exactly once. Consumers that work in the text domain rather than the token domain read them from here instead of restating them.
Declare both delimiters or neither. None means this parser has no text
form at all, so a text-domain consumer cannot bound a reasoning span and
will leave reasoning in the assistant’s content; declaring only one is a
bug, since a span needs both ends. A parser whose chat template prefills
the opening delimiter still declares it – whether a given turn emits it is
a property of the request, not of the parser.
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.
-
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 non-reasoning chunks
(turns where the chat template prefilled </think>, or any
chunk after reasoning ended in a prior chunk) aren’t misclassified
as reasoning.
-
Parameters:
-
Return type:
will_reason_after_prompt()
will_reason_after_prompt(prompt_token_ids)
Predicts whether the model will emit reasoning after this prompt.
Kimi K2.5 chat templates emit <think> to open the new assistant
turn’s reasoning section, and </think> to close the prior
assistant turn’s reasoning section.
Scan right-to-left and return based on the first delimiter seen:
<think>→ reasoning is currently open →True.</think>(or<|tool_calls_section_begin|>) → reasoning is currently closed →False.- No delimiters at all → reasoning is not in use →
False.
Uses the same end-of-reasoning delimiters as stream() so both
agree on where reasoning ends.
KimiK2_5TextConfig
class max.pipelines.architectures.kimik2_5.KimiK2_5TextConfig(*, dtype, kv_params, devices, use_subgraphs=True, data_parallel_degree=1, quantization_encoding=None, vocab_size=129280, hidden_size=7168, intermediate_size=18432, moe_intermediate_size=2048, moe_layer_freq=1, num_hidden_layers=61, num_attention_heads=128, num_key_value_heads=128, n_shared_experts=1, n_routed_experts=256, routed_scaling_factor=2.5, kv_lora_rank=512, q_lora_rank=1536, qk_rope_head_dim=64, v_head_dim=128, qk_nope_head_dim=128, topk_method='greedy', n_group=8, topk_group=4, num_experts_per_tok=8, first_k_dense_replace=3, norm_topk_prob=True, hidden_act='silu', max_position_embeddings=4096, max_seq_len, rms_norm_eps=1e-06, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, rope_interleave=True, scoring_func='sigmoid', attention_bias=False, attention_dropout=0.0, norm_dtype=bfloat16, gate_dtype=None, correction_bias_dtype=None, max_batch_context_length=131072, quant_config=None, dense_mlp_layers_without_quant=frozenset({}), ep_config=None, graph_mode='auto', return_logits=ReturnLogits.LAST_TOKEN, return_hidden_states=ReturnHiddenStates.NONE, eagle_aux_hidden_state_layer_ids=None, eplb_profile_enabled=False)
Bases: _KimiK2_5VisionCacheConfig, DeepseekV3Config, ArchConfigWithVisionCache
-
Parameters:
-
- dtype (DType)
- kv_params (KVCacheParamInterface)
- devices (list[DeviceRef])
- use_subgraphs (bool)
- data_parallel_degree (int)
- quantization_encoding (SupportedEncoding | None)
- vocab_size (int)
- hidden_size (int)
- intermediate_size (int)
- moe_intermediate_size (int)
- moe_layer_freq (int)
- num_hidden_layers (int)
- num_attention_heads (int)
- num_key_value_heads (int)
- n_shared_experts (int)
- n_routed_experts (int)
- routed_scaling_factor (float)
- kv_lora_rank (int)
- q_lora_rank (int)
- qk_rope_head_dim (int)
- v_head_dim (int)
- qk_nope_head_dim (int)
- topk_method (str)
- n_group (int)
- topk_group (int)
- num_experts_per_tok (int)
- first_k_dense_replace (int)
- norm_topk_prob (bool)
- hidden_act (str)
- max_position_embeddings (int)
- max_seq_len (int)
- rms_norm_eps (float)
- tie_word_embeddings (bool)
- rope_theta (float)
- rope_scaling (dict[str, Any] | None)
- rope_interleave (bool)
- scoring_func (str)
- attention_bias (bool)
- attention_dropout (float)
- norm_dtype (DType)
- gate_dtype (DType | None)
- correction_bias_dtype (DType | None)
- max_batch_context_length (int)
- quant_config (QuantConfig | None)
- dense_mlp_layers_without_quant (frozenset[int])
- ep_config (EPConfig | None)
- graph_mode (str)
- return_logits (ReturnLogits)
- return_hidden_states (ReturnHiddenStates)
- eagle_aux_hidden_state_layer_ids (list[int] | None)
- eplb_profile_enabled (bool)
DEFAULT_ENCODING
DEFAULT_ENCODING: ClassVar[SupportedEncoding] = 'bfloat16'
SUPPORTED_ENCODINGS
SUPPORTED_ENCODINGS: ClassVar[set[SupportedEncoding]] = {'bfloat16', 'float4_e2m1fnx2', 'float8_e4m3fn'}
calculate_max_seq_len()
classmethod calculate_max_seq_len(huggingface_config, model_config)
Returns the resolved maximum sequence length.
Bounds or defaults the user’s model_config.max_length with the
model’s own limits. Construction runs this once and stores the
result on model_config.max_length; memory planning may lower
it further, but only on the memory plan.
-
Parameters:
-
- huggingface_config (AutoConfig) – The HuggingFace config to read model bounds from.
- model_config (MAXModelConfig) – The model config whose
max_lengthcarries the user’s setting.
-
Return type:
initialize()
classmethod initialize(pipeline_config, model_config=None, *, max_seq_len)
Initializes a DeepseekV3Config instance from pipeline configuration.
This method creates a config instance with all fields that can be determined from the pipeline configuration, without needing the state_dict. Fields that depend on the state_dict (like norm_dtype, quant_config, etc.) should be set via the finalize() method.
-
Parameters:
-
- pipeline_config (PipelineConfig) – The MAX Engine pipeline configuration.
- model_config (MAXModelConfig | None)
- max_seq_len (int)
-
Returns:
-
An initialized DeepseekV3Config instance.
-
Return type:
KimiToolParser
class max.pipelines.architectures.kimik2_5.KimiToolParser
Bases: StructuralTagToolParser
Parses Kimi K2.5-style tool calls from model responses.
Kimi K2.5 wraps tool calls in section/call markers and embeds the
function name as a compound functions.{name}:{idx} identifier
before a dedicated argument-begin marker. Arguments are raw JSON,
which the base class can diff directly.
CALL_BEGIN
CALL_BEGIN: ClassVar[str] = '<|tool_call_begin|>'
CALL_END
CALL_END: ClassVar[str] = '<|tool_call_end|>'
SECTION_BEGIN
SECTION_BEGIN: ClassVar[str] = '<|tool_calls_section_begin|>'
SECTION_END
SECTION_END: ClassVar[str] = '<|tool_calls_section_end|>'
XGRAMMAR_FORMAT
XGRAMMAR_FORMAT = 'kimi'
generate_tool_call_grammar()
static generate_tool_call_grammar(response_format_schema=None, tools=None, tokenizer=None, backend='xgrammar', tool_choice=None, **kwargs)
Generates a constrained-decoding grammar for Kimi tool calls.
Returns a serialized xgrammar StructuralTag that frames the Kimi
tool-call envelope and constrains each call’s arguments to that
tool’s JSON schema. When response_format_schema is provided, the
grammar also accepts a JSON response matching the schema (the model’s
first tokens select the branch).
-
Parameters:
-
- response_format_schema (dict[str, Any] | None) – Optional JSON schema dict. When provided, the grammar also accepts a JSON response matching the schema.
- tools (list[dict[str, Any]] | None) – Optional list of OpenAI-style tool dicts.
- tokenizer (PipelineTokenizer[Any, Any, Any] | None) – Unused (the xgrammar tag references literal markers).
- backend (str) – Structured-output backend; must be
"xgrammar". - tool_choice (str | dict[str, Any] | None) –
"auto","required", or a named choice. - **kwargs (Any) – Ignored; accepts future kwargs.
-
Returns:
-
The StructuralTag serialized as a JSON string.
-
Return type:
VisionConfig
class max.pipelines.architectures.kimik2_5.VisionConfig(dtype, devices, init_pos_emb_height, init_pos_emb_time, init_pos_emb_width, merge_kernel_size, mm_hidden_size, patch_size, projector_ln_eps, text_hidden_size, vt_hidden_size, vt_intermediate_size, vt_num_attention_heads, vt_num_hidden_layers, merge_type=None, mm_projector_type=None, model_type='', pos_emb_type=None, projector_hidden_act=None, video_attn_type=None, has_bias=True, in_channels=3, rope_max_height=512, rope_max_width=512, rope_theta=10000.0)
Bases: object
Vision configuration for Kimi-K2.5 models with required fields.
-
Parameters:
-
- dtype (DType)
- devices (list[DeviceRef])
- init_pos_emb_height (int)
- init_pos_emb_time (int)
- init_pos_emb_width (int)
- merge_kernel_size (list[int])
- mm_hidden_size (int)
- patch_size (int)
- projector_ln_eps (float)
- text_hidden_size (int)
- vt_hidden_size (int)
- vt_intermediate_size (int)
- vt_num_attention_heads (int)
- vt_num_hidden_layers (int)
- merge_type (str | None)
- mm_projector_type (str | None)
- model_type (str)
- pos_emb_type (str | None)
- projector_hidden_act (str | None)
- video_attn_type (str | None)
- has_bias (bool)
- in_channels (int)
- rope_max_height (int)
- rope_max_width (int)
- rope_theta (float)
devices
Devices that the Kimi-K2.5 vision encoder model is parallelized over.
dtype
dtype: DType
DType of the Kimi-K2.5 vision model weights.
finalize()
finalize(vision_dtype)
Finalize VisionConfig with state_dict dependent fields.
-
Parameters:
-
vision_dtype (DType)
-
Return type:
-
None
has_bias
has_bias: bool = True
Whether linear projections in the vision transformer include bias terms.
in_channels
in_channels: int = 3
Number of input image channels (3 for RGB).
init_pos_emb_height
init_pos_emb_height: int
Height of the initial position embedding.
init_pos_emb_time
init_pos_emb_time: int
Time of the initial position embedding.
init_pos_emb_width
init_pos_emb_width: int
Width of the initial position embedding.
initialize_from_config()
classmethod initialize_from_config(pipeline_config, hf_vision_config, huggingface_config=None)
Initialize VisionConfig from HuggingFace vision config.
-
Parameters:
-
- pipeline_config (PipelineConfig) – MAX Engine pipeline configuration.
- hf_vision_config (AutoConfig) – HuggingFace vision sub-config.
- huggingface_config (AutoConfig | None) – Full HuggingFace model config, used to derive
text_hidden_sizefromtext_config.hidden_sizewhenhf_vision_configdoes not carry the attribute directly (e.g. moonshotai/Kimi-VL-A3B-Instruct vs nvidia/Kimi-K2.5-NVFP4).
-
Return type:
Note: dtype fields will be set to defaults and should be updated via finalize() once state_dict is available.
merge_kernel_size
Kernel size for the merge operation.
merge_type
Type of the merge operation.
mm_hidden_size
mm_hidden_size: int
Hidden size of the multi-modal hidden layer.
mm_projector_type
Type of the multi-modal projector.
model_type
model_type: str = ''
Type of the model.
patch_size
patch_size: int
Size of the patch.
pos_emb_type
Type of the position embedding.
projector_hidden_act
Activation function for the projector.
projector_ln_eps
projector_ln_eps: float
Epsilon for the layer normalization.
rope_max_height
rope_max_height: int = 512
Maximum grid height for RoPE frequency precomputation. Hardcoded to 512 in https://huggingface.co/nvidia/Kimi-K2.5-NVFP4/blob/main/modeling_kimi_k25.py#L571
rope_max_width
rope_max_width: int = 512
Maximum grid width for RoPE frequency precomputation. Hardcoded to 512 in https://huggingface.co/nvidia/Kimi-K2.5-NVFP4/blob/main/modeling_kimi_k25.py#L571
rope_theta
rope_theta: float = 10000.0
Base for the RoPE inverse-frequency exponent. Hardcoded to 10000 in https://huggingface.co/nvidia/Kimi-K2.5-NVFP4/blob/main/modeling_kimi_k25.py#L379
text_hidden_size
text_hidden_size: int
Hidden size of the text hidden layer.
video_attn_type
Type of the video attention.
vt_hidden_size
vt_hidden_size: int
Hidden size of the video hidden layer.
vt_intermediate_size
vt_intermediate_size: int
Intermediate size of the video hidden layer.
vt_num_attention_heads
vt_num_attention_heads: int
Number of attention heads of the video hidden layer.
vt_num_hidden_layers
vt_num_hidden_layers: int
Number of hidden layers of the video hidden layer.