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.unified_dspark_gemma4
Unified DSpark speculative decoding for Gemma4.
DSparkGemma4β
class max.pipelines.architectures.unified_dspark_gemma4.DSparkGemma4(config, *, kv_params, devices, dtype)
Bases: Module
DSpark draft transformer for a Gemma4 target.
-
Parameters:
-
- config (DSparkGemma4DraftConfig)
- kv_params (KVCacheParams)
- devices (list[DeviceRef])
- dtype (DType)
forward_block()β
forward_block(input_embeds, kv_collection, input_row_offsets)
-
Parameters:
-
- input_embeds (TensorValue)
- kv_collection (KVCacheInputsPerDevice[TensorValue, BufferValue])
- input_row_offsets (TensorValue)
-
Return type:
materialize_kv()β
materialize_kv(ctx_hidden, input_row_offsets, kv_collection)
-
Parameters:
-
- ctx_hidden (TensorValue)
- input_row_offsets (TensorValue)
- kv_collection (KVCacheInputsPerDevice[TensorValue, BufferValue])
-
Return type:
-
None
project_target_hidden()β
project_target_hidden(target_hs_concat)
-
Parameters:
-
target_hs_concat (TensorValue)
-
Return type:
DSparkGemma4Attentionβ
class max.pipelines.architectures.unified_dspark_gemma4.DSparkGemma4Attention(*, rope_global, rope_local, num_attention_heads, num_key_value_heads, num_global_key_value_heads, attention_k_eq_v, hidden_size, kv_params, global_head_dim, layer_idx, layer_idx_in_cache, is_sliding, dtype=float32, devices, linear_cls=<class 'max.nn.linear.Linear'>, has_bias=False, qk_norm_eps=1e-06, local_window_size=1024, quant_config=None, fused_qkv=False)
Bases: Gemma4Attention
Non-causal DSpark draft attention over [materialized ctx ; block].
Initializes the attention layer.
-
Parameters:
-
- rope_global (RotaryEmbedding) β Rotary embedding used for global (non-sliding window) attention layers.
- rope_local (RotaryEmbedding) β Rotary embedding used for sliding window attention layers.
- num_attention_heads (int) β The number of attention heads.
- num_key_value_heads (int) β The number of key/value heads.
- hidden_size (int) β The dimension of the hidden states.
- kv_params (KVCacheParams) β KV Cache Params, including the number of kv heads, the head dim, and data type.
- layer_idx (int) β The layer number associated with this Attention block.
- layer_idx_in_cache (int) β The 0-based index of this layer within its sub-cache (sliding or global).
- is_sliding (bool) β Whether this layer uses sliding window attention.
- dtype (DType) β DType of the attention inputs and weights.
- devices (list[DeviceRef]) β Device to place the weights and run the computation. If multiple are provided, the first device is used. Use TensorParallelAttentionWithRope to use all devices during attention computation.
- linear_cls (Callable[..., Linear]) β Linear class to use for the outputs dense layer.
- has_bias (bool) β Whether to use an attention bias. Defaults to False.
- qk_norm_eps (float) β Value to use for numerical stability. Defaults to 1e-6.
- quant_config (QuantConfig | None) β Scaled quantization configuration. Defaults to None.
- fused_qkv (bool) β When True, the qkv/qk projection uses a single stacked
weight (
StackedLinear(stacked=True)) loaded pre-fused from the checkpoint instead of concatenating per-projection weights in-graph (DISTINF-194). Defaults to False. - num_global_key_value_heads (int)
- attention_k_eq_v (bool)
- global_head_dim (int)
- local_window_size (int)
mask_variantβ
mask_variant: MHAMaskVariant | None = '2'
materialize_kv_from_hidden()β
materialize_kv_from_hidden(hidden, kv_collection, input_row_offsets)
Projects ctx hidden states to K/V and writes the paged KV cache.
Matches the reference ctx path: K gets k_norm + RoPE at the ctx
positions (cache_length + row); V is the scale-free v_norm
of the pre-norm K projection and is not roped.
-
Parameters:
-
- hidden (TensorValue)
- kv_collection (KVCacheInputsPerDevice[TensorValue, BufferValue])
- input_row_offsets (TensorValue)
-
Return type:
-
None
DSparkGemma4DecoderLayerβ
class max.pipelines.architectures.unified_dspark_gemma4.DSparkGemma4DecoderLayer(attention, mlp, hidden_size, rms_norm_eps, dtype)
Bases: Module
Single-device Gemma4 decoder sandwich with a per-layer scalar.
Mirrors the reference Gemma4DSparkDecoderLayer: input_ln -> attn ->
post_attn_ln -> +residual; pre_ffw_ln -> mlp -> post_ffw_ln ->
+residual; then multiply by layer_scalar.
-
Parameters:
-
- attention (DSparkGemma4Attention)
- mlp (MLP)
- hidden_size (int)
- rms_norm_eps (float)
- dtype (DType)
DSparkGemma4DraftConfigβ
class max.pipelines.architectures.unified_dspark_gemma4.DSparkGemma4DraftConfig(hidden_size, intermediate_size, num_hidden_layers, num_attention_heads, num_key_value_heads, head_dim, rms_norm_eps, vocab_size, hidden_activation, final_logit_softcapping, rope_theta, partial_rotary_factor, max_seq_len, block_size, mask_token_id, target_layer_ids, markov_rank, markov_head_type)
Bases: object
DSpark drafter hyperparameters from the draft HF checkpoint config.
The checkpoint config (e.g. deepseek-ai/dspark_gemma4_12b_block7) is
a gemma4_text-style config extended with the DSpark fields
(block_size, mask_token_id, target_layer_ids,
markov_rank, β¦). Only full-attention (k_eq_v) draft layers are
supported, matching the reference drafter.
-
Parameters:
-
- hidden_size (int)
- intermediate_size (int)
- num_hidden_layers (int)
- num_attention_heads (int)
- num_key_value_heads (int)
- head_dim (int)
- rms_norm_eps (float)
- vocab_size (int)
- hidden_activation (str)
- final_logit_softcapping (float | None)
- rope_theta (float)
- partial_rotary_factor (float)
- max_seq_len (int)
- block_size (int)
- mask_token_id (int)
- target_layer_ids (tuple[int, ...])
- markov_rank (int)
- markov_head_type (str)
block_sizeβ
block_size: int
final_logit_softcappingβ
from_huggingface_config()β
classmethod from_huggingface_config(huggingface_config, *, max_seq_len=None)
Parses the DSpark draft checkpoint config (object or dict).
-
Parameters:
-
Return type:
head_dimβ
head_dim: int
Global head dim (global_head_dim in the HF config).
hidden_activationβ
hidden_activation: str
hidden_sizeβ
hidden_size: int
intermediate_sizeβ
intermediate_size: int
markov_head_typeβ
markov_head_type: str
markov_rankβ
markov_rank: int
mask_token_idβ
mask_token_id: int
max_seq_lenβ
max_seq_len: int
num_attention_headsβ
num_attention_heads: int
num_context_featuresβ
property num_context_features: int
num_hidden_layersβ
num_hidden_layers: int
num_key_value_headsβ
num_key_value_heads: int
Global (k_eq_v) key/value head count; every draft layer is global.
partial_rotary_factorβ
partial_rotary_factor: float
rms_norm_epsβ
rms_norm_eps: float
rope_thetaβ
rope_theta: float
target_layer_idsβ
vocab_sizeβ
vocab_size: int
DSparkMarkovHeadβ
class max.pipelines.architectures.unified_dspark_gemma4.DSparkMarkovHead(vocab_size, markov_rank, dtype, device)
Bases: Module
Vanilla markov head: bias = markov_w2(markov_w1[prev_token]).
Mirrors the reference VanillaMarkov (markov_head.py): a low-rank
per-token logit bias conditioned only on the previous draft token. The
hidden states are ignored by the vanilla head.
compute_step_bias()β
compute_step_bias(prev_tokens)
Returns the [batch, vocab] bias for [batch] prev tokens.
-
Parameters:
-
prev_tokens (TensorValue)
-
Return type:
UnifiedDSparkGemma4β
class max.pipelines.architectures.unified_dspark_gemma4.UnifiedDSparkGemma4(config)
Bases: Module
Fused module: merge β target β reject β materialize β draft block.
-
Parameters:
-
config (UnifiedDSparkGemma4Config)
input_types()β
input_types()
Single-device DSpark graph. See
build_spec_decode_input_types() for the canonical ordering.
Signal buffers are declared even though the graph is single-device:
Gemma4βs embedding/lm_head layers use collectives unconditionally.
-
Return type:
-
tuple[TensorType | BufferType, β¦]
UnifiedDSparkGemma4Configβ
class max.pipelines.architectures.unified_dspark_gemma4.UnifiedDSparkGemma4Config(*, target: 'Gemma4ForConditionalGenerationConfig', draft: 'DSparkGemma4DraftConfig', draft_kv_params: 'KVCacheParams', speculative_config: 'SpeculativeConfig', target_layer_ids: 'list[int]' = <factory>, mask_token_id: 'int' = 0, block_size: 'int' = 0)
Bases: ArchConfigWithKVCache
-
Parameters:
-
- target (Gemma4ForConditionalGenerationConfig)
- draft (DSparkGemma4DraftConfig)
- draft_kv_params (KVCacheParams)
- speculative_config (SpeculativeConfig)
- target_layer_ids (list[int])
- mask_token_id (int)
- block_size (int)
DEFAULT_ENCODINGβ
DEFAULT_ENCODING: ClassVar[max.pipelines.lib.config.SupportedEncoding] = 'bfloat16'
SUPPORTED_ENCODINGSβ
SUPPORTED_ENCODINGS: ClassVar[set[max.pipelines.lib.config.SupportedEncoding]] = {'bfloat16'}
block_sizeβ
block_size: int = 0
devicesβ
Devices the unified model runs on (the memory-planner protocol).
draftβ
draft: DSparkGemma4DraftConfig
draft_kv_paramsβ
draft_kv_params: KVCacheParams
get_kv_params()β
get_kv_params()
KV cache parameters to use when running the model.
-
Return type:
get_max_seq_len()β
get_max_seq_len()
Returns the default maximum sequence length for the model.
Subclasses should determine whether this value can be overridden by
setting the --max-length (pipeline_config.model.max_length) flag.
-
Return type:
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:
mask_token_idβ
mask_token_id: int = 0
resolve_block_size()β
resolve_block_size(*, default=None)
speculative_configβ
speculative_config: SpeculativeConfig
targetβ
target_layer_idsβ
validate_dspark_fields()β
validate_dspark_fields()
Strict validation of the DSpark fields parsed from the draft HF
config. Unlike DFlash, ALL block_size positions produce drafts,
so num_speculative_tokens must equal block_size (no - 1).
-
Return type:
-
None
UnifiedDSparkGemma4Inputsβ
class max.pipelines.architectures.unified_dspark_gemma4.UnifiedDSparkGemma4Inputs(tokens, input_row_offsets, return_n_logits, signal_buffers, *, kv_cache_inputs=None, lora=None, vision_embeddings=<factory>, vision_scatter_indices=<factory>, hidden_states=None, draft_tokens=None, seed=None, temperature=None, top_k=None, max_k=None, top_p=None, min_top_p=None, in_thinking_phase=None, pinned_bitmask=None, wait_payload=None, device_bitmask_scratch=None, structured_output=False)
Bases: UnifiedSpecDecodeInputs
Inputs for the unified DSpark Gemma4 graph.
The spec-decode fields and trailing buffer packing come from
UnifiedSpecDecodeInputs; tokens / input_row_offsets /
return_n_logits / signal_buffers plus the KV cache tree form this
single-device graphβs prefix. Signal buffers are bound because Gemma4βs
embedding and lm_head layers use collectives even on one device. The
DSpark graph does not bind in_thinking_phase.
-
Parameters:
-
- tokens (Buffer)
- input_row_offsets (Buffer)
- return_n_logits (Buffer)
- signal_buffers (list[Buffer])
- kv_cache_inputs (KVCacheInputsInterface[Buffer, Buffer] | None)
- lora (LoRAInputs | None)
- vision_embeddings (list[Buffer])
- vision_scatter_indices (list[Buffer])
- hidden_states (Buffer | list[Buffer] | None)
- draft_tokens (Buffer | None)
- seed (Buffer | None)
- temperature (Buffer | None)
- top_k (Buffer | None)
- max_k (Buffer | None)
- top_p (Buffer | None)
- min_top_p (Buffer | None)
- in_thinking_phase (Buffer | None)
- pinned_bitmask (Buffer | None)
- wait_payload (Buffer | None)
- device_bitmask_scratch (Buffer | None)
- structured_output (bool)
buffersβ
Returns positional Buffer inputs for model ABI calls.
input_row_offsetsβ
input_row_offsets: Buffer
return_n_logitsβ
return_n_logits: Buffer
signal_buffersβ
tokensβ
tokens: Buffer
UnifiedDSparkGemma4Modelβ
class max.pipelines.architectures.unified_dspark_gemma4.UnifiedDSparkGemma4Model(pipeline_config, session, devices, kv_cache_config, weights, adapter=None, return_logits=ReturnLogits.LAST_TOKEN, return_hidden_states=ReturnHiddenStates.NONE, max_batch_size=1)
Bases: _UnifiedSpecDecodeModelMixin, AlwaysSignalBuffersMixin, GraphPipelineModelWithKVCache[TextContext]
Unified DSpark Gemma4: target + draft in one compiled graph.
-
Parameters:
-
- pipeline_config (PipelineConfig)
- session (InferenceSession)
- devices (list[Device])
- kv_cache_config (KVCacheConfig)
- weights (Weights)
- adapter (WeightsAdapter | None)
- return_logits (ReturnLogits)
- return_hidden_states (ReturnHiddenStates)
- max_batch_size (int)
batch_processor_clsβ
batch_processor_cls
alias of UnifiedDSparkGemma4BatchProcessor
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 (PreTrainedConfig)
- pipeline_config (PipelineConfig)
- devices (list[DeviceRef])
- kv_cache_config (KVCacheConfig)
- cache_dtype (DType)
-
Return type:
modelβ
model: Model
model_config_clsβ
model_config_cls
alias of UnifiedDSparkGemma4Config