Fix Gemma 4 for upcoming Transformers version (#49797)

Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
This commit is contained in:
Harry Mellor
2026-08-10 07:48:26 +00:00
committed by GitHub
parent 81840a172f
commit 70b84f0bcb
15 changed files with 569 additions and 105 deletions
+27 -10
View File
@@ -886,9 +886,7 @@ class ModelConfig:
)
return supports_mm
def get_model_arch_config(
self,
) -> ModelArchitectureConfig:
def get_model_arch_config(self) -> ModelArchitectureConfig:
convertor_cls = MODEL_ARCH_CONFIG_CONVERTORS.get(
self.hf_config.model_type, ModelArchConfigConvertorBase
)
@@ -982,8 +980,8 @@ class ModelConfig:
"""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
@@ -1473,21 +1471,40 @@ class ModelConfig:
"""Returns the total number of KV heads."""
return self.model_arch_config.total_num_kv_heads
def get_num_kv_heads(self, parallel_config: ParallelConfig) -> int:
"""Returns the number of KV heads per GPU."""
def get_num_kv_heads(
self,
parallel_config: ParallelConfig,
arch_config: ModelArchitectureConfig | None = None,
) -> int:
"""Returns the number of KV heads per GPU.
Pass ``arch_config`` (from ``model_arch_config[layer_idx]``) to size a
single layer of a heterogeneous model rather than the model as a whole.
"""
if self.use_mla:
# When using MLA during decode it becomes MQA
return 1
total_num_kv_heads = self.get_total_num_kv_heads()
arch_config = arch_config or self.model_arch_config
total_num_kv_heads = arch_config.total_num_kv_heads
# 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
# parallel size so each GPU has at least one KV head.
return max(1, total_num_kv_heads // parallel_config.tensor_parallel_size)
def get_num_attention_heads(self, parallel_config: ParallelConfig) -> int:
num_heads = self.model_arch_config.total_num_attention_heads
def get_num_attention_heads(
self,
parallel_config: ParallelConfig,
arch_config: ModelArchitectureConfig | None = None,
) -> int:
"""Returns the number of attention heads per GPU.
Pass ``arch_config`` (from ``model_arch_config[layer_idx]``) to size a
single layer of a heterogeneous model rather than the model as a whole.
"""
arch_config = arch_config or self.model_arch_config
num_heads = arch_config.total_num_attention_heads
return num_heads // parallel_config.tensor_parallel_size
def get_num_experts(self) -> int:
+77
View File
@@ -1,5 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from copy import copy
from dataclasses import fields as dataclass_fields
from typing import Any
from pydantic import ConfigDict
@@ -64,3 +66,78 @@ class ModelArchitectureConfig:
derived_max_model_len_and_key: tuple[float, str | None]
"""Derived maximum model length and key from the hf config."""
per_layer_overrides: "list[dict[str, Any]] | None" = None
"""Per-layer values for the fields that vary, `None` unless some field does.
One dict per layer, holding only the fields whose value differs from the
whole-model value above. Everything else is read from the whole-model config,
so later edits to it are visible through `self[layer_idx]`."""
def __getitem__(self, layer_idx: int) -> "ModelArchitectureConfig":
"""ModelArchitectureConfig for a specific layer.
Returns `self` when no field varies by layer, so callers never need to
branch on heterogeneity. Mirrors `PreTrainedConfig.per_layer_config[i]`.
"""
if layer_idx < 0:
# Homogeneous configs would ignore a negative index and heterogeneous
# ones would wrap, so an off-by-one would only show up on the models
# this exists for. Reject it for both.
raise IndexError(f"layer index must not be negative, got {layer_idx}")
if self.per_layer_overrides is None:
return self
layer = copy(self)
object.__setattr__(layer, "per_layer_overrides", None)
for name, value in self.per_layer_overrides[layer_idx].items():
object.__setattr__(layer, name, value)
return layer
@classmethod
def from_layers(
cls, layers: "list[ModelArchitectureConfig]"
) -> "ModelArchitectureConfig":
"""Whole-model config for a checkpoint whose layers differ.
Fields that agree across layers are taken as they are. Fields that differ
are collapsed with `max`, so buffers are sized for the largest layer, and
the differing values are kept per layer. No field is named here: which
ones vary is whatever the checkpoint says.
"""
if not layers:
raise ValueError("a model must have at least one layer")
merged: dict[str, Any] = {}
overrides: list[dict[str, Any]] = [{} for _ in layers]
for f in dataclass_fields(cls):
if f.name == "per_layer_overrides":
continue
values = [getattr(layer, f.name) for layer in layers]
if all(value == values[0] for value in values):
merged[f.name] = values[0]
continue
# `bool` is an `int`, so an exact type check is what keeps a varying
# flag from collapsing to `any`. `is_deepseek_mla` doing that would
# make `use_mla` true model wide, and `get_num_kv_heads` then returns
# 1 for every layer, discarding the overrides built here.
if not all(type(value) in (int, float) for value in values):
raise ValueError(
f"{f.name!r} varies across layers and has no whole-model "
f"value: {sorted(set(map(repr, values)))}. Only numeric "
f"fields collapse (with `max`, to size buffers for the "
f"largest layer); give this one an explicit rule in "
f"ModelArchitectureConfig.from_layers."
)
merged[f.name] = max(values)
for override, value in zip(overrides, values):
if value != merged[f.name]:
override[f.name] = value
if len(layers) != merged["total_num_hidden_layers"]:
raise ValueError(
f"got {len(layers)} per-layer configs for a model with "
f"{merged['total_num_hidden_layers']} layers"
)
# A checkpoint can be heterogeneous over attributes vLLM never reads, in
# which case there is nothing to keep the layers apart for.
return cls(**merged, per_layer_overrides=overrides if any(overrides) else None)