Skip to content

Commit 354b9ff

Browse files
justinchubyCopilot
andauthored
Fix sharded GGUF evidence edge cases (#675)
## Summary - resolve local sharded-GGUF symlinks to their verified regular-file targets before artifact identity hashing, while retaining logical shard filenames in the digest - make missing `split.count`, `split.no`, and `split.tensors.count` diagnostics deterministic - add regressions covering the `build_from_gguf` symlink path, artifact hashing, missing targets, and reversed shard ordering This follows up on the still-applicable Copilot findings from #652 after its sharded import functionality was superseded on `main` by #656. ## Validation - `python -m pytest src/mobius/integrations/gguf/_shard_set_test.py -q --tb=short` (51 passed) - `python -m pytest tests/build_graph_test.py tests/cli_test.py src/ -q -k "not phi4mm and not apply_weights_unknown" --tb=short -n auto` (8627 passed, 64 skipped) - `lintrunner f --output oneline --all-files` - independent code review: no findings --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 0cea508 commit 354b9ff

13 files changed

Lines changed: 1135 additions & 217 deletions

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

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5274,22 +5274,13 @@ def _resolve_mmproj_companion_path(
52745274
return _resolve_gguf_path_impl(gguf_path, allow_mmproj_companion=True)
52755275

52765276

5277-
def _hub_cache_identity_paths(paths: Collection[Path]) -> list[Path] | None:
5278-
"""Resolve trusted Hub snapshot links to regular blob paths for hashing."""
5279-
from huggingface_hub.constants import HF_HUB_CACHE
5280-
5281-
cache_root = Path(HF_HUB_CACHE).expanduser().absolute()
5277+
def _regular_file_identity_paths(paths: Collection[Path]) -> list[Path] | None:
5278+
"""Resolve opened shard paths to regular-file targets for identity hashing."""
52825279
resolved_paths: list[Path] = []
52835280
for path in paths:
5284-
absolute = path.expanduser().absolute()
5285-
try:
5286-
absolute.relative_to(cache_root)
5287-
except ValueError:
5288-
return None
5289-
resolved = absolute.resolve(strict=True)
52905281
try:
5291-
resolved.relative_to(cache_root)
5292-
except ValueError:
5282+
resolved = path.expanduser().resolve(strict=True)
5283+
except OSError:
52935284
return None
52945285
if not resolved.is_file() or resolved.is_symlink():
52955286
return None
@@ -5504,7 +5495,7 @@ def build_from_gguf(
55045495
shard_open_kwargs["expected_sizes"] = expected_sizes
55055496
gguf_model = open_gguf_model(gguf_path, **shard_open_kwargs)
55065497
if isinstance(gguf_model, GgufShardSet):
5507-
identity_paths = _hub_cache_identity_paths(gguf_model.shard_paths)
5498+
identity_paths = _regular_file_identity_paths(gguf_model.shard_paths)
55085499
if identity_paths is not None:
55095500
gguf_model._set_identity_paths(identity_paths)
55105501
_validate_gguf_model(
@@ -6049,7 +6040,7 @@ def combine_mtp_report(mtp_report) -> None:
60496040
for name, tensor in state_dict.items()
60506041
if id(tensor) in reuse_candidates_by_id
60516042
}
6052-
attach_reused_initializers(pkg, gguf_path, final_candidates)
6043+
attach_reused_initializers(pkg, gguf_path, final_candidates, gguf_model)
60536044

60546045
# 9b. Sparse-MoE fusion + honesty gate (final graph state).
60556046
# Now that every native block carries its real packed bytes, collapse the
@@ -8175,11 +8166,11 @@ def _load_quantized_state_dict(
81758166
n_repacked += num_experts
81768167
elif should_repack:
81778168
if is_tencent_q1_0_tensor:
8178-
gguf_path, data_section_offset, reader_tensor = gguf_model._tensor_source(
8179-
gguf_name
8169+
read_source_range, data_section_offset, reader_tensor = (
8170+
gguf_model._tensor_source(gguf_name)
81808171
)
81818172
repacked = parse_tencent_q1_0_tensor(
8182-
str(gguf_path),
8173+
read_source_range,
81838174
data_section_offset,
81848175
reader_tensor,
81858176
)

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

Lines changed: 277 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from __future__ import annotations
77

8+
import errno
89
import json
910
import os
1011
import re
@@ -47,6 +48,18 @@ def _gguf_header_prefix(*architectures: str) -> bytes:
4748
)
4849

4950

51+
def _symlink_or_skip(link: Path, target: Path) -> None:
52+
try:
53+
link.symlink_to(target)
54+
except OSError as error:
55+
if os.name == "nt" and (
56+
getattr(error, "winerror", None) in {1, 50, 1314}
57+
or error.errno in {errno.EPERM, errno.EACCES, errno.ENOSYS}
58+
):
59+
pytest.skip(f"Windows runner cannot create test symlinks: {error}")
60+
raise
61+
62+
5063
def _run_gather_block_quantized(
5164
tmp_path: Path,
5265
*,
@@ -2467,15 +2480,21 @@ def tracking_open(self, *args, **kwargs):
24672480
def test_mixed_save_preserves_ranges_and_runs(self, tmp_path: Path):
24682481
from mobius._model_package import ModelPackage
24692482
from mobius.integrations.gguf import (
2470-
_reuse,
24712483
build_from_gguf,
24722484
verify_gguf_reuse_manifest,
24732485
)
24742486

24752487
gguf_path = tmp_path / "model.gguf"
24762488
_write_quantized_gguf(gguf_path, projection_quantization="f32")
24772489
package = build_from_gguf(gguf_path, reuse_gguf_weights=True)
2478-
with mock.patch.object(_reuse, "_sha256", wraps=_reuse._sha256) as sha256:
2490+
from mobius.integrations.gguf._reader import GGUFModel
2491+
2492+
with mock.patch.object(
2493+
GGUFModel,
2494+
"source_sha256",
2495+
autospec=True,
2496+
side_effect=GGUFModel.source_sha256,
2497+
) as sha256:
24792498
package.save(str(tmp_path), progress_bar=False)
24802499
assert sha256.call_count == 1
24812500

@@ -2551,9 +2570,13 @@ def test_save_rehashes_source_immediately_before_publish(
25512570
def mutate_source_before_verification(path, payload):
25522571
nonlocal mutated
25532572
if path.name.startswith(".gguf-reuse.json.") and path.name.endswith(".tmp"):
2554-
source = bytearray(gguf_path.read_bytes())
2555-
source[-1] ^= 1
2556-
gguf_path.write_bytes(source)
2573+
with gguf_path.open("r+b") as stream:
2574+
stream.seek(-1, os.SEEK_END)
2575+
value = stream.read(1)
2576+
stream.seek(-1, os.SEEK_END)
2577+
stream.write(bytes([value[0] ^ 0xFF]))
2578+
stream.flush()
2579+
os.fsync(stream.fileno())
25572580
mutated = True
25582581
return real_write_json(path, payload)
25592582

@@ -2565,6 +2588,211 @@ def mutate_source_before_verification(path, payload):
25652588
assert not (tmp_path / "model.onnx").exists()
25662589
assert not (tmp_path / "gguf-reuse.json").exists()
25672590

2591+
def test_reuse_plan_hashes_the_model_source_used_for_tensor_parsing(
2592+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2593+
):
2594+
from mobius.integrations.gguf import build_from_gguf
2595+
from mobius.integrations.gguf._reader import GGUFModel
2596+
2597+
gguf_path = tmp_path / "model.gguf"
2598+
_write_quantized_gguf(gguf_path, projection_quantization="f32")
2599+
source_sha256 = GGUFModel.source_sha256
2600+
mutated = False
2601+
2602+
def mutate_before_plan_hash(model, **kwargs):
2603+
nonlocal mutated
2604+
if not mutated and Path(model._path) == gguf_path:
2605+
with gguf_path.open("r+b") as stream:
2606+
stream.seek(-1, os.SEEK_END)
2607+
value = stream.read(1)
2608+
stream.seek(-1, os.SEEK_END)
2609+
stream.write(bytes([value[0] ^ 0xFF]))
2610+
mutated = True
2611+
return source_sha256(model, **kwargs)
2612+
2613+
monkeypatch.setattr(GGUFModel, "source_sha256", mutate_before_plan_hash)
2614+
2615+
with pytest.raises(ValueError, match="source changed after its reader was opened"):
2616+
build_from_gguf(gguf_path, reuse_gguf_weights=True)
2617+
assert mutated
2618+
2619+
def test_reuse_plan_with_relative_source_survives_cwd_change(
2620+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2621+
):
2622+
from mobius.integrations.gguf import build_from_gguf, verify_gguf_reuse_manifest
2623+
2624+
gguf_path = tmp_path / "model.gguf"
2625+
_write_quantized_gguf(gguf_path, projection_quantization="f32")
2626+
monkeypatch.chdir(tmp_path)
2627+
package = build_from_gguf(Path("model.gguf"), reuse_gguf_weights=True)
2628+
other = tmp_path / "other"
2629+
other.mkdir()
2630+
monkeypatch.chdir(other)
2631+
2632+
package.save(str(tmp_path), progress_bar=False)
2633+
verify_gguf_reuse_manifest(tmp_path)
2634+
2635+
def test_reuse_verifier_detects_mutation_between_hash_and_tensor_validation(
2636+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2637+
):
2638+
from mobius.integrations.gguf import build_from_gguf, verify_gguf_reuse_manifest
2639+
from mobius.integrations.gguf._reader import GGUFModel
2640+
2641+
gguf_path = tmp_path / "model.gguf"
2642+
_write_quantized_gguf(gguf_path, projection_quantization="f32")
2643+
build_from_gguf(gguf_path, reuse_gguf_weights=True).save(
2644+
str(tmp_path), progress_bar=False
2645+
)
2646+
source_sha256 = GGUFModel.source_sha256
2647+
mutated = False
2648+
2649+
def mutate_after_verifier_hash(model, **kwargs):
2650+
nonlocal mutated
2651+
digest = source_sha256(model, **kwargs)
2652+
if not mutated and Path(model._path) == gguf_path:
2653+
with gguf_path.open("r+b") as stream:
2654+
stream.seek(-1, os.SEEK_END)
2655+
value = stream.read(1)
2656+
stream.seek(-1, os.SEEK_END)
2657+
stream.write(bytes([value[0] ^ 0xFF]))
2658+
mutated = True
2659+
return digest
2660+
2661+
monkeypatch.setattr(GGUFModel, "source_sha256", mutate_after_verifier_hash)
2662+
2663+
with pytest.raises(ValueError, match="reuse manifest was verified"):
2664+
verify_gguf_reuse_manifest(tmp_path)
2665+
assert mutated
2666+
2667+
def test_reuse_verifier_rejects_source_replaced_by_symlink_before_open(
2668+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2669+
):
2670+
from mobius.integrations.gguf import build_from_gguf, verify_gguf_reuse_manifest
2671+
from mobius.integrations.gguf._reader import GGUFModel
2672+
2673+
gguf_path = tmp_path / "model.gguf"
2674+
_write_quantized_gguf(gguf_path, projection_quantization="f32")
2675+
build_from_gguf(gguf_path, reuse_gguf_weights=True).save(
2676+
str(tmp_path), progress_bar=False
2677+
)
2678+
moved_source = tmp_path / "moved-source.gguf"
2679+
original_init = GGUFModel.__init__
2680+
raced = False
2681+
2682+
def replace_before_verifier_open(model, path, **kwargs):
2683+
nonlocal raced
2684+
if not raced and Path(path) == gguf_path:
2685+
gguf_path.replace(moved_source)
2686+
_symlink_or_skip(gguf_path, moved_source)
2687+
raced = True
2688+
return original_init(model, path, **kwargs)
2689+
2690+
monkeypatch.setattr(GGUFModel, "__init__", replace_before_verifier_open)
2691+
2692+
with pytest.raises(ValueError, match="source is missing or unsafe"):
2693+
verify_gguf_reuse_manifest(tmp_path)
2694+
assert raced
2695+
2696+
def test_reuse_verifier_rechecks_symlink_after_final_handle_comparison(
2697+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2698+
):
2699+
from mobius.integrations.gguf import build_from_gguf, verify_gguf_reuse_manifest
2700+
from mobius.integrations.gguf._reader import GGUFModel
2701+
2702+
gguf_path = tmp_path / "model.gguf"
2703+
_write_quantized_gguf(gguf_path, projection_quantization="f32")
2704+
build_from_gguf(gguf_path, reuse_gguf_weights=True).save(
2705+
str(tmp_path), progress_bar=False
2706+
)
2707+
source_matches_path = GGUFModel.source_matches_path
2708+
path_is_symlink = Path.is_symlink
2709+
raced = False
2710+
symlink_recheck_observed = False
2711+
2712+
def replace_after_handle_comparison(model, path=None):
2713+
nonlocal raced
2714+
matches = source_matches_path(model, path)
2715+
if not raced and Path(model._path) == gguf_path:
2716+
assert matches
2717+
raced = True
2718+
return matches
2719+
2720+
def report_post_comparison_symlink(path):
2721+
nonlocal symlink_recheck_observed
2722+
if path == gguf_path and raced:
2723+
symlink_recheck_observed = True
2724+
return True
2725+
return path_is_symlink(path)
2726+
2727+
monkeypatch.setattr(GGUFModel, "source_matches_path", replace_after_handle_comparison)
2728+
monkeypatch.setattr(Path, "is_symlink", report_post_comparison_symlink)
2729+
2730+
with pytest.raises(ValueError, match="reuse manifest was verified"):
2731+
verify_gguf_reuse_manifest(tmp_path)
2732+
assert raced
2733+
assert symlink_recheck_observed
2734+
2735+
def test_reuse_verifier_rechecks_source_after_onnx_validation(
2736+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2737+
):
2738+
from mobius.integrations.gguf import _reuse, build_from_gguf
2739+
2740+
gguf_path = tmp_path / "model.gguf"
2741+
_write_quantized_gguf(gguf_path, projection_quantization="f32")
2742+
build_from_gguf(gguf_path, reuse_gguf_weights=True).save(
2743+
str(tmp_path), progress_bar=False
2744+
)
2745+
load_model = _reuse.ir.load
2746+
mutated = False
2747+
2748+
def mutate_after_onnx_load(path):
2749+
nonlocal mutated
2750+
model = load_model(path)
2751+
if not mutated:
2752+
with gguf_path.open("r+b") as stream:
2753+
stream.seek(-1, os.SEEK_END)
2754+
value = stream.read(1)
2755+
stream.seek(-1, os.SEEK_END)
2756+
stream.write(bytes([value[0] ^ 0xFF]))
2757+
mutated = True
2758+
return model
2759+
2760+
monkeypatch.setattr(_reuse.ir, "load", mutate_after_onnx_load)
2761+
2762+
with pytest.raises(ValueError, match="reuse manifest was verified"):
2763+
_reuse.verify_gguf_reuse_manifest(tmp_path)
2764+
assert mutated
2765+
2766+
def test_reuse_save_rechecks_source_immediately_before_publication(
2767+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
2768+
):
2769+
from mobius.integrations.gguf import _reuse, build_from_gguf
2770+
2771+
gguf_path = tmp_path / "model.gguf"
2772+
_write_quantized_gguf(gguf_path, projection_quantization="f32")
2773+
package = build_from_gguf(gguf_path, reuse_gguf_weights=True)
2774+
verify_manifest = _reuse.verify_gguf_reuse_manifest
2775+
mutated = False
2776+
2777+
def mutate_after_verification(*args, **kwargs):
2778+
nonlocal mutated
2779+
result = verify_manifest(*args, **kwargs)
2780+
with gguf_path.open("r+b") as stream:
2781+
stream.seek(-1, os.SEEK_END)
2782+
value = stream.read(1)
2783+
stream.seek(-1, os.SEEK_END)
2784+
stream.write(bytes([value[0] ^ 0xFF]))
2785+
mutated = True
2786+
return result
2787+
2788+
monkeypatch.setattr(_reuse, "verify_gguf_reuse_manifest", mutate_after_verification)
2789+
2790+
with pytest.raises(ValueError, match="package was being prepared"):
2791+
package.save(str(tmp_path), progress_bar=False)
2792+
assert mutated
2793+
assert not (tmp_path / "model.onnx").exists()
2794+
assert not (tmp_path / "gguf-reuse.json").exists()
2795+
25682796
def test_native_projection_bytes_are_not_copied_to_sidecar(self, tmp_path: Path):
25692797
from mobius.integrations.gguf import build_from_gguf
25702798
from mobius.integrations.gguf._reader import GGUFModel
@@ -4240,6 +4468,50 @@ def test_tencent_q1_0_preflight_uses_layout_and_exact_payload_bytes(
42404468
}
42414469
assert any(node.op_type == "MatMulNBits" for node in package["model"].graph)
42424470

4471+
def test_tencent_q1_0_reads_pinned_bytes_during_symlink_aba(self, tmp_path: Path):
4472+
from mobius.integrations.gguf._reader import GGUFModel
4473+
from mobius.integrations.gguf._tencent_q1_0 import parse_tencent_q1_0_tensor
4474+
4475+
source_a = tmp_path / "source-a.gguf"
4476+
source_b = tmp_path / "source-b.gguf"
4477+
_write_tencent_q1_0_gguf(source_a)
4478+
_write_tencent_q1_0_gguf(source_b)
4479+
inspect_b = GGUFModel(source_b)
4480+
_read_b, data_offset_b, tensor_b = inspect_b._tensor_source("blk.0.attn_q.weight")
4481+
tensor_offset_b = int(tensor_b.field.parts[tensor_b.field.data[-1]][0])
4482+
inspect_b.close()
4483+
with source_b.open("r+b") as stream:
4484+
stream.seek(data_offset_b + tensor_offset_b + 2)
4485+
value = stream.read(1)
4486+
stream.seek(data_offset_b + tensor_offset_b + 2)
4487+
stream.write(bytes([value[0] ^ 0xFF]))
4488+
4489+
logical = tmp_path / "logical.gguf"
4490+
_symlink_or_skip(logical, source_a)
4491+
model_a = GGUFModel(logical)
4492+
read_a, data_offset_a, tensor_a = model_a._tensor_source("blk.0.attn_q.weight")
4493+
expected = parse_tencent_q1_0_tensor(read_a, data_offset_a, tensor_a)
4494+
4495+
logical.unlink()
4496+
_symlink_or_skip(logical, source_b)
4497+
injected = parse_tencent_q1_0_tensor(read_a, data_offset_a, tensor_a)
4498+
logical.unlink()
4499+
_symlink_or_skip(logical, source_a)
4500+
4501+
model_b = GGUFModel(source_b)
4502+
read_b, replacement_offset, replacement_tensor = model_b._tensor_source(
4503+
"blk.0.attn_q.weight"
4504+
)
4505+
replacement = parse_tencent_q1_0_tensor(
4506+
read_b,
4507+
replacement_offset,
4508+
replacement_tensor,
4509+
)
4510+
4511+
np.testing.assert_array_equal(injected.weight, expected.weight)
4512+
assert not np.array_equal(injected.weight, replacement.weight)
4513+
assert model_a.source_matches_path()
4514+
42434515
def test_preflight_records_mapped_bias_and_scale_parameters(self) -> None:
42444516
from gguf import GGMLQuantizationType
42454517
from onnxscript import nn

0 commit comments

Comments
 (0)