"""Convert DecidaBERT to one multifunction Core ML package: one function per fixed length (`len_512`, `len_1024`, ...), weights stored once. Inputs input_ids / attention_mask [1, L] int32; output logits [1, 3, L] (noul, choice, score). Writes build/coreml//.mlpackage and decida.json with what the app needs to build the layout and read the answers. .venv/bin/python -I tools/convert_coreml.py --model build/hf/DecidaBERT-large-v2 --name DecidaBERT-large-v2 .venv/bin/python -I tools/convert_coreml.py --model build/hf/DecidaBERT-large-v2 --name DecidaBERT-large-v2-int8 --weights int8 """ from __future__ import annotations import argparse import json import os import shutil import sys import time import coremltools as ct import numpy as np import torch ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) from baseline import load_package # noqa: E402 from coreml_model import FixedLengthDecida # noqa: E402 def convert_bucket(model, length: int, path: str, weights: str = "float16") -> None: wrapped = FixedLengthDecida(model, length).eval() ids = torch.full((1, length), 50283, dtype=torch.int32) mask = torch.ones((1, length), dtype=torch.int32) with torch.no_grad(): traced = torch.jit.trace(wrapped, (ids, mask)) ml = ct.convert( traced, inputs=[ct.TensorType("input_ids", shape=(1, length), dtype=np.int32), ct.TensorType("attention_mask", shape=(1, length), dtype=np.int32)], outputs=[ct.TensorType("logits", dtype=np.float32)], convert_to="mlprogram", minimum_deployment_target=ct.target.iOS18, # native scaled_dot_product_attention compute_precision=ct.precision.FLOAT16, ) if weights == "int8": # Data-free 8-bit weights, one scale per output channel; activations stay float16. op = ct.optimize.coreml.OpLinearQuantizerConfig(mode="linear_symmetric", granularity="per_channel") ml = ct.optimize.coreml.linear_quantize_weights(ml, ct.optimize.coreml.OptimizationConfig(global_config=op)) ml.save(path) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--name", required=True) ap.add_argument("--package", default=os.path.join(ROOT, "reference/model-v2/decidabert_v2")) ap.add_argument("--buckets", default="512,1024,2048,4096,8192") ap.add_argument("--out", default=os.path.join(ROOT, "build/coreml")) ap.add_argument("--weights", choices=["float16", "int8"], default="float16") args = ap.parse_args() buckets = [int(b) for b in args.buckets.split(",")] model = load_package(args.package).load(args.model, device="cpu") out = os.path.join(args.out, args.name) parts = os.path.join(out, "parts") os.makedirs(parts, exist_ok=True) desc = ct.utils.MultiFunctionDescriptor() for b in buckets: t = time.time() p = os.path.join(parts, f"{args.name}-{b}.mlpackage") convert_bucket(model, b, p, args.weights) desc.add_function(p, src_function_name="main", target_function_name=f"len_{b}") print(f"converted len_{b} in {time.time() - t:.0f}s", flush=True) desc.default_function_name = f"len_{buckets[0]}" final = os.path.join(out, f"{args.name}.mlpackage") shutil.rmtree(final, ignore_errors=True) ct.utils.save_multifunction(desc, final) shutil.rmtree(parts) dc = json.load(open(os.path.join(args.model, "decision_config.json"))) tok = model.layout meta = {"name": args.name, "weights": args.weights, "buckets": buckets, "functions": [f"len_{b}" for b in buckets], "max_len": dc["max_len"], "head_max_tokens": dc["head_max_tokens"], "option_max_tokens": dc["option_max_tokens"], "confidence_temperature": dc["confidence_temperature"], "tokens": {"cls": tok.CLS, "sep": tok.SEP, "mask": tok.MASK, "pad": tok.PAD}, "outputs": {"logits": "[1, 3, L]: row 0 noul, 1 choice, 2 score"}} json.dump(meta, open(os.path.join(out, "decida.json"), "w"), indent=1) print("wrote", final) if __name__ == "__main__": main()