"""Text-only HF checkpoint for export (plan section 4, "导出纯文本检查点"). ``save_text_only(weights, out_dir)`` writes a HF-format ``Qwen3_5ForCausalLM`` checkpoint (``model_type: qwen3_5_text``) without the vision tower and the MTP head, plus the tokenizer and a manifest. ``weights`` accepts everything ``macjev.eval.torch_scorer`` accepts (base repo id / HF dir, a ``weights-*.safetensors`` from ``macjev.train``, or a run dir with ``checkpoints.json``), so the export sees exactly the weights the evaluator scored. Both converters accept this layout (verified 2026-09-23, see tests/macjev/export and RUNTIME_SWITCH.md): llama.cpp ``convert_hf_to_gguf.py`` registers ``Qwen3_5ForCausalLM`` (-> arch ``qwen35``) and mlx-lm ``qwen3_5`` wraps a flat text config. mlx-lm decides whether to apply the Qwen3.5 ``1 + w`` RMSNorm shift by detecting un-sanitised ``conv1d`` weights (HF layout ``[C, 1, K]``); the HF layout is kept on purpose so the shift still happens without MTP. """ from __future__ import annotations import hashlib import json import shutil import time from pathlib import Path import torch from .. import backbone as bb from ..eval.torch_scorer import _load_state_into, _resolve_weights TEXT_ONLY_VERSION = "macjev-text-only-v1" DEFAULT_BASE = "Qwen/Qwen3.5-0.8B-Base" def sha256_file(path: Path, chunk: int = 1 << 22) -> str: h = hashlib.sha256() with open(path, "rb") as f: while True: b = f.read(chunk) if not b: break h.update(b) return h.hexdigest() def load_torch(weights: str | Path, base: str = DEFAULT_BASE, dtype: torch.dtype = torch.bfloat16, device: str = "cpu") -> tuple[bb.Backbone, dict]: """Load weights exactly like TorchScorer does (text model only).""" kind, path = _resolve_weights(weights) if kind == "hf": b = bb.load(path or weights, device="cpu", dtype=dtype) info = {"kind": "hf", "path": str(b.path)} else: b = bb.load(base, device="cpu", dtype=dtype) info = {"kind": "safetensors", "path": str(path), "base": str(b.path), **_load_state_into(b.model, path)} b.model.to(device).eval() return b, info def weights_fingerprint(weights: str | Path, base: str = DEFAULT_BASE) -> dict: """sha256 of the weight files ``weights`` resolves to (plus the base architecture for a bare safetensors file), so an existing export is only reused for exactly the same weights.""" kind, path = _resolve_weights(weights) if kind == "safetensors": files = [Path(path)] arch = str(bb.resolve(base).name) + "/" + json.loads((bb.resolve(base) / "config.json").read_text()).get( "model_type", "?") else: d = Path(path) if path else bb.resolve(weights) files = sorted(d.glob("*.safetensors")) arch = None return {"kind": kind, "arch_from_base": arch, "sha256": {f.name: sha256_file(f) for f in files}} def save_text_only(weights: str | Path, out_dir: str | Path, base: str = DEFAULT_BASE, overwrite: bool = False) -> dict: out = Path(out_dir) fingerprint = weights_fingerprint(weights, base) if out.exists() and any(out.iterdir()): if not overwrite: manifest = out / "text_only_manifest.json" if manifest.exists(): m = json.loads(manifest.read_text()) if m.get("source_fingerprint") == fingerprint: return m raise FileExistsError(f"{out} holds a text-only export of different (or unfingerprinted) weights; " "use a new --out or overwrite=True (a stale export is never reused)") raise FileExistsError(f"{out} exists and is not a text-only export") shutil.rmtree(out) b, info = load_torch(weights, base=base) try: from mac_laya.artifacts import resource_guard resource_guard(int(b.parameter_count() * 2 * 1.1)) except ImportError: # pragma: no cover - mac_laya always present in this repo pass out.mkdir(parents=True, exist_ok=True) b.model.config.architectures = ["Qwen3_5ForCausalLM"] if b.arch == "qwen3_5" else b.model.config.architectures b.model.save_pretrained(out, safe_serialization=True) b.tokenizer.save_pretrained(out) src = Path(info.get("base") or info["path"]) for extra in ("LICENSE", "generation_config.json"): if (src / extra).exists() and not (out / extra).exists(): shutil.copy2(src / extra, out / extra) cfg = json.loads((out / "config.json").read_text()) files = sorted(p.name for p in out.glob("*.safetensors")) n_params = b.parameter_count() manifest = {"version": TEXT_ONLY_VERSION, "created_unix": time.time(), "source": info, "source_fingerprint": fingerprint, "architectures": cfg.get("architectures"), "model_type": cfg.get("model_type"), "dtype": "bfloat16", "parameters_text_model": n_params, "dropped": (["vision tower (model.visual.*)", "MTP head (mtp.*)"] if b.arch == "qwen3_5" else []), "tie_word_embeddings": bool(cfg.get("tie_word_embeddings")), "files": {f: sha256_file(out / f) for f in files}} (out / "text_only_manifest.json").write_text(json.dumps(manifest, indent=2)) return manifest def main(argv=None): import argparse ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--weights", required=True) ap.add_argument("--out", required=True) ap.add_argument("--base", default=DEFAULT_BASE) ap.add_argument("--overwrite", action="store_true") a = ap.parse_args(argv) print(json.dumps(save_text_only(a.weights, a.out, a.base, a.overwrite), indent=2)) if __name__ == "__main__": main()