Skip to content

Commit c6acc01

Browse files
Copilotxiaoyu-work
andauthored
Fix post-merge config and quantization resolution for transformers builder
Co-authored-by: xiaoyu-work <[email protected]>
1 parent e35b7cd commit c6acc01

4 files changed

Lines changed: 245 additions & 14 deletions

File tree

‎src/mobius/_configs/_base.py‎

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,7 @@ def _extract_component_quantization(
467467
return None
468468
if decoder_quantization is not None:
469469
nested["decoder"] = dataclasses.replace(decoder_quantization)
470+
nested["embedding"] = dataclasses.replace(decoder_quantization)
470471
return nested
471472

472473

@@ -526,6 +527,27 @@ def quantization_for(self, component: str) -> QuantizationConfig | None:
526527
None,
527528
)
528529

530+
def quantization_for_source_paths(
531+
self,
532+
component: str,
533+
source_paths: tuple[str, ...],
534+
*,
535+
ignored_source_names: tuple[str, ...] = ("lm_head", "embed_tokens"),
536+
) -> QuantizationConfig | None:
537+
"""Resolve module-level rules using one component's Hugging Face paths."""
538+
quantization = self.quantization_for(component)
539+
if quantization is None or not quantization.has_module_plan:
540+
return quantization
541+
effective_paths = tuple(
542+
path
543+
for path in source_paths
544+
if path.rsplit(".", 1)[-1] not in ignored_source_names
545+
)
546+
return quantization.for_source_paths(
547+
effective_paths or source_paths,
548+
component=component,
549+
)
550+
529551

530552
@dataclasses.dataclass
531553
class ArchitectureConfig(BaseModelConfig):
@@ -1682,6 +1704,31 @@ class CausalLMConfig(ArchitectureConfig):
16821704
"""
16831705

16841706

1707+
@dataclasses.dataclass
1708+
class GrokGGUFConfig(CausalLMConfig):
1709+
"""GGUF-only Grok graph settings loaded by the pinned llama.cpp implementation."""
1710+
1711+
embedding_scale: float = 78.38367176906169
1712+
attention_output_scale: float = 0.08838834764831845
1713+
logit_output_scale: float = 0.5773502691896257
1714+
attn_logit_softcapping: float = 30.0
1715+
router_logit_softcapping: float = 30.0
1716+
final_logit_softcapping: float = 0.0
1717+
attention_temperature_length: int = 0
1718+
has_dense_ffn: bool = False
1719+
has_gated_dense_ffn: bool = False
1720+
has_gated_experts: bool = True
1721+
1722+
1723+
@dataclasses.dataclass
1724+
class GroveMoEGGUFConfig(CausalLMConfig):
1725+
"""GGUF-only GroveMoE chunk-expert routing settings."""
1726+
1727+
chunk_expert_intermediate_size: int = DEFAULT_INT
1728+
experts_per_group: int = DEFAULT_INT
1729+
expert_group_scale: float = 0.05
1730+
1731+
16851732
@dataclasses.dataclass
16861733
class Qwen4ExpConfig(CausalLMConfig):
16871734
"""Exact configuration for experimental Qwen4/Qwen3.8 Flash-Next."""
@@ -2758,10 +2805,12 @@ class Eagle3Config(CausalLMConfig):
27582805
eagle_aux_hidden_state_layer_ids: list[int] | None = None
27592806
target_layer_ids: list[int] | None = None
27602807
use_target_lm_head: bool = False
2808+
use_draft_token_embedding: bool = False
27612809

27622810
@classmethod
27632811
def from_transformers(cls, config, parent_config=None) -> Eagle3Config:
27642812
layer_cfg = getattr(config, "transformer_layer_config", None)
2813+
is_speculators_format = layer_cfg is not None
27652814
if layer_cfg is not None:
27662815
# speculators format: arch config nested under transformer_layer_config.
27672816
if isinstance(layer_cfg, dict):
@@ -2782,6 +2831,7 @@ def from_transformers(cls, config, parent_config=None) -> Eagle3Config:
27822831
eagle_aux_hidden_state_layer_ids=getattr(
27832832
config, "eagle_aux_hidden_state_layer_ids", None
27842833
),
2834+
use_draft_token_embedding=is_speculators_format,
27852835
)
27862836

27872837

@@ -4434,6 +4484,16 @@ class SpeechToTextConfig(ArchitectureConfig):
44344484
decoder_start_token_id: int | None = None
44354485
layer_norm_eps: float = 1e-5
44364486

4487+
@property
4488+
def encoder_output_size(self) -> int:
4489+
"""Channel width of ``encoder_hidden_states``.
4490+
4491+
Defaults to the decoder width because most speech encoder-decoders share
4492+
one model dimension. Architectures whose encoder is narrower or wider
4493+
(e.g. Moonshine Streaming with a projection adapter) override this.
4494+
"""
4495+
return self.hidden_size
4496+
44374497

44384498
@dataclasses.dataclass
44394499
class WhisperConfig(SpeechToTextConfig):
@@ -4580,6 +4640,173 @@ def from_transformers(cls, config, parent_config=None) -> MoonshineConfig:
45804640
return cls(**options)
45814641

45824642

4643+
def _sub_config_get(config, name: str, default):
4644+
"""Read ``name`` from a sub-config that may be an object or a plain dict."""
4645+
if isinstance(config, dict):
4646+
value = config.get(name, default)
4647+
else:
4648+
value = getattr(config, name, default)
4649+
return default if value is None else value
4650+
4651+
4652+
@dataclasses.dataclass
4653+
class MoonshineStreamingConfig(SpeechToTextConfig):
4654+
"""Configuration for Moonshine Streaming raw-waveform encoder-decoder ASR.
4655+
4656+
Moonshine Streaming replaces the offline Moonshine convolutional stem with a
4657+
fixed-length framing front end (``frame_ms`` frames of raw samples), per-frame
4658+
CMVN, learned asinh compression, and two *causal* strided convolutions. Its
4659+
encoder carries no rotary embedding; position information comes from the
4660+
causal stem plus per-layer asymmetric ``(left, right)`` sliding windows, which
4661+
bound the streaming lookahead. The decoder adds an absolute learned position
4662+
table (``pos_emb``) to the encoder output before cross-attention.
4663+
"""
4664+
4665+
encoder_input_name: str = "input_values"
4666+
encoder_input_channels: int | None = None
4667+
encoder_uses_attention_mask: bool = True
4668+
decoder_uses_encoder_attention_mask: bool = True
4669+
encoder_hidden_size: int = DEFAULT_INT
4670+
encoder_intermediate_size: int = DEFAULT_INT
4671+
encoder_num_hidden_layers: int = DEFAULT_INT
4672+
encoder_num_attention_heads: int = DEFAULT_INT
4673+
encoder_num_key_value_heads: int = DEFAULT_INT
4674+
encoder_head_dim: int = DEFAULT_INT
4675+
encoder_hidden_act: str = "gelu"
4676+
decoder_hidden_act: str = "silu"
4677+
#: Q/K/V and output projection bias of the encoder attention. Upstream
4678+
#: gates all four encoder projections on the encoder sub-config's
4679+
#: ``attention_bias`` (the decoder's output projection stays bias-free).
4680+
encoder_attention_bias: bool = False
4681+
#: Per-layer ``(left_window, right_window)`` attention spans of the encoder.
4682+
#: ``left`` counts the query position itself; ``right`` is the strict
4683+
#: lookahead. ``right == 0`` means the layer is fully causal.
4684+
encoder_sliding_windows: tuple[tuple[int, int], ...] = ((16, 4),)
4685+
encoder_sample_rate: int = 16_000
4686+
encoder_frame_ms: float = 5.0
4687+
#: Epsilon of the per-frame cepstral mean/variance normalisation.
4688+
encoder_cmvn_eps: float = 1e-6
4689+
4690+
def __post_init__(self):
4691+
# A tuple keeps the config hashable and prevents accidental mutation of
4692+
# the per-layer window schedule shared by every encoder layer.
4693+
self.encoder_sliding_windows = tuple(
4694+
(int(left), int(right)) for left, right in self.encoder_sliding_windows
4695+
)
4696+
if self.encoder_hidden_size == DEFAULT_INT:
4697+
self.encoder_hidden_size = self.hidden_size
4698+
if self.encoder_intermediate_size == DEFAULT_INT:
4699+
self.encoder_intermediate_size = self.intermediate_size
4700+
if self.encoder_num_attention_heads == DEFAULT_INT:
4701+
self.encoder_num_attention_heads = self.num_attention_heads
4702+
if self.encoder_num_key_value_heads == DEFAULT_INT:
4703+
self.encoder_num_key_value_heads = self.encoder_num_attention_heads
4704+
if self.encoder_num_hidden_layers == DEFAULT_INT:
4705+
self.encoder_num_hidden_layers = len(self.encoder_sliding_windows)
4706+
if self.encoder_head_dim == DEFAULT_INT:
4707+
self.encoder_head_dim = (
4708+
self.encoder_hidden_size // self.encoder_num_attention_heads
4709+
)
4710+
if len(self.encoder_sliding_windows) != self.encoder_num_hidden_layers:
4711+
raise ValueError(
4712+
"MoonshineStreamingConfig: encoder_sliding_windows has "
4713+
f"{len(self.encoder_sliding_windows)} entries but the encoder has "
4714+
f"{self.encoder_num_hidden_layers} layers."
4715+
)
4716+
4717+
@property
4718+
def encoder_output_size(self) -> int:
4719+
"""Encoder width; the decoder projects it when it differs from its own."""
4720+
return self.encoder_hidden_size
4721+
4722+
@property
4723+
def frame_length(self) -> int:
4724+
"""Raw samples per encoder frame (``sample_rate * frame_ms / 1000``).
4725+
4726+
Upstream rounds to the nearest integer, so the audio length fed to the
4727+
encoder must be a multiple of this value; the processor's
4728+
``pad_to_multiple_of`` enforces that.
4729+
"""
4730+
return round(self.encoder_sample_rate * self.encoder_frame_ms / 1000.0)
4731+
4732+
@classmethod
4733+
def from_transformers(cls, config, parent_config=None) -> MoonshineStreamingConfig:
4734+
if config.model_type != "moonshine_streaming":
4735+
raise ValueError(
4736+
"MoonshineStreamingConfig expects model_type='moonshine_streaming', "
4737+
f"got '{config.model_type}'"
4738+
)
4739+
4740+
hidden_size = config.hidden_size
4741+
decoder_heads = config.num_attention_heads
4742+
# ``encoder_config`` is a nested MoonshineStreamingEncoderConfig on a
4743+
# trusted config object and a plain dict when the JSON is read directly.
4744+
encoder_config = getattr(config, "encoder_config", None) or {}
4745+
encoder_hidden_size = _sub_config_get(encoder_config, "hidden_size", hidden_size)
4746+
encoder_heads = _sub_config_get(encoder_config, "num_attention_heads", decoder_heads)
4747+
rope_parameters = getattr(config, "rope_parameters", None) or getattr(
4748+
config, "rope_scaling", None
4749+
)
4750+
rope_parameters = rope_parameters or {}
4751+
windows = _sub_config_get(
4752+
encoder_config,
4753+
"sliding_windows",
4754+
((16, 4), (16, 4), (16, 0), (16, 0), (16, 4), (16, 4)),
4755+
)
4756+
4757+
options = dict(
4758+
vocab_size=config.vocab_size,
4759+
hidden_size=hidden_size,
4760+
intermediate_size=config.intermediate_size,
4761+
num_hidden_layers=config.num_hidden_layers,
4762+
num_attention_heads=decoder_heads,
4763+
num_key_value_heads=getattr(config, "num_key_value_heads", decoder_heads),
4764+
head_dim=getattr(config, "head_dim", None) or hidden_size // decoder_heads,
4765+
hidden_act=getattr(config, "hidden_act", "silu"),
4766+
pad_token_id=getattr(config, "pad_token_id", 0),
4767+
tie_word_embeddings=getattr(config, "tie_word_embeddings", False),
4768+
attn_qkv_bias=getattr(config, "attention_bias", False),
4769+
attn_o_bias=False,
4770+
max_position_embeddings=getattr(config, "max_position_embeddings", 4096),
4771+
rope_type=rope_parameters.get("rope_type", "default"),
4772+
rope_theta=rope_parameters.get("rope_theta", 10_000.0),
4773+
rope_scaling=rope_parameters or None,
4774+
partial_rotary_factor=rope_parameters.get("partial_rotary_factor", 1.0),
4775+
rope_interleave=True,
4776+
mlp_bias=True,
4777+
encoder_hidden_size=encoder_hidden_size,
4778+
encoder_intermediate_size=_sub_config_get(
4779+
encoder_config, "intermediate_size", config.intermediate_size
4780+
),
4781+
encoder_num_hidden_layers=_sub_config_get(
4782+
encoder_config, "num_hidden_layers", config.num_hidden_layers
4783+
),
4784+
encoder_num_attention_heads=encoder_heads,
4785+
encoder_num_key_value_heads=_sub_config_get(
4786+
encoder_config, "num_key_value_heads", encoder_heads
4787+
),
4788+
encoder_head_dim=_sub_config_get(encoder_config, "head_dim", None)
4789+
or encoder_hidden_size // encoder_heads,
4790+
encoder_hidden_act=_sub_config_get(encoder_config, "hidden_act", "gelu"),
4791+
encoder_attention_bias=bool(
4792+
_sub_config_get(encoder_config, "attention_bias", False)
4793+
),
4794+
decoder_hidden_act=getattr(config, "hidden_act", "silu"),
4795+
encoder_sliding_windows=tuple(tuple(window) for window in windows),
4796+
encoder_sample_rate=_sub_config_get(encoder_config, "sample_rate", 16_000),
4797+
encoder_frame_ms=_sub_config_get(encoder_config, "frame_ms", 5.0),
4798+
decoder_start_token_id=getattr(config, "decoder_start_token_id", 1),
4799+
layer_norm_eps=getattr(config, "layer_norm_eps", 1e-5),
4800+
model_type="moonshine_streaming",
4801+
bos_token_id=getattr(config, "bos_token_id", 1),
4802+
eos_token_id=getattr(config, "eos_token_id", 2),
4803+
)
4804+
resolved = _resolve_dtype(config)
4805+
if resolved is not None:
4806+
options["dtype"] = resolved
4807+
return cls(**options)
4808+
4809+
45834810
def _conv_widths(config, defaults, hidden_size: int) -> tuple[int, ...]:
45844811
"""Per-layer channel widths of a wav2vec2-family convolutional feature encoder.
45854812

‎src/mobius/_configs/_quantization.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,11 @@ def from_transformers(cls, hf_config) -> QuantizationConfig | None:
223223
expert_dtype=getattr(hf_config, "expert_dtype", None),
224224
)
225225

226+
@property
227+
def has_module_plan(self) -> bool:
228+
"""Whether module-selection rules or overrides are present."""
229+
return bool(self.modules_to_not_convert) or bool(self.overrides)
230+
226231
@staticmethod
227232
def _matches_exclusion(pattern: str, module_name: str) -> bool:
228233
if pattern.startswith("re:"):
@@ -233,7 +238,7 @@ def _matches_exclusion(pattern: str, module_name: str) -> bool:
233238
def _matches_override(pattern: str, module_name: str) -> bool:
234239
if pattern.startswith("re:"):
235240
return _compile_pattern(pattern[3:]).fullmatch(module_name) is not None
236-
return pattern == module_name
241+
return pattern == module_name or module_name.startswith(f"{pattern}.") or pattern in module_name
237242

238243
def for_module(
239244
self,
@@ -253,3 +258,15 @@ def for_module(
253258
):
254259
return override.apply(self)
255260
return self
261+
262+
def for_source_paths(
263+
self,
264+
source_paths: tuple[str, ...],
265+
*,
266+
component: str = "decoder",
267+
) -> QuantizationConfig | None:
268+
"""Resolve module-level rules for a set of source paths."""
269+
resolved = self.for_module(source_paths)
270+
if resolved is None:
271+
return None
272+
return dataclasses.replace(resolved, overrides={}, modules_to_not_convert=())

‎src/mobius/integrations/transformers/_builder.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -604,7 +604,6 @@ def build_transformers_model(
604604
manifest=component_manifest,
605605
task=resolved_task,
606606
)
607-
)
608607
package.apply_weights(
609608
state_dict,
610609
prefix_map=getattr(model_module, "weight_prefix_map", None),

‎src/mobius/integrations/transformers/_builder_test.py‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,6 @@ def test_strip_to_text_only_drops_component_quantization() -> None:
305305
quant_method="olive",
306306
)
307307
config = make_config(
308-
<<<<<<< HEAD
309308
quantization=decoder,
310309
component_quantization={
311310
"decoder": decoder,
@@ -315,12 +314,6 @@ def test_strip_to_text_only_drops_component_quantization() -> None:
315314
quant_method="olive",
316315
),
317316
},
318-
=======
319-
component_quantization={
320-
"decoder": decoder,
321-
"vision_encoder": decoder,
322-
}
323-
>>>>>>> origin/refactor/typed-weight-pipeline
324317
)
325318

326319
stripped = transformers_builder._strip_to_text_only(config, "qwen2")
@@ -329,8 +322,6 @@ def test_strip_to_text_only_drops_component_quantization() -> None:
329322
assert stripped.quantization is decoder
330323

331324

332-
<<<<<<< HEAD
333-
=======
334325
def test_strip_to_text_only_resolves_decoder_module_plan() -> None:
335326
decoder = QuantizationConfig(
336327
bits=4,
@@ -356,9 +347,6 @@ def test_strip_to_text_only_resolves_decoder_module_plan() -> None:
356347
assert stripped.quantization is not None
357348
assert (stripped.quantization.bits, stripped.quantization.group_size) == (8, 32)
358349
assert stripped.quantization.overrides == {}
359-
360-
361-
>>>>>>> origin/refactor/typed-weight-pipeline
362350
def test_transformers_build_uses_canonical_weight_loader(monkeypatch) -> None:
363351
hf_config = type("HFConfig", (), {"model_type": "qwen2"})()
364352
config = make_config(model_type="qwen2")

0 commit comments

Comments
 (0)