Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
perf(gemma4): read the source layer's kv slab on kv-shared layers
  • Loading branch information
ischencheng committed Nov 12, 2026
commit 34964775b6721d8ef8e8da87e9ad24220b5380fd
2 changes: 2 additions & 0 deletions python/freetoken/kvcache/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ def create_kvcache_pool(
# slabs.
layer_ids: tuple[int, ...] | None = None
kv_specs = [s for s in model_config.kv_cache_group_specs() if s.num_layers > 0]
if any(s.shared_layers for s in kv_specs):
raise NotImplementedError("KV-shared layers are only mapped by the hybrid full/SWA pool")
if model_config.has_linear_attention:
assert len(kv_specs) == 1, (
f"hybrid-linear models support one paged-KV group, got "
Expand Down
8 changes: 8 additions & 0 deletions python/freetoken/kvcache/hybrid_swa_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def __init__(
"swa": self.swa_kv_pool,
}
self.layers_mapping = self._build_layers_mapping(num_layers, specs)
self._shared_layers = frozenset(layer_id for spec in specs.values() for layer_id, _ in spec.shared_layers)
if self._swa_paged:
self._init_swa_paged_state()

Expand Down Expand Up @@ -116,6 +117,11 @@ def _build_layers_mapping(
if mapping[layer_id] is not None:
raise ValueError(f"KV layer id {layer_id} appears in more than one group")
mapping[layer_id] = _LayerRef(group=group_name, index=local_index)
for group_name in ("full", "swa"):
for layer_id, source in specs[group_name].shared_layers:
if source not in specs[group_name].layer_ids or mapping[layer_id] is not None:
raise ValueError(f"KV-shared layer {layer_id} cannot read layer {source}'s {group_name} slab")
mapping[layer_id] = mapping[source]

missing = [layer_id for layer_id, ref in enumerate(mapping) if ref is None]
if missing:
Expand Down Expand Up @@ -220,6 +226,8 @@ def store_kv(
out_loc: torch.Tensor,
layer_id: int,
) -> None:
if layer_id in self._shared_layers:
return # its source layer stored these rows earlier in the same forward
ref = self.layers_mapping[layer_id]
storage = self._storages[ref.group]
indices = out_loc
Expand Down
17 changes: 15 additions & 2 deletions python/freetoken/models/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ class KVCacheGroupSpec:
# Attention-type taxonomy value for this group; drives the backend capability
# matrix and (with the pool factory) selects the KV pool family.
attn_type: AttnType = AttnType.FULL
# (layer, source) pairs: layers of this group that read the source's slab and own none.
# They are not in ``layer_ids``, so neither the pool nor the cost model gives them a slab.
shared_layers: Tuple[Tuple[int, int], ...] = ()

@property
def num_layers(self) -> int:
Expand Down Expand Up @@ -382,6 +385,8 @@ class ModelConfig:
# Generic execution-path capability flags (set by a model's parse_config) so the engine and
# factories stay model-agnostic instead of branching on dsv4_args:
single_stream_only: bool = False # model runs one sequence at a time -> force bs=1
# (layer, source) pairs: the layer attends over the KV the source layer stored and stores none
kv_shared_layers: Tuple[Tuple[int, int], ...] = ()
# Extra per-request tensors riding the LinearStatePool slots (see SlotStateSpec);
# () for models without any. Requires a linear-attention group to ride on.
slot_states: Tuple[SlotStateSpec, ...] = ()
Expand Down Expand Up @@ -498,13 +503,21 @@ def kv_cache_group_specs(self) -> Tuple[KVCacheGroupSpec, ...]:
),
)

sources = dict(self.kv_shared_layers)

def split(group) -> dict:
return dict(
layer_ids=tuple(i for i in group.layer_ids if i not in sources),
shared_layers=tuple((i, sources[i]) for i in group.layer_ids if i in sources),
)

specs: list[KVCacheGroupSpec] = []
for group in self.attention_groups:
if isinstance(group, FullAttentionGroupConfig):
specs.append(
KVCacheGroupSpec(
name=group.name,
layer_ids=group.layer_ids,
**split(group),
num_kv_heads=group.num_kv_heads,
head_dim=group.head_dim,
sliding_window=None,
Expand All @@ -519,7 +532,7 @@ def kv_cache_group_specs(self) -> Tuple[KVCacheGroupSpec, ...]:
specs.append(
KVCacheGroupSpec(
name=group.name,
layer_ids=group.layer_ids,
**split(group),
num_kv_heads=group.num_kv_heads,
head_dim=group.head_dim,
sliding_window=group.sliding_window,
Expand Down
4 changes: 2 additions & 2 deletions python/freetoken/models/gemma4/attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ class Gemma4Attention(BaseOP):

On E2B / E4B the KV-shared tail projects q only and attends over the k, v of the last
earlier layer of its attention type. That layer hands its rows over in ``shared_kv``, a
dict living for one forward, so a captured graph records the same tensors. Each shared
layer still stores them in its own KV slab; reading the source's slab would save that memory.
dict living for one forward, so a captured graph records the same tensors. The KV pool
maps a shared layer onto its source's slab and skips its store (``kv_shared_layers``).
"""

def __init__(self, config: ModelConfig, layer_id: int, *, prefix: str = ""):
Expand Down
30 changes: 21 additions & 9 deletions python/freetoken/models/gemma4/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ def is_kv_shared(self, layer_id: int) -> bool:
def is_kv_source(self, layer_id: int, group_layer_ids: tuple[int, ...]) -> bool:
return layer_id == max((i for i in group_layer_ids if i < self.first_kv_shared_layer), default=None)

def kv_shared_layers(self, *groups_layer_ids: tuple[int, ...]) -> tuple[tuple[int, int], ...]:
"""``ModelConfig.kv_shared_layers``: each shared layer paired with its group's source."""
pairs = []
for layer_ids in groups_layer_ids:
source = next((i for i in layer_ids if self.is_kv_source(i, layer_ids)), None)
# no earlier layer of this type: nothing to read, so those layers keep their own slabs
if source is not None:
pairs += [(i, source) for i in layer_ids if self.is_kv_shared(i)]
return tuple(sorted(pairs))


def gemma4_e_args(
num_layers: int,
Expand Down Expand Up @@ -201,6 +211,15 @@ def parse_config(hf_config: Any) -> ModelConfig:
# checkpoint's own ignore-list.
expert_quant = detect_expert_quant(top_cfg)
dense_quant = "nvfp4" if (expert_quant == "nvfp4" and not num_experts > 0) else "none"
# Gemma4UnifiedTextConfig omits the E-series fields
e_args = gemma4_e_args(
cfg.num_hidden_layers,
getattr(cfg, "hidden_size_per_layer_input", None) or 0,
getattr(cfg, "vocab_size_per_layer_input", None) or 0,
getattr(cfg, "num_kv_shared_layers", None) or 0,
num_experts,
cfg.intermediate_size * (2 if getattr(cfg, "use_double_wide_mlp", False) else 1),
)

return ModelConfig(
num_layers=cfg.num_hidden_layers,
Expand Down Expand Up @@ -229,15 +248,8 @@ def parse_config(hf_config: Any) -> ModelConfig:
embedding_scale=float(cfg.hidden_size) ** 0.5,
vision_config=_parse_vision_config(top_cfg, cfg.hidden_size),
image_token_id=getattr(top_cfg, "image_token_id", None),
# Gemma4UnifiedTextConfig omits the E-series fields
gemma4_e_args=gemma4_e_args(
cfg.num_hidden_layers,
getattr(cfg, "hidden_size_per_layer_input", None) or 0,
getattr(cfg, "vocab_size_per_layer_input", None) or 0,
getattr(cfg, "num_kv_shared_layers", None) or 0,
num_experts,
cfg.intermediate_size * (2 if getattr(cfg, "use_double_wide_mlp", False) else 1),
),
gemma4_e_args=e_args,
kv_shared_layers=e_args.kv_shared_layers(full_layer_ids, sliding_layer_ids) if e_args is not None else (),
attention_groups=(
FullAttentionGroupConfig(
name="full",
Expand Down
1 change: 1 addition & 0 deletions python/freetoken/models/gemma4/gguf.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ def g(key: str):
vision_config=vision_config,
image_token_id=getattr(shim, "image_token_id", None),
gemma4_e_args=e_args,
kv_shared_layers=e_args.kv_shared_layers(full_layer_ids, swa_layer_ids) if e_args is not None else (),
attention_groups=(
FullAttentionGroupConfig(
name="full",
Expand Down
26 changes: 26 additions & 0 deletions tests/models/gemma4/test_e_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,32 @@ def test_kv_source_is_the_last_unshared_layer_of_each_attention_type():
assert [i for i in swa.layer_ids if args.is_kv_source(i, swa.layer_ids)] == [13]


@pytest.mark.parametrize("kv_format", ["none", "int8_per_token_head"])
@pytest.mark.parametrize("release, full_slabs, swa_slabs", [(E2B, 3, 12), (E4B, 4, 20)])
def test_shared_layers_read_their_source_slab_and_own_none(release, full_slabs, swa_slabs, kv_format):
from freetoken.kvcache import create_kvcache_pool
from freetoken.kvcache.format import KV_FORMATS

config = parse_config(_hf_config(release))
pool = create_kvcache_pool(
model_config=config, num_pages=2, page_size=16, num_swa_tokens=8,
dtype=torch.bfloat16, device=torch.device("cpu"), kv_format=KV_FORMATS[kv_format],
)

assert pool.full_kv_pool.buffer.shape[1] == full_slabs
assert pool.swa_kv_pool.buffer.shape[1] == swa_slabs
args = config.gemma4_e_args
for group in config.attention_groups:
(source,) = [i for i in group.layer_ids if args.is_kv_source(i, group.layer_ids)]
for i in filter(args.is_kv_shared, group.layer_ids):
assert pool.k_cache(i).data_ptr() == pool.k_cache(source).data_ptr()
assert pool.v_cache(i).data_ptr() == pool.v_cache(source).data_ptr()
if kv_format != "none":
# a shared layer reading zero scales would only show up as worse 8-bit outputs
assert pool.k_scale(i).data_ptr() == pool.k_scale(source).data_ptr()
assert pool.v_scale(i).data_ptr() == pool.v_scale(source).data_ptr()


def test_model_shapes_match_the_e2b_checkpoint():
state = _meta_model(parse_config(_hf_config(E2B))).state_dict()

Expand Down
Loading