Skip to content

Commit 9b462db

Browse files
justinchubyCopilot
andcommitted
Fuse LFM2 normalization and causal convolution
Use RMSNormalization stash_type for faithful fp32 accumulation and residual skip-norm fusion. Replace the decomposed short convolution with CausalConvWithState and derive global cache slots directly from graph input indices. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 1d66402 commit 9b462db

10 files changed

Lines changed: 161 additions & 105 deletions

File tree

‎src/mobius/components/_short_conv.py‎

Lines changed: 17 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -16,53 +16,36 @@
1616

1717

1818
class _DepthwiseShortConv1d(nn.Module):
19-
"""Depthwise Conv1D with a full-kernel recurrent cache."""
19+
"""Depthwise Conv1D backed by ``com.microsoft.CausalConvWithState``."""
2020

2121
def __init__(self, channels: int, kernel_size: int, *, bias: bool):
2222
super().__init__()
2323
self.weight = nn.Parameter([channels, 1, kernel_size])
2424
self.bias = nn.Parameter([channels]) if bias else None
2525
self._channels = channels
26-
self._kernel_size = kernel_size
2726

2827
def forward(
2928
self,
3029
op: OpBuilder,
3130
hidden_states: ir.Value,
3231
conv_state: ir.Value,
3332
) -> tuple[ir.Value, ir.Value]:
34-
# The cache contract is K-wide, but causal Conv only needs its newest
35-
# K-1 values. Appending T inputs then produces exactly T outputs.
36-
past = op.Slice(
37-
conv_state,
38-
op.Constant(value_ints=[1]),
39-
op.Constant(value_ints=[INT64_MAX]),
40-
op.Constant(value_ints=[2]),
41-
)
42-
conv_input = op.Concat(past, hidden_states, axis=2)
43-
if self.bias is None:
44-
conv_output = op.Conv(
45-
conv_input,
46-
self.weight,
47-
kernel_shape=[self._kernel_size],
48-
group=self._channels,
49-
)
50-
else:
51-
conv_output = op.Conv(
52-
conv_input,
53-
self.weight,
54-
self.bias,
55-
kernel_shape=[self._kernel_size],
56-
group=self._channels,
33+
bias = self.bias
34+
if bias is None:
35+
bias = op.Expand(
36+
op.CastLike(op.Constant(value_float=0.0), self.weight),
37+
op.Constant(value_ints=[self._channels]),
5738
)
58-
59-
present_state = op.Slice(
60-
conv_input,
61-
op.Constant(value_ints=[-self._kernel_size]),
62-
op.Constant(value_ints=[INT64_MAX]),
63-
op.Constant(value_ints=[2]),
39+
return op.CausalConvWithState(
40+
hidden_states,
41+
self.weight,
42+
bias,
43+
conv_state,
44+
activation="none",
45+
ndim=1,
46+
_domain="com.microsoft",
47+
_outputs=2,
6448
)
65-
return conv_output, present_state
6649

6750

6851
class GatedShortConv(nn.Module):
@@ -90,8 +73,8 @@ def forward(
9073
9174
Args:
9275
hidden_states: Input activations shaped ``(batch, seq, hidden)``.
93-
conv_state: Previous full convolution window shaped
94-
``(batch, hidden, kernel_size)``.
76+
conv_state: Previous convolution history shaped
77+
``(batch, hidden, kernel_size - 1)``.
9578
attention_mask: Optional padding mask shaped
9679
``(batch, past_seq + seq)``.
9780
"""

‎src/mobius/components/_short_conv_test.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ def test_gated_short_conv_builds_stateful_graph():
1111
component = GatedShortConv(hidden_size=16, kernel_size=3)
1212
builder, op, graph = create_test_builder()
1313
hidden_states = create_test_input(builder, "hidden_states", [1, 4, 16])
14-
conv_state = create_test_input(builder, "conv_state", [1, 16, 3])
14+
conv_state = create_test_input(builder, "conv_state", [1, 16, 2])
1515
attention_mask = create_test_input(builder, "attention_mask", [1, 4])
1616

1717
output, present_state = component(op, hidden_states, conv_state, attention_mask)
1818
builder._adapt_outputs([output, present_state], "")
1919

20-
assert any(node.op_type == "Conv" for node in graph)
20+
assert any(node.op_type == "CausalConvWithState" for node in graph)
2121
assert {name for name, _ in component.named_parameters()} == {
2222
"in_proj.weight",
2323
"conv.weight",

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -194,28 +194,28 @@ def _graph_input_names(model: ir.Model) -> list[str]:
194194
]
195195

196196

197-
def _count_kv_cache_layers(model: ir.Model | None) -> int | None:
198-
"""Return the number of ``past_key_values.{i}.key`` inputs in *model*.
199-
200-
ORT-GenAI binds ``num_hidden_layers`` KV cache pairs by name, so that
201-
field must reflect the graph rather than the architecture. The two differ
202-
for KV-layer-sharing models (Gemma 3n / Gemma 4), whose trailing layers
203-
borrow K,V from an earlier layer and therefore own no cache entry.
204-
205-
Returns ``None`` when *model* is absent or has no such inputs (e.g. a
206-
static-cache export, which uses ``key_cache.{i}`` instead), letting
207-
callers fall back to the config value.
197+
def _count_cache_layer_slots(model: ir.Model | None) -> int | None:
198+
"""Return the number of globally indexed cache slots required by *model*.
199+
200+
ORT-GenAI binds cache inputs by ``past_key_values.{i}.*`` names, so
201+
``num_hidden_layers`` must cover the highest global layer index in the
202+
graph. Counting only ``.key`` inputs undercounts hybrid models whose other
203+
layers carry convolution or recurrent state; counting all inputs overcounts
204+
key/value pairs. The required slot count is therefore ``max(i) + 1``.
205+
206+
This also preserves the smaller graph-derived count for KV-sharing models
207+
whose cache-owning layer indices form a shorter contiguous prefix. Returns
208+
``None`` when *model* is absent or has no dynamic-cache inputs (e.g. a
209+
static-cache export using ``key_cache.{i}``).
208210
"""
209211
if model is None:
210212
return None
211-
count = sum(
212-
1
213-
for inp in model.graph.inputs
214-
if inp.name is not None
215-
and inp.name.startswith("past_key_values.")
216-
and inp.name.endswith(".key")
217-
)
218-
return count or None
213+
layer_indices: set[int] = set()
214+
for inp in model.graph.inputs:
215+
parts = inp.name.split(".") if inp.name is not None else []
216+
if len(parts) >= 3 and parts[0] == "past_key_values" and parts[1].isdigit():
217+
layer_indices.add(int(parts[1]))
218+
return max(layer_indices) + 1 if layer_indices else None
219219

220220

221221
def _introspect_inputs(pkg: ModelPackage, key: str) -> dict[str, str] | None:
@@ -996,7 +996,7 @@ def _write_genai_config(
996996
decoder_inputs=decoder_inputs,
997997
decoder_filename=decoder_filename,
998998
supports_in_place_kv_cache=supports_in_place_kv_cache,
999-
num_kv_cache_layers=_count_kv_cache_layers(decoder_model),
999+
num_cache_layer_slots=_count_cache_layer_slots(decoder_model),
10001000
)
10011001

10021002
if is_vlm:

‎src/mobius/integrations/ort_genai/auto_export_test.py‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from mobius.integrations.ort_genai.auto_export import (
1717
_copy_tokenizer_files,
1818
_copy_tokenizer_files_from_local,
19-
_count_kv_cache_layers,
19+
_count_cache_layer_slots,
2020
_fix_chat_template,
2121
_fix_tokenizer_config,
2222
_graph_input_names,
@@ -2129,8 +2129,8 @@ def test_missing_key_returns_none(self):
21292129
assert _introspect_outputs(pkg, "vision_encoder") is None
21302130

21312131

2132-
class TestCountKvCacheLayers:
2133-
"""Tests for _count_kv_cache_layers() helper."""
2132+
class TestCountCacheLayerSlots:
2133+
"""Tests for _count_cache_layer_slots() helper."""
21342134

21352135
def test_counts_key_inputs(self):
21362136
"""Counts past_key_values.{i}.key inputs, not the value pairs."""
@@ -2144,15 +2144,26 @@ def test_counts_key_inputs(self):
21442144
"past_key_values.1.value",
21452145
]
21462146
)
2147-
assert _count_kv_cache_layers(model) == 2
2147+
assert _count_cache_layer_slots(model) == 2
2148+
2149+
def test_uses_global_indices_across_hybrid_cache_types(self):
2150+
model = _mock_model_with_inputs(
2151+
[
2152+
"past_key_values.0.conv_state",
2153+
"past_key_values.1.key",
2154+
"past_key_values.1.value",
2155+
"past_key_values.3.recurrent_state",
2156+
]
2157+
)
2158+
assert _count_cache_layer_slots(model) == 4
21482159

21492160
def test_returns_none_without_kv_cache(self):
21502161
"""A static-cache export (key_cache.{i}) falls back to the config."""
21512162
model = _mock_model_with_inputs(["input_ids", "key_cache.0", "value_cache.0"])
2152-
assert _count_kv_cache_layers(model) is None
2163+
assert _count_cache_layer_slots(model) is None
21532164

21542165
def test_returns_none_for_missing_model(self):
2155-
assert _count_kv_cache_layers(None) is None
2166+
assert _count_cache_layer_slots(None) is None
21562167

21572168

21582169
class TestGemma4RealModel:

‎src/mobius/integrations/ort_genai/genai_config.py‎

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def from_config(
232232
decoder_inputs: dict[str, str] | None = None,
233233
decoder_filename: str | None = None,
234234
supports_in_place_kv_cache: bool | None = None,
235-
num_kv_cache_layers: int | None = None,
235+
num_cache_layer_slots: int | None = None,
236236
) -> GenaiConfigGenerator:
237237
"""Create a generator from a BaseModelConfig-like dataclass.
238238
@@ -242,16 +242,13 @@ def from_config(
242242
overridden since they are often not on the model config.
243243
244244
Args:
245-
num_kv_cache_layers: Number of KV cache entries the exported
246-
decoder graph actually has. Overrides
245+
num_cache_layer_slots: Number of globally indexed cache slots the
246+
exported decoder graph requires. Overrides
247247
``config.num_hidden_layers`` for the ``num_hidden_layers``
248-
field written to ``genai_config.json`` — ORT-GenAI uses that
249-
field to decide how many ``past_key_values.%d.{key,value}``
250-
bindings to create, so it must match the graph, not the
251-
architecture. They differ for KV-layer-sharing models
252-
(Gemma 3n / Gemma 4), where the last
253-
``num_kv_shared_layers`` layers borrow K,V from an earlier
254-
layer and own no cache entry. ``None`` uses the config value.
248+
field written to ``genai_config.json``. This is smaller than
249+
the architecture count for KV-sharing models and retains global
250+
indices for hybrid KV/recurrent-cache models. ``None`` uses the
251+
config value.
255252
"""
256253
pad = pad_token_id
257254
if pad is None:
@@ -268,13 +265,9 @@ def from_config(
268265
vocab_size=config.vocab_size,
269266
hidden_size=config.hidden_size,
270267
num_hidden_layers=(
271-
config.num_hidden_layers
272-
if model_type == "lfm2"
273-
else (
274-
num_kv_cache_layers
275-
if num_kv_cache_layers is not None
276-
else config.num_hidden_layers
277-
)
268+
num_cache_layer_slots
269+
if num_cache_layer_slots is not None
270+
else config.num_hidden_layers
278271
),
279272
num_attention_heads=config.num_attention_heads,
280273
num_key_value_heads=config.num_key_value_heads,
@@ -288,7 +281,11 @@ def from_config(
288281
decoder_filename=decoder_filename,
289282
supports_in_place_kv_cache=supports_in_place_kv_cache,
290283
layer_types=getattr(config, "layer_types", None),
291-
conv_cache_size=getattr(config, "short_conv_kernel", None),
284+
conv_cache_size=(
285+
getattr(config, "short_conv_kernel", 1) - 1
286+
if hasattr(config, "short_conv_kernel")
287+
else None
288+
),
292289
)
293290

294291
def with_vision(
@@ -479,7 +476,9 @@ def generate(self) -> dict[str, Any]:
479476
}
480477
if self.model_type == "lfm2":
481478
decoder["layer_types"] = self._layer_types or []
482-
decoder["conv_cache_size"] = self._conv_cache_size or 3
479+
decoder["conv_cache_size"] = (
480+
self._conv_cache_size if self._conv_cache_size is not None else 3
481+
)
483482
decoder["inputs"]["past_conv_names"] = "past_key_values.%d.conv_state"
484483
decoder["outputs"]["present_conv_names"] = "present.%d.conv_state"
485484

‎src/mobius/integrations/ort_genai/genai_config_test.py‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -89,17 +89,31 @@ def test_lfm2_decoder_declares_hybrid_cache(self):
8989
num_key_value_heads=8,
9090
head_dim=64,
9191
layer_types=["conv", "conv", "full_attention", "conv"],
92-
conv_cache_size=3,
92+
conv_cache_size=2,
9393
)
9494

9595
decoder = gen.generate()["model"]["decoder"]
9696

9797
assert decoder["layer_types"] == ["conv", "conv", "full_attention", "conv"]
98-
assert decoder["conv_cache_size"] == 3
98+
assert decoder["conv_cache_size"] == 2
9999
assert decoder["inputs"]["past_conv_names"] == "past_key_values.%d.conv_state"
100100
assert decoder["outputs"]["present_conv_names"] == "present.%d.conv_state"
101101
assert gen.generate()["search"]["past_present_share_buffer"] is False
102102

103+
def test_lfm2_kernel_one_preserves_zero_width_cache(self):
104+
gen = GenaiConfigGenerator(
105+
"lfm2",
106+
vocab_size=256,
107+
hidden_size=64,
108+
num_hidden_layers=1,
109+
num_attention_heads=4,
110+
num_key_value_heads=2,
111+
head_dim=16,
112+
layer_types=["conv"],
113+
conv_cache_size=0,
114+
)
115+
assert gen.generate()["model"]["decoder"]["conv_cache_size"] == 0
116+
103117
def test_token_ids_included_when_set(self):
104118
"""Token IDs are included in the model section."""
105119
gen = GenaiConfigGenerator(
@@ -543,7 +557,7 @@ class FakeConfig:
543557
config = gen.generate()
544558
assert config["model"]["context_length"] == 4096
545559

546-
def test_num_kv_cache_layers_overrides_num_hidden_layers(self):
560+
def test_num_cache_layer_slots_overrides_num_hidden_layers(self):
547561
"""KV-sharing models report the graph's cache count, not the layer count.
548562
549563
Gemma 3n / Gemma 4 trailing layers borrow K,V from an earlier layer and
@@ -561,15 +575,15 @@ class FakeConfig:
561575
head_dim: int = 128
562576

563577
cfg = FakeConfig()
564-
gen = GenaiConfigGenerator.from_config(cfg, "gemma3n", num_kv_cache_layers=20)
578+
gen = GenaiConfigGenerator.from_config(cfg, "gemma3n", num_cache_layer_slots=20)
565579
assert gen.generate()["model"]["decoder"]["num_hidden_layers"] == 20
566580

567581
# None falls back to the config value.
568582
gen = GenaiConfigGenerator.from_config(cfg, "gemma3n")
569583
assert gen.generate()["model"]["decoder"]["num_hidden_layers"] == 35
570584

571-
def test_lfm2_keeps_global_layer_count(self):
572-
"""LFM2 indexes attention and convolution caches by global layer id."""
585+
def test_hybrid_cache_slots_keep_global_layer_count(self):
586+
"""Hybrid cache slots retain global layer indices without model checks."""
573587

574588
@dataclasses.dataclass
575589
class FakeConfig:
@@ -586,12 +600,11 @@ class FakeConfig:
586600

587601
gen = GenaiConfigGenerator.from_config(
588602
FakeConfig(),
589-
"lfm2",
590-
num_kv_cache_layers=6,
603+
"custom_hybrid",
604+
num_cache_layer_slots=14,
591605
)
592606
decoder = gen.generate()["model"]["decoder"]
593607
assert decoder["num_hidden_layers"] == 14
594-
assert decoder["layer_types"] == FakeConfig().layer_types
595608

596609

597610
def test_cuda_enables_decoder_graph_capture_only():

‎src/mobius/models/lfm2.py‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,17 @@ class Lfm2RMSNorm(RMSNorm):
2828
"""LFM2 RMSNorm with fp32 variance accumulation, matching Transformers."""
2929

3030
def forward(self, op: OpBuilder, hidden_states: ir.Value) -> ir.Value:
31-
hidden_states_f32 = op.Cast(hidden_states, to=ir.DataType.FLOAT)
32-
variance = op.ReduceMean(
33-
op.Mul(hidden_states_f32, hidden_states_f32),
34-
[-1],
35-
keepdims=1,
31+
# stash_type=FLOAT computes normalization in fp32, casts the normalized
32+
# activation back to the input dtype, then applies gamma. This is the
33+
# exact ordering used by Transformers' LlamaRMSNorm and also exposes the
34+
# standard op to the residual SkipSimplifiedLayerNorm fusion.
35+
return op.RMSNormalization(
36+
hidden_states,
37+
self.weight,
38+
axis=-1,
39+
epsilon=self.variance_epsilon,
40+
stash_type=ir.DataType.FLOAT,
3641
)
37-
normalized_f32 = op.Mul(
38-
hidden_states_f32,
39-
op.Reciprocal(op.Sqrt(op.Add(variance, self.variance_epsilon))),
40-
)
41-
# Transformers casts the normalized activation back before applying gamma.
42-
return op.Mul(op.CastLike(normalized_f32, hidden_states), self.weight)
4342

4443

4544
class Lfm2DecoderLayer(nn.Module):

0 commit comments

Comments
 (0)