Skip to content
Merged
32 changes: 23 additions & 9 deletions vllm/config/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,11 +812,19 @@ def _supports_multimodal_for_mm_prefix(self) -> bool:

def get_model_arch_config(
self,
layer_idx: int | None = None,
) -> ModelArchitectureConfig:
hf_config = self.hf_config
hf_text_config = self.hf_text_config
if layer_idx is not None:
if getattr(hf_config, "is_heterogeneous", False):
hf_config = hf_config.per_layer_config[layer_idx]
if getattr(hf_text_config, "is_heterogeneous", False):
hf_text_config = hf_text_config.per_layer_config[layer_idx]
convertor_cls = MODEL_ARCH_CONFIG_CONVERTORS.get(
self.hf_config.model_type, ModelArchConfigConvertorBase
)
convertor = convertor_cls(self.hf_config, self.hf_text_config)
convertor = convertor_cls(hf_config, hf_text_config)
return convertor.convert(
supports_multimodal=self._supports_multimodal_for_mm_prefix()
)
Expand Down Expand Up @@ -861,8 +869,8 @@ def _get_transformers_backend_cls(self) -> str:
"""Determine which Transformers modeling backend class will be used if
`model_impl` is set to `transformers` or `auto`."""
cls = "Transformers"
# If 'hf_config != hf_text_config' it's a nested config, i.e. multimodal
cls += "MultiModal" if self.hf_config != self.hf_text_config else ""
# If 'hf_config is not hf_text_config' it's a nested config, i.e. multimodal
cls += "MultiModal" if self.hf_config is not self.hf_text_config else ""
cls += "MoE" if self.is_moe else ""
# Check if the architecture we're wrapping has defaults
runner = None
Expand Down Expand Up @@ -1367,20 +1375,26 @@ def is_mm_prefix_lm(self) -> bool:
def rswa_window(self) -> int | None:
return self.model_arch_config.rswa_window

def get_head_size(self) -> int:
return self.model_arch_config.head_size
def get_head_size(self, layer_idx: int | None = None) -> int:
if layer_idx is None:
return self.model_arch_config.head_size
return self.get_model_arch_config(layer_idx=layer_idx).head_size

def get_total_num_kv_heads(self) -> int:
def get_total_num_kv_heads(self, layer_idx: int | None = None) -> int:
"""Returns the total number of KV heads."""
return self.model_arch_config.total_num_kv_heads
if layer_idx is None:
return self.model_arch_config.total_num_kv_heads
return self.get_model_arch_config(layer_idx=layer_idx).total_num_kv_heads

def get_num_kv_heads(self, parallel_config: ParallelConfig) -> int:
def get_num_kv_heads(
self, parallel_config: ParallelConfig, layer_idx: int | None = None
) -> int:
"""Returns the number of KV heads per GPU."""
if self.use_mla:
# When using MLA during decode it becomes MQA
return 1

total_num_kv_heads = self.get_total_num_kv_heads()
total_num_kv_heads = self.get_total_num_kv_heads(layer_idx=layer_idx)
# If tensor parallelism is used, we divide the number of KV heads by
# the tensor parallel size. We will replicate the KV heads in the
# case where the number of KV heads is smaller than the tensor
Expand Down
8 changes: 2 additions & 6 deletions vllm/model_executor/model_loader/weight_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,8 @@ def get_quant_config(
and hf_quant_config.get("quant_method") == "compressed-tensors"
and "config_groups" in hf_quant_config
):
if hf_text_config is not None:
n_heads = getattr(hf_text_config, "num_attention_heads", None)
n_kv_heads = getattr(hf_text_config, "num_key_value_heads", None)
else:
n_heads = getattr(model_config.hf_config, "num_attention_heads", None)
n_kv_heads = getattr(model_config.hf_config, "num_key_value_heads", None)
n_heads = model_config.model_arch_config.total_num_attention_heads
n_kv_heads = model_config.model_arch_config.total_num_kv_heads

hf_quant_config["total_num_heads"] = n_heads
hf_quant_config["total_num_kv_heads"] = (
Expand Down
48 changes: 28 additions & 20 deletions vllm/model_executor/models/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,26 +200,38 @@ class Gemma4Config(VerifyAndUpdateConfig):
def verify_and_update_config(vllm_config: "VllmConfig") -> None:
"""Configure attention for heterogeneous head dimensions.

Gemma4 uses different head dimensions for sliding window
(head_dim) vs full attention (global_head_dim) layers. The
default FA3 on Hopper cannot handle head_dim > 256, which
causes mixed backend selection and numerical divergence.

When FA4 is available we force it for ALL layers, giving a
uniform kernel path and avoiding the mixed FA3+FA4 penalty.
When FA4 is not available we fall back to Triton.
Gemma4 uses different head dimensions for sliding window vs full attention
layers. The default FA3 on Hopper cannot handle head_dim > 256, which causes
mixed backend selection and numerical divergence.

When FA4 is available we force it for ALL layers, giving a uniform kernel path
and avoiding the mixed FA3+FA4 penalty. When FA4 is not available we fall back
to Triton.
"""
hf_text_config = vllm_config.model_config.hf_text_config
head_dim = getattr(hf_text_config, "head_dim", None)
global_head_dim = getattr(hf_text_config, "global_head_dim", None)
if hasattr(hf_text_config, "is_heterogeneous"):
# Transformers >= 5.15.0
head_dims = {
layer_type: hf_text_config.per_layer_config[layer_type].head_dim
for layer_type in hf_text_config.layer_types
}
else:
# Transformers < 5.15.0
head_dims = {
"sliding_attention": getattr(hf_text_config, "head_dim", None),
"full_attention": getattr(hf_text_config, "global_head_dim", None),
}

if head_dim is None or global_head_dim is None or head_dim == global_head_dim:
if (
any(dim is None for dim in head_dims.values())
or len(set(head_dims.values())) == 1
):
return

from vllm.v1.attention.backends.fa_utils import is_fa_version_supported
from vllm.v1.attention.backends.registry import AttentionBackendEnum

max_head_dim = max(head_dim, global_head_dim)
max_head_dim = max(head_dims.values())

if is_fa_version_supported(4) and max_head_dim <= 512:
if (
Expand All @@ -229,20 +241,16 @@ def verify_and_update_config(vllm_config: "VllmConfig") -> None:
):
vllm_config.attention_config.flash_attn_version = 4
logger.info(
"Gemma4 model has heterogeneous head dimensions "
"(head_dim=%d, global_head_dim=%d). Using FA4 for "
"Gemma4 model has heterogeneous head dimensions %s. Using FA4 for "
"all layers to avoid mixed FA3/FA4 penalty.",
head_dim,
global_head_dim,
head_dims,
)
elif vllm_config.attention_config.backend is None:
vllm_config.attention_config.backend = AttentionBackendEnum.TRITON_ATTN
logger.info(
"Gemma4 model has heterogeneous head dimensions "
"(head_dim=%d, global_head_dim=%d). FA4 not available, "
"forcing TRITON_ATTN backend.",
head_dim,
global_head_dim,
"%s. FA4 not available, forcing TRITON_ATTN backend.",
head_dims,
)


Expand Down
35 changes: 15 additions & 20 deletions vllm/model_executor/models/gemma4.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,6 @@ def __init__(
num_kv_heads: int,
head_dim: int,
max_position_embeddings: int,
use_k_eq_v: bool = False,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
attn_logits_soft_cap: float | None = None,
Expand All @@ -389,7 +388,6 @@ def __init__(
super().__init__()
self.config = config
self.hidden_size = hidden_size
self.use_k_eq_v = use_k_eq_v

tp_size = get_tensor_model_parallel_world_size()
self.tp_rank = get_tensor_model_parallel_rank()
Expand Down Expand Up @@ -571,26 +569,24 @@ def __init__(

# Gemma4 uses different head dimensions for sliding vs full attention
layer_type = config.layer_types[layer_idx]
self.is_full_attention = layer_type == "full_attention"
if self.is_full_attention:
head_dim = getattr(config, "global_head_dim", config.head_dim)
else:
head_dim = config.head_dim

# Determine if this full-attention layer uses k_eq_v
# (laptop variant: no v_proj, K reused as V on full attention layers)
use_k_eq_v = self.is_full_attention and getattr(
config, "attention_k_eq_v", False
)

# For k_eq_v full-attention layers, use num_global_key_value_heads
# as the KV head count when k_eq_v is enabled.
if use_k_eq_v:
num_kv_heads = getattr(
config, "num_global_key_value_heads", config.num_key_value_heads
)
if hasattr(config, "is_heterogeneous"):
# Transformers >= 5.15.0
layer_config = config.per_layer_config[layer_idx]
head_dim = layer_config.head_dim
num_kv_heads = layer_config.num_key_value_heads
else:
# Transformers < 5.15.0
# Determine if this full-attention layer uses k_eq_v
# (laptop variant: no v_proj, K reused as V on full attention layers)
head_dim = config.head_dim
num_kv_heads = config.num_key_value_heads
if layer_type == "full_attention":
head_dim = getattr(config, "global_head_dim", head_dim)
if getattr(config, "attention_k_eq_v", False):
num_kv_heads = getattr(
config, "num_global_key_value_heads", num_kv_heads
)

self.self_attn = Gemma4Attention(
config=config,
Expand All @@ -599,7 +595,6 @@ def __init__(
num_kv_heads=num_kv_heads,
head_dim=head_dim,
max_position_embeddings=config.max_position_embeddings,
use_k_eq_v=use_k_eq_v,
cache_config=cache_config,
quant_config=quant_config,
attn_logits_soft_cap=getattr(config, "attn_logit_softcapping", None),
Expand Down
34 changes: 21 additions & 13 deletions vllm/model_executor/models/gemma4_dspark.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,27 @@ def __init__(
quant_config: QuantizationConfig | None,
prefix: str,
) -> None:
is_full = config.layer_types[extract_layer_index(prefix)] == "full_attention"
head_dim = (
getattr(config, "global_head_dim", config.head_dim)
if is_full
else config.head_dim
)
use_k_eq_v = is_full and getattr(config, "attention_k_eq_v", False)
num_kv_heads = (
getattr(config, "num_global_key_value_heads", config.num_key_value_heads)
if use_k_eq_v
else config.num_key_value_heads
layer_idx = extract_layer_index(prefix)
layer_type = config.layer_types[layer_idx]
self.use_k_eq_v = layer_type == "full_attention" and getattr(
config, "attention_k_eq_v", False
)

if hasattr(config, "is_heterogeneous"):
# Transformers >= 5.15.0
layer_config = config.per_layer_config[layer_idx]
head_dim = layer_config.head_dim
num_kv_heads = layer_config.num_key_value_heads
else:
# Transformers < 5.15.0
head_dim = config.head_dim
num_kv_heads = config.num_key_value_heads
if layer_type == "full_attention":
head_dim = getattr(config, "global_head_dim", head_dim)
if self.use_k_eq_v:
num_kv_heads = getattr(
config, "num_global_key_value_heads", num_kv_heads
)
super().__init__(
config=config,
hidden_size=config.hidden_size,
Expand All @@ -62,7 +71,6 @@ def __init__(
prefix=prefix,
)
self.is_kv_shared_layer = False
self.use_k_eq_v = use_k_eq_v
self.kv_size = self.num_kv_heads * self.head_dim
attn_bias = getattr(config, "attention_bias", False)
self.k_proj = ColumnParallelLinear(
Expand All @@ -74,7 +82,7 @@ def __init__(
)
self.v_proj = (
None
if use_k_eq_v
if self.use_k_eq_v
else ColumnParallelLinear(
config.hidden_size,
self.total_num_kv_heads * self.head_dim,
Expand Down
26 changes: 15 additions & 11 deletions vllm/model_executor/models/gemma4_mtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,20 +272,24 @@ def __init__(

layer_idx = extract_layer_index(prefix)
layer_type = config.layer_types[layer_idx]
is_full_attention = layer_type == "full_attention"
head_dim = (
getattr(config, "global_head_dim", config.head_dim)
if is_full_attention
else config.head_dim
)

use_k_eq_v = is_full_attention and getattr(config, "attention_k_eq_v", False)
if use_k_eq_v:
num_kv_heads = getattr(
config, "num_global_key_value_heads", config.num_key_value_heads
)
if hasattr(config, "is_heterogeneous"):
# Transformers >= 5.15.0
layer_config = config.per_layer_config[layer_idx]
head_dim = layer_config.head_dim
num_kv_heads = layer_config.num_key_value_heads
else:
# Transformers < 5.15.0
# Determine if this full-attention layer uses k_eq_v
# (laptop variant: no v_proj, K reused as V on full attention layers)
head_dim = config.head_dim
num_kv_heads = config.num_key_value_heads
if layer_type == "full_attention":
head_dim = getattr(config, "global_head_dim", head_dim)
if getattr(config, "attention_k_eq_v", False):
num_kv_heads = getattr(
config, "num_global_key_value_heads", num_kv_heads
)

self.self_attn = Gemma4MTPAttention(
config=config,
Expand Down
15 changes: 12 additions & 3 deletions vllm/model_executor/models/transformers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,18 +556,27 @@ def create_attention_instances(self) -> dict[int, Attention]:
):
per_layer_sliding_window = self.config.sliding_window

if getattr(text_config, "is_heterogeneous", False):
layer_head_size = self.model_config.get_head_size(layer_idx=i)
layer_num_kv_heads = self.model_config.get_num_kv_heads(
self.parallel_config, layer_idx=i
)
else:
layer_head_size = head_size
layer_num_kv_heads = num_kv_heads

attn_cls = (
EncoderOnlyAttention
if attn_type == AttentionType.ENCODER_ONLY
else Attention
)
attention_instances[i] = attn_cls(
num_heads=num_heads,
head_size=head_size,
head_size=layer_head_size,
# NOTE: We use Llama scale as default, if it's set by
# Transformers, it's updated in vllm_attention_forward
scale=head_size**-0.5,
num_kv_heads=num_kv_heads,
scale=layer_head_size**-0.5,
num_kv_heads=layer_num_kv_heads,
cache_config=self.cache_config,
quant_config=self.quant_config,
logits_soft_cap=logits_soft_cap,
Expand Down
42 changes: 36 additions & 6 deletions vllm/transformers_utils/model_arch_config_convertor.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,12 +601,42 @@ def is_mm_prefix_lm(self, supports_multimodal: bool = True) -> bool:
)

def get_head_size(self) -> int:
# Gemma4 uses dual head dimensions: head_dim (sliding attention)
# and global_head_dim (full attention). Return the largest so
# that attention backends allocate buffers large enough for both.
head_dim = getattr(self.hf_text_config, "head_dim", 0)
global_head_dim = getattr(self.hf_text_config, "global_head_dim", 0)
return max(head_dim, global_head_dim) or super().get_head_size()
# Gemma4 uses different head dimensions for sliding attention and full
# attention. Return the largest so that attention backends allocate buffers
# large enough for both.
text_config = self.hf_text_config
if hasattr(text_config, "is_heterogeneous"):
Comment thread
Isotr0py marked this conversation as resolved.
Resolved
# Transformers >= 5.15.0
head_dims = {
layer_type: text_config.per_layer_config[layer_type].head_dim
for layer_type in set(text_config.layer_types)
}
else:
# Transformers < 5.15.0
head_dims = {
"sliding_attention": getattr(text_config, "head_dim", 0),
"full_attention": getattr(text_config, "global_head_dim", 0),
}
return max(head_dims.values()) or super().get_head_size()

def get_total_num_kv_heads(self) -> int:
# When attention_k_eq_v is set, Gemma4 also varies KV heads per layer.
# Return the largest so KV cache buffers allocate large enough for every layer,
# mirroring get_head_size above.
text_config = self.hf_text_config
if hasattr(text_config, "is_heterogeneous"):
# Transformers >= 5.15.0
num_key_value_heads = {
layer_type: text_config.per_layer_config[layer_type].num_key_value_heads
for layer_type in set(text_config.layer_types)
}
else:
# Transformers < 5.15.0
num_key_value_heads = {
"sliding_attention": getattr(text_config, "num_key_value_heads", 0),
"full_attention": getattr(text_config, "num_global_key_value_heads", 0),
}
return max(num_key_value_heads.values()) or super().get_total_num_kv_heads()


class MossAudioModelArchConfigConvertor(ModelArchConfigConvertorBase):
Expand Down
Loading