Skip to content

Commit 710b032

Browse files
xiaoyu-workCopilotjustinchubyCopilot
authored
Fix multi-component export portability (#623)
This pull request enhances the cross-platform detection and reporting of available RAM in the `mobius.preflight` module. It introduces platform-specific implementations for Windows, macOS, and Linux, improves test coverage for these changes, and updates related tests to use the new probing mechanism. Additionally, it includes a small fix in a build graph test to ensure node ordering is validated. **Improvements to RAM detection and reporting:** * Added platform-specific functions for detecting available RAM: `_windows_available_ram_bytes` for Windows, `_darwin_available_ram_bytes` for macOS, `_proc_available_ram_bytes` for Linux, and a fallback using `os.sysconf` when necessary. The new `_probe_available_ram` function selects the best available method and returns both the value and its source. (`[[1]](diffhunk://#diff-9bc6af1f2ebeb847e186fe5570e6ac0d76b0343bf9eb51e0fbd9f2e2c5cfa15aL462-R492)`, `[[2]](diffhunk://#diff-9bc6af1f2ebeb847e186fe5570e6ac0d76b0343bf9eb51e0fbd9f2e2c5cfa15aR502-R561)`) * Updated `check_ram` to use the new `_probe_available_ram` function, improving reporting by including the source of the RAM measurement. (`[src/mobius/preflight.pyL486-R582](diffhunk://#diff-9bc6af1f2ebeb847e186fe5570e6ac0d76b0343bf9eb51e0fbd9f2e2c5cfa15aL486-R582)`) **Testing and test utilities:** * Added comprehensive tests for the new RAM detection logic, including platform-specific probes, fallback mechanisms, and parsing of macOS `vm_stat` output. Existing tests now monkeypatch `_probe_available_ram` instead of `_available_ram_bytes`. (`[[1]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59R199-R236)`, `[[2]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59L219-R257)`, `[[3]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59L230-R276)`, `[[4]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59L248-R286)`, `[[5]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59L272-R310)`, `[[6]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59L291-R329)`, `[[7]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59L306-R344)`, `[[8]](diffhunk://#diff-f86b6f1c3e1afc379705d505194294a8ecc9896b48259c164b776eb3f1b34f59L328-R366)`) **General codebase improvements:** * Added missing imports (`ctypes`, `wintypes`, `re`, `subprocess`, `sys`) to support the new platform-specific RAM detection logic. (`[src/mobius/preflight.pyR41-R52](diffhunk://#diff-9bc6af1f2ebeb847e186fe5570e6ac0d76b0343bf9eb51e0fbd9f2e2c5cfa15aR41-R52)`) * In `_should_inline`, ensured the model graph is sorted after rewrites to maintain correct producer-consumer ordering. (`[src/mobius/_optimizations.pyR707-R709](diffhunk://#diff-0e0781be69f6ae96d51801d3a2ba76bdb7220c897d668aae0282064c2962e8a2R707-R709)`) **Build/test validation:** * In `tests/build_graph_test.py`, switched to using `build_from_module` for clarity and added an explicit check that ensures node producers in the vision encoder graph are ordered before their consumers. (`[[1]](diffhunk://#diff-e3747952023a0b5f01abf736f1c02d1cc314598012d2eb94b7e2dfa8405c9271L1235-R1235)`, `[[2]](diffhunk://#diff-e3747952023a0b5f01abf736f1c02d1cc314598012d2eb94b7e2dfa8405c9271R1247-R1254)`) --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent c3fa21e commit 710b032

19 files changed

Lines changed: 1081 additions & 151 deletions

‎src/mobius/_configs/_base.py‎

Lines changed: 91 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -771,17 +771,64 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
771771
if rope_config is not None:
772772
rope_config = dataclasses.replace(rope_config, rope_interleave=rope_interleave)
773773

774+
per_layer_config = getattr(config, "per_layer_config", None)
775+
layer_configs = []
776+
layer_types = getattr(config, "layer_types", None)
777+
if per_layer_config:
778+
layer_configs = list(
779+
per_layer_config.values()
780+
if isinstance(per_layer_config, dict)
781+
else per_layer_config
782+
)
783+
784+
def _per_layer_value(attribute: str) -> int | None:
785+
values = set()
786+
values_by_layer_type: dict[str, set[int]] = {}
787+
for index, layer_config in enumerate(layer_configs):
788+
value = (
789+
layer_config.get(attribute)
790+
if isinstance(layer_config, dict)
791+
else getattr(layer_config, attribute, None)
792+
)
793+
if value is None:
794+
continue
795+
values.add(value)
796+
if layer_types and len(layer_types) == len(layer_configs):
797+
values_by_layer_type.setdefault(layer_types[index], set()).add(value)
798+
if not values:
799+
return None
800+
if len(values) == 1:
801+
return next(iter(values))
802+
supported_layer_types = {"sliding_attention", "full_attention"}
803+
if (
804+
model_type not in {"gemma4_text", "gemma4_unified_text"}
805+
or set(values_by_layer_type) != supported_layer_types
806+
or any(len(type_values) != 1 for type_values in values_by_layer_type.values())
807+
):
808+
raise ValueError(
809+
f"Mobius does not support these heterogeneous per-layer {attribute} "
810+
f"values: {sorted(values)}."
811+
)
812+
return next(iter(values_by_layer_type["sliding_attention"]))
813+
814+
head_dim = _per_layer_value("head_dim")
815+
if head_dim is None:
816+
head_dim = getattr(config, "head_dim", None)
817+
num_key_value_heads = _per_layer_value("num_key_value_heads")
818+
if num_key_value_heads is None:
819+
num_key_value_heads = getattr(config, "num_key_value_heads", None)
820+
774821
options = dict(
775822
head_dim=(
776-
config.head_dim
777-
if (hasattr(config, "head_dim") and config.head_dim is not None)
823+
head_dim
824+
if head_dim is not None
778825
else getattr(config, "d_kv", None)
779826
or getattr(config, "kv_channels", None)
780827
or _as_int(hidden_size) // _as_int(num_attention_heads)
781828
),
782829
num_attention_heads=_as_int(num_attention_heads),
783830
num_key_value_heads=_as_int(
784-
getattr(config, "num_key_value_heads", None)
831+
num_key_value_heads
785832
or getattr(config, "n_kv_heads", None)
786833
or (
787834
getattr(config, "multi_query_group_num", None)
@@ -2540,15 +2587,50 @@ def from_transformers(cls, config, parent_config=None) -> Gemma4Config:
25402587
# Override with the correct sliding-attention theta (e.g. 10_000 for E2B/E4B).
25412588
base = dataclasses.replace(base, rope_theta=float(sliding_rope["rope_theta"]))
25422589

2543-
# num_global_key_value_heads: only set when attention_k_eq_v is True
2544-
# (full-attention layers use fewer KV heads than sliding layers).
2545-
num_global_kv = None
2546-
if getattr(config, "attention_k_eq_v", False):
2547-
num_global_kv = getattr(config, "num_global_key_value_heads", None)
2590+
num_global_kv = getattr(config, "num_global_key_value_heads", None)
2591+
global_head_dim = getattr(config, "global_head_dim", None)
2592+
if global_head_dim is None or num_global_kv is None:
2593+
per_layer_config = getattr(config, "per_layer_config", None)
2594+
layer_types = getattr(config, "layer_types", None)
2595+
if per_layer_config and layer_types:
2596+
layer_configs = list(
2597+
per_layer_config.values()
2598+
if isinstance(per_layer_config, dict)
2599+
else per_layer_config
2600+
)
2601+
if len(layer_types) == len(layer_configs):
2602+
full_head_dims = {
2603+
(
2604+
layer_config.get("head_dim")
2605+
if isinstance(layer_config, dict)
2606+
else getattr(layer_config, "head_dim", None)
2607+
)
2608+
for layer_type, layer_config in zip(
2609+
layer_types, layer_configs, strict=True
2610+
)
2611+
if layer_type == "full_attention"
2612+
}
2613+
full_head_dims.discard(None)
2614+
if global_head_dim is None and len(full_head_dims) == 1:
2615+
global_head_dim = next(iter(full_head_dims))
2616+
full_kv_heads = {
2617+
(
2618+
layer_config.get("num_key_value_heads")
2619+
if isinstance(layer_config, dict)
2620+
else getattr(layer_config, "num_key_value_heads", None)
2621+
)
2622+
for layer_type, layer_config in zip(
2623+
layer_types, layer_configs, strict=True
2624+
)
2625+
if layer_type == "full_attention"
2626+
}
2627+
full_kv_heads.discard(None)
2628+
if num_global_kv is None and len(full_kv_heads) == 1:
2629+
num_global_kv = next(iter(full_kv_heads))
25482630

25492631
return cls(
25502632
**_shallow_fields(base),
2551-
global_head_dim=getattr(config, "global_head_dim", None),
2633+
global_head_dim=global_head_dim,
25522634
global_rope_theta=float(full_rope.get("rope_theta", 1_000_000.0)),
25532635
global_partial_rotary_factor=float(full_rope.get("partial_rotary_factor", 0.25)),
25542636
num_global_key_value_heads=num_global_kv,

‎src/mobius/_configs/_quantization.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ class QuantizationConfig:
3333
# When True, the LM head projection is block-wise quantized (MatMulNBits).
3434
# Used by Olive RTN exports and quantized GGUF imports.
3535
quantize_lm_head: bool = False
36+
# When True, multimodal vision projections are block-wise quantized.
37+
# Olive RTN records this when ``quantize_vision`` is enabled.
38+
quantize_vision: bool = False
3639
# When True, the input embedding and LM head share one weight table. Olive
3740
# RTN records this in its own config (``tie_word_embeddings``) and may clear
3841
# the model's top-level flag, so it is tracked here independently.
@@ -120,5 +123,6 @@ def from_transformers(cls, hf_config) -> QuantizationConfig | None:
120123
sym=qc.get("sym", qc.get("symmetric", True)),
121124
quantize_embeddings=bool(qc.get("embeds", False)),
122125
quantize_lm_head=bool(qc.get("lm_head", False)),
126+
quantize_vision=bool(qc.get("quantize_vision", False)),
123127
tie_word_embeddings=bool(qc.get("tie_word_embeddings", False)),
124128
)

‎src/mobius/_configs_test.py‎

Lines changed: 93 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,8 +1036,8 @@ def test_from_transformers_symmetric_key_fallback(self):
10361036
assert qc is not None
10371037
assert qc.sym is False
10381038

1039-
def test_from_transformers_olive_embeds_and_lm_head(self):
1040-
"""Olive RTN exports flag quantized embeddings and LM head."""
1039+
def test_from_transformers_olive_component_flags(self):
1040+
"""Olive RTN exports flags for quantized tables and vision projections."""
10411041
hf = type(
10421042
"HFConfig",
10431043
(),
@@ -1048,18 +1048,21 @@ def test_from_transformers_olive_embeds_and_lm_head(self):
10481048
"group_size": 32,
10491049
"embeds": True,
10501050
"lm_head": True,
1051+
"quantize_vision": True,
10511052
}
10521053
},
10531054
)()
10541055
qc = QuantizationConfig.from_transformers(hf)
10551056
assert qc is not None
10561057
assert qc.quantize_embeddings is True
10571058
assert qc.quantize_lm_head is True
1059+
assert qc.quantize_vision is True
10581060

1059-
def test_quantize_embed_lm_head_default_false(self):
1061+
def test_quantize_component_flags_default_false(self):
10601062
qc = QuantizationConfig()
10611063
assert qc.quantize_embeddings is False
10621064
assert qc.quantize_lm_head is False
1065+
assert qc.quantize_vision is False
10631066

10641067
def test_architecture_config_has_quantization_field(self):
10651068
config = ArchitectureConfig()
@@ -1182,6 +1185,93 @@ def test_multiple_errors_reported(self):
11821185
class TestGemma4Config:
11831186
"""Tests for Gemma4Config.from_transformers."""
11841187

1188+
@staticmethod
1189+
def _heterogeneous_config(*head_dims, layer_types=None, kv_heads=None):
1190+
class FakeConfig:
1191+
model_type = "gemma4_text"
1192+
num_attention_heads = 8
1193+
num_hidden_layers = len(head_dims)
1194+
vocab_size = 262144
1195+
hidden_size = 1536
1196+
intermediate_size = 6144
1197+
hidden_act = "silu"
1198+
max_position_embeddings = 131072
1199+
rms_norm_eps = 1e-6
1200+
rope_theta = 10_000.0
1201+
1202+
def __init__(self):
1203+
layer_kv_heads = kv_heads or [1] * len(head_dims)
1204+
self.per_layer_config = [
1205+
type(
1206+
"LayerConfig",
1207+
(),
1208+
{
1209+
"head_dim": head_dim,
1210+
"num_key_value_heads": num_kv_heads,
1211+
},
1212+
)()
1213+
for head_dim, num_kv_heads in zip(head_dims, layer_kv_heads, strict=True)
1214+
]
1215+
self.layer_types = layer_types
1216+
1217+
@property
1218+
def head_dim(self):
1219+
raise RuntimeError("global per-layer attribute access is ambiguous")
1220+
1221+
@property
1222+
def num_key_value_heads(self):
1223+
raise RuntimeError("global per-layer attribute access is ambiguous")
1224+
1225+
return FakeConfig()
1226+
1227+
def test_uniform_per_layer_head_dim_avoids_ambiguous_global_access(self):
1228+
from mobius._configs import Gemma4Config
1229+
1230+
config = Gemma4Config.from_transformers(self._heterogeneous_config(256, 256))
1231+
1232+
assert config.head_dim == 256
1233+
1234+
def test_heterogeneous_per_layer_head_dim_fails_loudly(self):
1235+
from mobius._configs import Gemma4Config
1236+
1237+
with pytest.raises(ValueError, match="heterogeneous per-layer head_dim"):
1238+
Gemma4Config.from_transformers(self._heterogeneous_config(128, 256))
1239+
1240+
def test_dual_head_dim_maps_sliding_and_full_attention(self):
1241+
from mobius._configs import Gemma4Config
1242+
1243+
config = Gemma4Config.from_transformers(
1244+
self._heterogeneous_config(
1245+
256,
1246+
512,
1247+
layer_types=["sliding_attention", "full_attention"],
1248+
kv_heads=[8, 2],
1249+
)
1250+
)
1251+
1252+
assert config.head_dim == 256
1253+
assert config.global_head_dim == 512
1254+
assert config.num_key_value_heads == 8
1255+
assert config.num_global_key_value_heads == 2
1256+
1257+
def test_unsupported_third_heterogeneous_layer_type_fails(self):
1258+
from mobius._configs import Gemma4Config
1259+
1260+
with pytest.raises(ValueError, match="heterogeneous per-layer head_dim"):
1261+
Gemma4Config.from_transformers(
1262+
self._heterogeneous_config(
1263+
256,
1264+
512,
1265+
128,
1266+
layer_types=[
1267+
"sliding_attention",
1268+
"full_attention",
1269+
"window_attention",
1270+
],
1271+
kv_heads=[8, 2, 4],
1272+
)
1273+
)
1274+
11851275
def test_boa_token_id_extracted_from_parent(self):
11861276
"""boa_token_id lives on the parent HF config, not text_config."""
11871277
from mobius._configs import Gemma4Config

‎src/mobius/_optimizations.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,9 @@ def _should_inline(func: ir.Function) -> bool:
704704
"so the decoder fuses to GroupQueryAttention."
705705
)
706706

707+
# Rewrites may insert producers after existing consumers.
708+
model.graph.sort()
709+
707710

708711
def fold_initializers_after_weights(model: ir.Model) -> None:
709712
"""Fold weight ``Transpose`` and ``Concat`` nodes after weights are loaded.

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2343,6 +2343,26 @@ def mixed_native_q5_q8_gguf(tmp_path: Path) -> Path:
23432343
class TestReuseGgufWeights:
23442344
"""Tests for mixed GGUF references plus converted ONNX sidecar weights."""
23452345

2346+
def test_fsync_file_uses_writable_descriptor_on_windows(self, tmp_path: Path, monkeypatch):
2347+
from mobius.integrations.gguf import _reuse
2348+
2349+
path = tmp_path / "artifact.bin"
2350+
path.write_bytes(b"artifact")
2351+
opened_modes = []
2352+
real_open = Path.open
2353+
2354+
def tracking_open(self, *args, **kwargs):
2355+
if self == path:
2356+
opened_modes.append(args[0] if args else kwargs.get("mode", "r"))
2357+
return real_open(self, *args, **kwargs)
2358+
2359+
monkeypatch.setattr(_reuse.os, "name", "nt")
2360+
monkeypatch.setattr(Path, "open", tracking_open)
2361+
2362+
_reuse._fsync_file(path)
2363+
2364+
assert opened_modes == ["r+b"]
2365+
23462366
def test_mixed_save_preserves_ranges_and_runs(self, tmp_path: Path):
23472367
from mobius._model_package import ModelPackage
23482368
from mobius.integrations.gguf import (

‎src/mobius/integrations/gguf/_reuse.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -565,7 +565,8 @@ def _verification_lock(root: Path) -> Iterator[None]:
565565

566566

567567
def _fsync_file(path: Path) -> None:
568-
with path.open("rb") as stream:
568+
mode = "r+b" if os.name == "nt" else "rb"
569+
with path.open(mode) as stream:
569570
os.fsync(stream.fileno())
570571

571572

0 commit comments

Comments
 (0)