Skip to content

Commit e73e0a5

Browse files
justinchubyCopilot
andauthored
fix: L2 test failures - memory budget, XLM/XLNet activation (#224)
This pull request introduces several improvements and fixes for model configuration extraction, focusing on more robust handling of activation functions, RoPE (Rotary Position Embedding) detection, and Mixture-of-Experts (MoE) parameters. It also improves support for models with non-standard or missing config fields and adds targeted tests for new fallback logic. **Configuration Extraction Improvements:** * Added a comprehensive `_resolve_hidden_act` function to robustly extract the activation function from HuggingFace configs, supporting a wide range of field names and fallback patterns (e.g., `ff_activation`, `gelu_activation`, Qwen/CTRL defaults) (`src/mobius/_configs.py`, [[1]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aR31-R61) [[2]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aL967-R1042). * Improved RoPE detection logic to recognize implicit RoPE usage in models that don't expose `rope_scaling` or `rope_parameters`, using model-type-specific defaults and non-default `rope_theta` as signals (`src/mobius/_configs.py`, [[1]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aR317-R334) [[2]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aL316-R380) [[3]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aR978-R986). * Enhanced MoE parameter extraction with additional field fallbacks and logic for shared expert size calculation, supporting more model variants (ERNIE, GLM, Hunyuan) (`src/mobius/_configs.py`, [[1]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aL1132-R1211) [[2]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aR1542-R1559). **Vision and Numeric Field Handling:** * Improved handling of vision model configs where hidden sizes or image sizes may be lists or dicts, ensuring correct scalar extraction for multi-stage models (e.g., Florence2, PVT-v2) (`src/mobius/_configs.py`, [[1]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aL424-R491) [[2]](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aL1450-R1529). **Testing and Validation:** * Added targeted tests for activation function extraction fallbacks to ensure correct behavior for various config patterns (e.g., XLNet, XLM) (`src/mobius/_configs_test.py`, [src/mobius/_configs_test.pyR977-R1036](diffhunk://#diff-731306b65028c2c328cb51b5b913709558032a78c6b87949e4d09240894c35c1R977-R1036)). * Updated the architecture validation test suite with more explicit skip reasons for models with missing or non-standard vision configs, and improved config resolution for Qwen3-Omni (`tests/arch_validation_test.py`, [[1]](diffhunk://#diff-605a9a76abfdb6fe5972842956c1abbd489a12ece1c1b2d7d14ca64d29fe36cbL50-R55) [[2]](diffhunk://#diff-605a9a76abfdb6fe5972842956c1abbd489a12ece1c1b2d7d14ca64d29fe36cbL104-R100). **Other Fixes:** * Mapped `"xielu"` activation to `silu` in the activation registry to prevent crashes in base MLP construction for Apertus models (`src/mobius/components/_activations.py`, [src/mobius/components/_activations.pyR86-R91](diffhunk://#diff-e063741e948256ed0e92721271b783756e05a8d7ec6ead98745e7725aa16c4c5R86-R91)). * For MLA models (MiniCPM3, DeepSeek-V2), ensured rotary embedding applies to the correct head dimension (`src/mobius/components/_rotary_embedding.py`, [src/mobius/components/_rotary_embedding.pyL18-R21](diffhunk://#diff-c82f6b31190bef4f731dd6d05639a59fe4bcead50ef185208b6b8cb55febd62eL18-R21)). * Set the correct config class for `LongcatFlashCausalLMModel` (`src/mobius/models/longcat_flash.py`, [[1]](diffhunk://#diff-ec4e78dd6ffd3e8372c228067e7f6307a410a5fed3ac963369d1d5f818df0028L21-R21) [[2]](diffhunk://#diff-ec4e78dd6ffd3e8372c228067e7f6307a410a5fed3ac963369d1d5f818df0028R438). * Ensured `Sam2Config` defaults to `"gelu"` activation if not explicitly set (`src/mobius/_configs.py`, [src/mobius/_configs.pyR1933-R1936](diffhunk://#diff-8d2bbd9d3e7313b834f95b7d3260a3a15173d37d9ee5dd344f863d666f172f7aR1933-R1936)). These changes collectively improve the robustness and coverage of model config parsing, especially for edge cases and recent model architectures. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 93f0f55 commit e73e0a5

8 files changed

Lines changed: 303 additions & 88 deletions

File tree

‎src/mobius/_config_resolver.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,20 @@ def _dict_to_pretrained_config(d: dict):
115115
"""
116116
import transformers
117117

118+
# Some composite configs (e.g. Phi4-MM) have rope_scaling at the
119+
# top level without max_position_embeddings, which crashes
120+
# PretrainedConfig.__post_init__ rope standardization. Strip rope
121+
# fields proactively when the guard field is absent — the nested
122+
# text_config will carry its own rope_scaling.
123+
has_rope_fields = "rope_scaling" in d or "rope_parameters" in d
124+
has_max_pos = "max_position_embeddings" in d
125+
if has_rope_fields and not has_max_pos:
126+
logger.debug(
127+
"Stripping top-level rope fields from %s config: "
128+
"rope_scaling present without max_position_embeddings",
129+
d.get("model_type", "unknown"),
130+
)
131+
d = {k: v for k, v in d.items() if k not in ("rope_scaling", "rope_parameters")}
118132
config = transformers.PretrainedConfig(**d)
119133
# Recursively convert known nested config keys
120134
nested_keys = (

‎src/mobius/_configs.py‎

Lines changed: 143 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from __future__ import annotations
55

66
import dataclasses
7+
import math
78

89
import onnx_ir as ir
910
import torch
@@ -27,6 +28,37 @@ def _resolve_dtype(config) -> ir.DataType | None:
2728
return None
2829

2930

31+
def _resolve_hidden_act(config, model_type: str) -> str | None:
32+
"""Resolve the hidden activation function from HF config patterns.
33+
34+
Fallback order (first truthy value wins):
35+
hidden_act — standard field (most models)
36+
hidden_activation — some encoder models
37+
activation_function — GPT-2 family
38+
ff_activation — XLNet
39+
dense_act_fn — some BERT variants
40+
activation — generic fallback
41+
afn — older BERT configs
42+
"silu" (qwen) — Qwen v1 hardcodes silu; no activation attr
43+
"gelu" (XLM) — gelu_activation=True is a boolean flag
44+
"relu" (ctrl) — CTRL hardcodes relu; no hidden_act attr
45+
"""
46+
return (
47+
getattr(config, "hidden_act", None)
48+
or getattr(config, "hidden_activation", None)
49+
or getattr(config, "activation_function", None)
50+
or getattr(config, "ff_activation", None)
51+
or getattr(config, "dense_act_fn", None)
52+
or getattr(config, "activation", None)
53+
or getattr(config, "afn", None)
54+
or ("silu" if model_type in ("qwen",) else None)
55+
# gelu_activation is a boolean (XLM) — must be after all string
56+
# attrs so it cannot override an explicit hidden_act.
57+
or ("gelu" if getattr(config, "gelu_activation", False) else None)
58+
or ("relu" if model_type in ("ctrl",) else None)
59+
)
60+
61+
3062
def _nested_rope_theta(rope_scaling: dict, key: str) -> float | None:
3163
"""Extract rope_theta from a nested rope_scaling dict (e.g. Gemma3)."""
3264
sub = rope_scaling.get(key)
@@ -282,6 +314,30 @@ def _first_not_none(*values, default=None):
282314
return default
283315

284316

317+
# Models that use RoPE but hardcode rope_theta entirely in model __init__,
318+
# not in config JSON. These are NOT detectable via config introspection
319+
# without trust_remote_code. When a new model fails L2 with missing RoPE:
320+
# 1. Confirm the model's HF source uses rotary embeddings
321+
# 2. Find the hardcoded rope_theta in the transformers source
322+
# 3. Add an entry here: model_type → rope_theta
323+
# TODO: migrate to a registry annotation (uses_rope: bool, rope_theta: float)
324+
# once the registry schema supports per-model capability flags.
325+
_IMPLICIT_ROPE_DEFAULTS: dict[str, float] = {
326+
# chatglm: config JSON has no rope_theta/rope_scaling/rotary_* attrs;
327+
# uses default rope_theta=10000.0 hardcoded in modeling code.
328+
"chatglm": 10_000.0,
329+
# deepseek_vl_v2: config JSON has no rope_theta attr;
330+
# uses default rope_theta=10000.0 hardcoded in modeling code.
331+
"deepseek_vl_v2": 10_000.0,
332+
# jamba: config JSON has no rope_theta/rope_scaling/rotary_* attrs;
333+
# uses rope_theta=8000.0 hardcoded in modeling code.
334+
"jamba": 8_000.0,
335+
# NOTE: qwen3_omni_moe removed — its config JSON contains
336+
# rope_scaling (with embedded rope_theta=1e6), so
337+
# _extract_rope_config() already handles it via the rope_scaling path.
338+
}
339+
340+
285341
def _extract_rope_config(config) -> RoPEConfig | None:
286342
"""Extract and normalize RoPE-related config fields.
287343
@@ -290,19 +346,24 @@ def _extract_rope_config(config) -> RoPEConfig | None:
290346
291347
Returns ``None`` when the source config has no RoPE signal at all —
292348
i.e. it declares neither the modern ``rope_parameters``/``rope_scaling``
293-
fields nor the legacy ``rotary_dim``/``rotary_pct``/``rotary_emb_base``
294-
fields. This is the "NoPE" case (e.g. NemotronH, GraniteMoeHybrid,
295-
GPT-2 family, BERT family, OPT) — the model does not use rotary
296-
position embeddings at all, and callers should treat RoPE as absent
297-
rather than manufacturing defaults that would silently introduce RoPE
298-
operations into the ONNX graph.
299-
300-
Note: ``rope_theta`` alone is NOT a sufficient RoPE signal because
301-
models like NemotronH carry ``rope_theta`` in their config as dead
302-
data despite not using RoPE. HuggingFace's ``rope_parameters`` field
303-
(populated by ``PretrainedConfig.__post_init__``) is the authoritative
304-
modern signal; legacy GPT-J / GPT-NeoX / CodeGen models predate it
305-
and use the ``rotary_*`` fields instead.
349+
fields, nor the legacy ``rotary_dim``/``rotary_pct``/``rotary_emb_base``
350+
fields, nor a non-default ``rope_theta``. This is the "NoPE" case
351+
(e.g. NemotronH, GraniteMoeHybrid, GPT-2 family, BERT family, OPT) —
352+
the model does not use rotary position embeddings at all, and callers
353+
should treat RoPE as absent rather than manufacturing defaults that
354+
would silently introduce RoPE operations into the ONNX graph.
355+
356+
RoPE signal detection:
357+
- ``rope_parameters`` / ``rope_scaling``: authoritative modern signal
358+
(populated by ``PretrainedConfig.__post_init__``).
359+
- ``rotary_dim`` / ``rotary_pct`` / ``rotary_emb_base``: legacy
360+
signal used by GPT-J / GPT-NeoX / CodeGen models that predate
361+
``rope_parameters``.
362+
- ``rope_theta`` with a non-default value (≠ 10000.0): treated as a
363+
RoPE indicator for models like Arctic and Jamba that set a custom
364+
``rope_theta`` without exposing ``rope_scaling``. The HF default
365+
of 10000.0 is excluded via ``math.isclose()`` because NoPE models
366+
(e.g. NemotronH) inherit it as dead config data.
306367
"""
307368
# Check for RoPE signals BEFORE the `or {}` fallback below —
308369
# `or {}` converts None to empty dict, destroying the absence signal.
@@ -313,7 +374,21 @@ def _extract_rope_config(config) -> RoPEConfig | None:
313374
or getattr(config, "rotary_pct", None) is not None
314375
or getattr(config, "rotary_emb_base", None) is not None
315376
)
316-
if raw_rope_scaling is None and raw_rope_parameters is None and not has_legacy_rope:
377+
# rope_theta alone is a weaker signal but still indicates RoPE intent
378+
# for many models (Arctic, Jamba, etc.) that don't set rope_scaling.
379+
# Only treat it as a signal when it differs from the common default
380+
# (10000.0) to avoid false positives on NoPE models that inherit
381+
# rope_theta as dead config data.
382+
raw_rope_theta = getattr(config, "rope_theta", None)
383+
has_nondefault_rope_theta = raw_rope_theta is not None and not math.isclose(
384+
raw_rope_theta, 10_000.0
385+
)
386+
if (
387+
raw_rope_scaling is None
388+
and raw_rope_parameters is None
389+
and not has_legacy_rope
390+
and not has_nondefault_rope_theta
391+
):
317392
return None
318393

319394
rope_scaling = raw_rope_scaling or {}
@@ -421,8 +496,10 @@ def _extract_vision_config(config, parent_config, model_type: str) -> dict:
421496
_intermediate = getattr(vc, "intermediate_size", None)
422497
if _intermediate is None:
423498
_mlp_ratio = getattr(vc, "mlp_ratio", None)
424-
if _mlp_ratio is not None and _vis_hidden is not None:
425-
_intermediate = int(_vis_hidden * _mlp_ratio)
499+
# _vis_hidden may be a list for multi-stage models (Florence2)
500+
_scalar_hidden = _first(_vis_hidden) if _vis_hidden is not None else None
501+
if _mlp_ratio is not None and _scalar_hidden is not None:
502+
_intermediate = int(_scalar_hidden * _mlp_ratio)
426503

427504
vision_fields.update(
428505
hidden_size=_vis_hidden,
@@ -909,6 +986,15 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
909986
rope_config = _extract_rope_config(config)
910987
mrope_fields = _extract_mrope_fields(config)
911988

989+
# Models that use RoPE but don't expose rope_scaling/rope_parameters
990+
# in their HF config (e.g. loaded without trust_remote_code, or
991+
# because the HF code hardcodes defaults internally).
992+
if rope_config is None and model_type in _IMPLICIT_ROPE_DEFAULTS:
993+
rope_config = RoPEConfig(
994+
rope_type="default",
995+
rope_theta=_IMPLICIT_ROPE_DEFAULTS[model_type],
996+
)
997+
912998
# Some hierarchical models (Segformer, Swin) use plural list attrs
913999
# instead of scalar ones. Resolve to a scalar for the base config.
9141000
hidden_size = (
@@ -964,16 +1050,7 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
9641050
or getattr(config, "decoder_ffn_dim", None)
9651051
or 4 * _as_int(hidden_size)
9661052
),
967-
hidden_act=(
968-
getattr(config, "hidden_act", None)
969-
or getattr(config, "hidden_activation", None)
970-
or getattr(config, "activation_function", None)
971-
or getattr(config, "dense_act_fn", None)
972-
or getattr(config, "activation", None)
973-
or getattr(config, "afn", None)
974-
# Qwen v1 configs have no activation attr; default to silu
975-
or ("silu" if model_type in ("qwen",) else None)
976-
),
1053+
hidden_act=_resolve_hidden_act(config, model_type),
9771054
layer_types=(
9781055
getattr(config, "layer_types", None)
9791056
or getattr(config, "attention_layers", None)
@@ -1129,14 +1206,20 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
11291206
),
11301207
# MoE
11311208
num_local_experts=(
1132-
getattr(config, "num_local_experts", None)
1133-
or getattr(config, "num_experts", None)
1134-
or getattr(config, "n_routed_experts", None)
1209+
_first(getattr(config, "num_local_experts", None))
1210+
or _first(getattr(config, "num_experts", None))
1211+
or _first(getattr(config, "n_routed_experts", None))
1212+
or _first(getattr(config, "moe_num_experts", None))
1213+
),
1214+
num_experts_per_tok=(
1215+
_first(getattr(config, "num_experts_per_tok", None))
1216+
or _first(getattr(config, "moe_k", None))
1217+
or _first(getattr(config, "moe_topk", None))
11351218
),
1136-
num_experts_per_tok=(getattr(config, "num_experts_per_tok", None)),
1137-
moe_intermediate_size=(getattr(config, "moe_intermediate_size", None)),
1219+
moe_intermediate_size=_first(getattr(config, "moe_intermediate_size", None)),
11381220
shared_expert_intermediate_size=(
11391221
getattr(config, "shared_expert_intermediate_size", None)
1222+
or _shared_expert_size(config)
11401223
),
11411224
norm_topk_prob=(getattr(config, "norm_topk_prob", True)),
11421225
post_feedforward_norm=(model_type in ("flex_olmo",)),
@@ -1447,8 +1530,14 @@ def _as_int(value) -> int:
14471530
"""Coerce *value* to int, taking the first element if it is a list/tuple.
14481531
14491532
Some HuggingFace configs express ``image_size`` or ``patch_size`` as
1450-
``[H, W]`` lists. We take the first element (height) for simplicity.
1533+
``[H, W]`` lists or ``{"height": H, "width": W}`` dicts.
1534+
We take the first element (height) for simplicity.
14511535
"""
1536+
if isinstance(value, dict):
1537+
# PVT-v2 etc. use {"height": H, "width": W} for image_size
1538+
if "height" in value:
1539+
return int(value["height"])
1540+
return int(next(iter(value.values())))
14521541
if isinstance(value, (list, tuple)):
14531542
return int(value[0])
14541543
return int(value)
@@ -1461,6 +1550,24 @@ def _first(value):
14611550
return value
14621551

14631552

1553+
def _shared_expert_size(config) -> int | None:
1554+
"""Compute shared_expert_intermediate_size from moe_intermediate_size * n_shared_experts.
1555+
1556+
ERNIE-4.5 uses ``moe_num_shared_experts``, GLM-4.5 uses ``n_shared_experts``,
1557+
and Hunyuan uses ``num_shared_expert`` (singular, per-layer list).
1558+
Both share ``moe_intermediate_size`` as the per-expert FFN hidden size.
1559+
"""
1560+
moe_dim = _first(getattr(config, "moe_intermediate_size", None))
1561+
n_shared = _first(
1562+
getattr(config, "moe_num_shared_experts", None)
1563+
or getattr(config, "n_shared_experts", None)
1564+
or getattr(config, "num_shared_expert", None)
1565+
)
1566+
if moe_dim is not None and n_shared is not None:
1567+
return int(moe_dim) * int(n_shared)
1568+
return None
1569+
1570+
14641571
# ---------------------------------------------------------------------------
14651572
# Category subclasses — type markers for model categories
14661573
# ---------------------------------------------------------------------------
@@ -1834,6 +1941,10 @@ class Sam2Config(ArchitectureConfig):
18341941
@classmethod
18351942
def from_transformers(cls, config, parent_config=None) -> Sam2Config:
18361943
base = ArchitectureConfig.from_transformers(config, parent_config)
1944+
# SAM2 uses gelu in its backbone MLP but doesn't expose a single
1945+
# hidden_act field — default to gelu.
1946+
if base.hidden_act is None:
1947+
base = dataclasses.replace(base, hidden_act="gelu")
18371948
return cls(
18381949
**_shallow_fields(base),
18391950
sam2_embed_dims=getattr(config, "sam2_embed_dims", None),

‎src/mobius/_configs_test.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,22 @@ class Cfg:
335335

336336
assert _extract_rope_config(Cfg()) is None
337337

338+
def test_nondefault_rope_theta_without_rope_scaling_activates_rope(self):
339+
"""Non-default rope_theta alone (e.g. 50000) is treated as a RoPE signal.
340+
341+
Models like Arctic and Jamba set a custom rope_theta without
342+
exposing rope_scaling in their config JSON. The non-default value
343+
distinguishes them from NoPE models that inherit 10000.0 as dead data.
344+
"""
345+
346+
class Cfg:
347+
rope_theta = 50_000.0 # no rope_scaling, no rope_parameters
348+
349+
result = _extract_rope_config(Cfg())
350+
assert result is not None
351+
assert result.rope_type == "default"
352+
assert result.rope_theta == pytest.approx(50_000.0)
353+
338354
def test_rope_parameters_activates_rope(self):
339355
"""``rope_parameters`` on the HF config is the modern RoPE signal."""
340356

@@ -974,3 +990,63 @@ def test_boa_token_id_none_when_absent(self):
974990

975991
config = Gemma4Config.from_transformers(text_config)
976992
assert config.boa_token_id is None
993+
994+
995+
class TestActivationFallbacks:
996+
"""Tests for hidden_act extraction fallbacks (ff_activation, gelu_activation)."""
997+
998+
def test_ff_activation_fallback(self):
999+
"""ff_activation is used when hidden_act is absent (XLNet pattern)."""
1000+
1001+
class FakeConfig:
1002+
model_type = "xlnet"
1003+
num_attention_heads = 8
1004+
num_key_value_heads = 8
1005+
num_hidden_layers = 2
1006+
vocab_size = 1000
1007+
hidden_size = 256
1008+
intermediate_size = 512
1009+
max_position_embeddings = 1024
1010+
head_dim = 32
1011+
ff_activation = "gelu"
1012+
1013+
config = ArchitectureConfig.from_transformers(FakeConfig())
1014+
assert config.hidden_act == "gelu"
1015+
1016+
def test_gelu_activation_true_fallback(self):
1017+
"""gelu_activation=True maps to 'gelu' (XLM pattern)."""
1018+
1019+
class FakeConfig:
1020+
model_type = "xlm"
1021+
num_attention_heads = 8
1022+
num_key_value_heads = 8
1023+
num_hidden_layers = 2
1024+
vocab_size = 1000
1025+
hidden_size = 256
1026+
intermediate_size = 512
1027+
max_position_embeddings = 1024
1028+
head_dim = 32
1029+
gelu_activation = True
1030+
1031+
config = ArchitectureConfig.from_transformers(FakeConfig())
1032+
assert config.hidden_act == "gelu"
1033+
1034+
def test_gelu_activation_false_does_not_set_gelu(self):
1035+
"""gelu_activation=False should not set hidden_act to gelu."""
1036+
1037+
class FakeConfig:
1038+
model_type = "some_model"
1039+
num_attention_heads = 8
1040+
num_key_value_heads = 8
1041+
num_hidden_layers = 2
1042+
vocab_size = 1000
1043+
hidden_size = 256
1044+
intermediate_size = 512
1045+
max_position_embeddings = 1024
1046+
head_dim = 32
1047+
gelu_activation = False
1048+
1049+
config = ArchitectureConfig.from_transformers(FakeConfig())
1050+
# With gelu_activation=False and no other activation attr,
1051+
# hidden_act should be None (not "gelu")
1052+
assert config.hidden_act is None

‎src/mobius/components/_activations.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,12 @@ def linear(op: builder.OpBuilder, x):
8383
"silu": silu,
8484
"swish": silu,
8585
"tanh": tanh,
86+
# xielu is a parametric learnable activation (used by Apertus).
87+
# Mapped to silu here so CausalLMModel.__init__ can construct the
88+
# base MLP without crashing. ApertusCausalLMModel immediately
89+
# replaces the MLP with ApertusFCMLP that uses the real
90+
# XIELUActivation nn.Module (with alpha_p/alpha_n parameters).
91+
"xielu": silu,
8692
}
8793
)
8894

‎src/mobius/components/_rotary_embedding.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515

1616

1717
def _get_default_inv_freq(config: ArchitectureConfig) -> np.ndarray:
18-
dim = int(config.head_dim * config.partial_rotary_factor)
18+
# For MLA models (MiniCPM3, DeepSeek-V2), rope applies only to the
19+
# qk_rope portion — use qk_rope_head_dim instead of full head_dim.
20+
rope_head_dim = config.qk_rope_head_dim or config.head_dim
21+
dim = int(rope_head_dim * config.partial_rotary_factor)
1922
return 1.0 / (config.rope_theta ** (np.arange(0, dim, 2, dtype=np.float32) / dim))
2023

2124

0 commit comments

Comments
 (0)