"""GGUF (llama.cpp) and MLX conversion of a text-only checkpoint. GGUF: ``third_party/llama.cpp/convert_hf_to_gguf.py --no-mtp --outtype f16`` (the text-only checkpoint has no MTP tensors; without ``--no-mtp`` the converter declares 25 blocks and llama.cpp fails with ``blk.24.attn_norm.weight not found``), then ``llama-quantize`` to Q8_0 and Q4_K_M. F16 rather than BF16 because the M1 Max (Apple GPU family 7) has no native bf16. Non-Qwen3.5 text checkpoints (the MiniCPM5 ``llama`` arm) convert without ``--no-mtp`` and without the MLX relabel. MLX: ``mlx_lm.convert`` to bf16 and affine 8/4-bit (group size 64). mlx-lm 0.31.3 only registers ``model_type: qwen3_5`` (not the HF text-only ``qwen3_5_text``), so conversion reads a staging directory whose config.json is the text-only config with ``model_type`` relabelled to ``qwen3_5`` (weights and tokenizer are symlinks; nothing else changes - mlx-lm's ``ModelArgs`` wraps a flat config as ``text_config``). The affine formats are named ``affine8-g64`` / ``affine4-g64``: they are NOT Q8_0 / Q4_K_M. """ from __future__ import annotations import json import os import subprocess import sys import time from pathlib import Path from ..paths import ROOT from .text_only import sha256_file LLAMA_CPP = ROOT / "third_party" / "llama.cpp" QUANTIZE_BIN = LLAMA_CPP / "build" / "bin" / "llama-quantize" GGUF_FORMATS = {"gguf-f16": ("f16", None), "gguf-q8_0": ("q8_0", "Q8_0"), "gguf-q4_k_m": ("q4_k_m", "Q4_K_M")} MLX_FORMATS = {"mlx-bf16": ("bf16", None), "mlx-8bit": ("affine8-g64", 8), "mlx-4bit": ("affine4-g64", 4)} ALL_FORMATS = list(GGUF_FORMATS) + list(MLX_FORMATS) def llama_cpp_commit() -> str: try: return subprocess.check_output(["git", "-C", str(LLAMA_CPP), "rev-parse", "HEAD"], text=True).strip() except Exception: return "unknown" def _guard(nbytes: int) -> None: from mac_laya.artifacts import resource_guard resource_guard(nbytes) def text_only_id(text_only: Path) -> dict: """sha256 of the text-only weight files (from its manifest; hashed if there is none).""" man = Path(text_only) / "text_only_manifest.json" if man.exists(): return json.loads(man.read_text())["files"] return {p.name: sha256_file(p) for p in sorted(Path(text_only).glob("*.safetensors"))} def _check_stamp(out_dir: Path, src: dict, existing: list[Path]) -> None: """Outputs in ``out_dir`` are reused only if they were built from exactly this text-only checkpoint (``source.json``); anything else is refused, never silently reused.""" stamp = out_dir / "source.json" if stamp.exists(): if json.loads(stamp.read_text()) != src: raise FileExistsError(f"{out_dir} holds exports of a different text-only checkpoint; use a new --out") elif existing: raise FileExistsError(f"{out_dir} holds unstamped exports ({existing[0].name}...); use a new --out") out_dir.mkdir(parents=True, exist_ok=True) stamp.write_text(json.dumps(src, indent=2)) def is_qwen35_text(text_only: Path) -> bool: """True for the Qwen3.5 text-only layout (``model_type: qwen3_5_text``); False for e.g. the MiniCPM5 (``llama``) base arm of plan section 4.5, which has no MTP and a native mlx-lm type.""" return json.loads((Path(text_only) / "config.json").read_text()).get("model_type") == "qwen3_5_text" def to_gguf(text_only: Path, out_dir: Path, formats: list[str], log_dir: Path | None = None) -> dict: out_dir.mkdir(parents=True, exist_ok=True) _check_stamp(out_dir, text_only_id(text_only), sorted(out_dir.glob("*.gguf"))) log_dir = log_dir or out_dir f16 = out_dir / "model-f16.gguf" res = {} size = sum(p.stat().st_size for p in text_only.glob("*.safetensors")) if not f16.exists(): _guard(int(size * 1.1)) env = {**os.environ, "PYTHONPATH": str(LLAMA_CPP / "gguf-py")} # --no-mtp only for qwen35: the converter exits with an error for architectures without MTP cmd = [sys.executable, str(LLAMA_CPP / "convert_hf_to_gguf.py"), str(text_only), *(["--no-mtp"] if is_qwen35_text(text_only) else []), "--outtype", "f16", "--outfile", str(f16)] t0 = time.time() with open(log_dir / "convert_gguf.log", "w") as log: subprocess.run(cmd, check=True, env=env, stdout=log, stderr=subprocess.STDOUT) res["convert_seconds"] = time.time() - t0 for fmt in formats: stem, qtype = GGUF_FORMATS[fmt] path = out_dir / f"model-{stem}.gguf" if qtype and not path.exists(): if not QUANTIZE_BIN.exists(): raise FileNotFoundError(f"{QUANTIZE_BIN} missing; build llama.cpp (tools/macjev-score/build.sh)") _guard(int(size * 0.6)) with open(log_dir / f"quantize_{stem}.log", "w") as log: subprocess.run([str(QUANTIZE_BIN), str(f16), str(path), qtype], check=True, stdout=log, stderr=subprocess.STDOUT) res[fmt] = {"path": str(path), "bytes": path.stat().st_size, "sha256": sha256_file(path), "quant": qtype or "F16"} if "gguf-f16" not in formats: res["intermediate_f16"] = {"path": str(f16), "bytes": f16.stat().st_size} res["llama_cpp_commit"] = llama_cpp_commit() return res def mlx_staging(text_only: Path, stage: Path) -> Path: stage.mkdir(parents=True, exist_ok=True) for p in text_only.iterdir(): if p.name == "config.json": continue link = stage / p.name if link.is_symlink() or link.exists(): link.unlink() link.symlink_to(p.resolve()) cfg = json.loads((text_only / "config.json").read_text()) if cfg.get("model_type") == "qwen3_5_text": # only Qwen3.5 needs the relabel (see module doc) cfg["model_type"] = "qwen3_5" else: cfg = _flatten_rope(cfg) (stage / "config.json").write_text(json.dumps(cfg, indent=2)) return stage def _flatten_rope(cfg: dict) -> dict: """transformers >= 5 saves ``rope_parameters: {rope_theta, rope_type, ...}`` and no top-level ``rope_theta``; mlx-lm's ``llama`` ModelArgs only reads ``rope_theta`` / ``rope_scaling`` and would silently fall back to theta 10000 (found in review: MiniCPM5 arm, theta 5e6). qwen3_5 in mlx-lm reads ``rope_parameters`` itself and is not touched.""" rp = cfg.get("rope_parameters") if not isinstance(rp, dict): return cfg cfg = dict(cfg) if "rope_theta" in rp: if "rope_theta" in cfg and float(cfg["rope_theta"]) != float(rp["rope_theta"]): raise ValueError(f"conflicting rope_theta {cfg['rope_theta']} vs rope_parameters {rp['rope_theta']}") cfg["rope_theta"] = rp["rope_theta"] rtype = rp.get("rope_type", rp.get("type", "default")) if rtype not in (None, "default"): if cfg.get("rope_scaling") not in (None, {}): raise ValueError("both rope_scaling and non-default rope_parameters present; refusing to guess") cfg["rope_scaling"] = {k: v for k, v in rp.items() if k != "rope_theta"} return cfg def to_mlx(text_only: Path, out_dir: Path, formats: list[str], group_size: int = 64) -> dict: from mlx_lm import convert import mlx.core as mx import mlx_lm out_dir.mkdir(parents=True, exist_ok=True) _check_stamp(out_dir, text_only_id(text_only), [out_dir / MLX_FORMATS[f][0] for f in MLX_FORMATS if (out_dir / MLX_FORMATS[f][0]).exists()]) stage = mlx_staging(text_only, out_dir / "_stage") size = sum(p.stat().st_size for p in text_only.glob("*.safetensors")) res = {"mlx": mx.__version__, "mlx_lm": mlx_lm.__version__} for fmt in formats: name, bits = MLX_FORMATS[fmt] path = out_dir / name if not (path / "config.json").exists(): _guard(int(size * (1.1 if bits is None else bits / 14))) if bits is None: convert(str(stage), str(path), dtype="bfloat16") else: convert(str(stage), str(path), quantize=True, q_bits=bits, q_group_size=group_size, q_mode="affine", dtype="bfloat16") files = sorted(path.glob("*.safetensors")) res[fmt] = {"path": str(path), "bytes": sum(f.stat().st_size for f in files), "sha256": {f.name: sha256_file(f) for f in files}, "quant": "none (bf16)" if bits is None else f"mlx affine {bits}-bit, group {group_size}"} return res