Files
Joseph Magly 0ca0d1d77e feat(gguf): add native GGUF toolkit
Add bounded GGUF v2/v3 parsing, transactional metadata and tensor edits,
split-file handling, provenance manifests, exact GGML storage typing, and
measurement-gated quantization planning. Preserve unmodified payloads
byte-for-byte and expose the toolkit through `obliteratus gguf`.

Verification:
- 57 focused tests on each of Python 3.11, 3.12, and 3.14.
- 377 combined focused, CLI, risk-map, CI-policy, package-export, and
  CLI-boundary tests on Python 3.14.
- 2,000 randomized exact-DP comparisons against brute force.
- Real single-file and three-shard GGUF metadata edits with tensor hashes
  preserved; independent GGUF reader opened every output.
- Ruff, risk-map validation, wheel/sdist build, and isolated wheel CLI smoke.

No real Qwen4 conversion or inference was run; runtime and quality
qualification remain separate gates.
2026-12-04 18:35:28 -05:00

166 lines
6.2 KiB
Python

"""CLI contracts for the GGUF toolkit; no model payload or external tool needed."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pytest
from obliteratus.gguf.format import MetadataValue, TensorInput, write_gguf
from obliteratus.gguf.optimize import PROFILE_SCHEMA
from obliteratus.gguf.patch import PATCH_SCHEMA
from obliteratus.gguf.spec import GGMLType, META_STRING
from obliteratus.gguf_cli import add_parser, run
pytestmark = pytest.mark.cpu
def _make_source(tmp_path: Path) -> Path:
payload = tmp_path / "payload.bin"
payload.write_bytes(np.ones(256, dtype="<f4").tobytes())
path = tmp_path / "model.gguf"
write_gguf(
path,
version=3,
metadata={"general.name": MetadataValue(META_STRING, "cli-test")},
tensors=[TensorInput(
name="blk.0.weight", shape=(256,), type_id=int(GGMLType.F32),
n_bytes=1024, source_path=payload, source_offset=0,
)],
)
return path
def test_parser_exposes_all_gguf_subcommands():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command")
add_parser(subparsers)
args = parser.parse_args(["gguf", "apply", "patch.json", "--output-dir", "out", "--json"])
assert args.command == "gguf"
assert args.gguf_command == "apply"
assert args.output_dir == Path("out")
assert args.json is True
def test_cli_inspect_plan_apply_verify(tmp_path, capsys):
source = _make_source(tmp_path)
assert run(SimpleNamespace(
gguf_command="inspect", sources=[source], json=True,
hash=True, hash_tensors=True,
)) == 0
inspected = json.loads(capsys.readouterr().out)
assert inspected["tensor_count"] == 1
assert len(inspected["sha256"]) == 64
assert len(inspected["tensor_sha256"]["blk.0.weight"]) == 64
patch_path = tmp_path / "patch.json"
patch_path.write_text(json.dumps({
"schema": PATCH_SCHEMA,
"sources": {"base": str(source)},
"metadata": {"set": {"general.name": "cli-edited"}},
"operations": [{"op": "scale", "name": "blk.0.weight", "alpha": 0.5}],
}))
assert run(SimpleNamespace(gguf_command="plan", patch=patch_path, json=True)) == 0
plan = json.loads(capsys.readouterr().out)
assert plan["outputs"][0]["tensor_count"] == 1
output_dir = tmp_path / "out"
assert run(SimpleNamespace(
gguf_command="apply", patch=patch_path, output_dir=output_dir,
overwrite=False, hash_sources=False, json=True,
)) == 0
manifest = json.loads(capsys.readouterr().out)
assert manifest["verification"]["status"] == "passed"
assert run(SimpleNamespace(
gguf_command="verify", sources=[], manifest=output_dir / "edit_manifest.json", json=True,
)) == 0
verified = json.loads(capsys.readouterr().out)
assert verified["status"] == "passed"
def test_cli_optimize_and_features_write_sidecars(tmp_path, capsys):
source = _make_source(tmp_path)
stats = tmp_path / "stats.json"
stats.write_text(json.dumps({"tensors": {
"blk.0.weight": {"sensitivity": {"Q4_K": 1.0, "Q8_0": 0.1}},
}}))
profile = tmp_path / "profile.json"
profile.write_text(json.dumps({
"schema": PROFILE_SCHEMA,
"source": str(source),
"tensor_stats": str(stats),
"candidate_types": ["Q4_K", "Q8_0"],
"baseline_type": "Q4_K",
"budget_bytes": 300,
}))
plan_output = tmp_path / "quant-plan.json"
types_output = tmp_path / "tensor-types.txt"
assert run(SimpleNamespace(
gguf_command="optimize", profile=profile, output=plan_output,
tensor_type_file=types_output, json=True,
)) == 0
plan = json.loads(capsys.readouterr().out)
assert plan["total_tensor_bytes"] <= 300
assert plan["review"]["source_files"] == [str(source)]
assert plan["review"]["tensor_type_file_path"] == str(types_output)
assert str(types_output) in plan["review"]["llama_quantize_argv"]
assert json.loads(plan_output.read_text())["schema"] == plan["schema"]
assert "blk.0.weight=" in types_output.read_text()
features_output = tmp_path / "features.json"
assert run(SimpleNamespace(
gguf_command="features", source=source, sample_rows=1,
max_tensors=None, output=features_output, json=True,
)) == 0
features = json.loads(capsys.readouterr().out)
assert features["features"]["blk.0.weight"]["status"] == "measured"
assert json.loads(features_output.read_text())["tensor_count"] == 1
# Existing outputs are not overwritten implicitly.
assert run(SimpleNamespace(
gguf_command="optimize", profile=profile, output=plan_output,
tensor_type_file=None, json=True,
)) == 2
error = json.loads(capsys.readouterr().out)
assert error["status"] == "error"
def test_cli_audit_reuses_lexotomy_detector(tmp_path, capsys):
from obliteratus.gguf_cot_knob import quantize_q8_0_row
rows = []
for index in range(4):
rows.append(quantize_q8_0_row(
np.full(64, 0.1 * (index + 1), dtype=np.float32)
))
payload = b"".join(rows)
source = tmp_path / "audit.gguf"
(tmp_path / "audit-out.bin").write_bytes(payload)
(tmp_path / "audit-emb.bin").write_bytes(payload)
write_gguf(
source,
version=3,
metadata={"general.name": MetadataValue(META_STRING, "audit")},
tensors=[
TensorInput("output.weight", (64, 4), int(GGMLType.Q8_0), len(payload),
tmp_path / "audit-out.bin", 0),
TensorInput("token_embd.weight", (64, 4), int(GGMLType.Q8_0), len(payload),
tmp_path / "audit-emb.bin", 0),
],
)
assert run(SimpleNamespace(
gguf_command="audit", source=source, special_token_ids=[0, 1],
we_token_ids=None, peer_token_ids=None, bg_sample_size=2,
z_threshold=8.0, sibling_fold_threshold=1.75, q6k_spike_min=4.0,
we_twin_cosine=0.90, we_subrow_top_k=256, we_subrow_cosine=0.75,
output_tensor="output.weight", embed_tensor="token_embd.weight", json=True,
)) == 0
result = json.loads(capsys.readouterr().out)
assert result["file"] == "audit.gguf"
assert "flagged" in result and "alerts" in result