194 lines · 7.7 KB · PythonRaw
# /// script# requires-python = ">=3.11,<3.12"# dependencies = [# "facenet-pytorch==2.6.0",# "coremltools>=8,<10",# "torch>=2.2,<2.3",# "numpy<2",# "pillow",# ]# ///"""Build FaceEmbedder.mlmodelc — the face identity model the helper's `faceembed` op runs. uv run apps/cotton/helper/model/convert_face_embedder.py --out apps/cotton/nativeThe model is InceptionResnetV1 from facenet-pytorch (Tim Esler, MIT), with theVGGFace2-pretrained weights the same project publishes under the same licence(design note §6). NOTHING is committed: the weights are fetched from theproject's GitHub release into helper/.build/model/, verified against thesha256 recorded below, converted with coremltools, checked against PyTorch ona synthetic image, then compiled with `xcrun coremlcompiler` into the outputdirectory. A changed checksum is a stop, not a warning.Input "face": one 160 × 160 RGB image; the model standardises it as (x − 127.5) / 128, facenet-pytorch's fixed_image_standardization.Output "embedding": 512 float32, L2-normalised (the network's own forward does that when classify=False; the helper normalises again)."""from __future__ import annotationsimport argparseimport hashlibimport shutilimport subprocessimport sysimport urllib.requestfrom pathlib import PathWEIGHTS_URL = "https://github.com/timesler/facenet-pytorch/releases/download/v2.2.9/20180402-114759-vggface2.pt"WEIGHTS_SHA256 = "281cebca8662831adb987a874bdcb36e73f5b1c6dc5ee5878f305e985625d99b"# facenet-pytorch's VGGFace2 checkpoint carries an 8631-way classifier head;# the constructor needs the number to build a state dict of the same shape.VGGFACE2_CLASSES = 8631MODEL_ID = "facenet-vggface2/v1"MODEL_NAME = "FaceEmbedder"DIMENSION = 512SIDE = 160HERE = Path(__file__).resolve().parentCACHE = HERE.parent / ".build" / "model"def sha256_of(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1 << 20), b""): digest.update(chunk) return digest.hexdigest()def fetch_weights() -> Path: CACHE.mkdir(parents=True, exist_ok=True) target = CACHE / Path(WEIGHTS_URL).name if not target.exists() or sha256_of(target) != WEIGHTS_SHA256: print(f"fetching {WEIGHTS_URL}") tmp = target.with_suffix(".part") urllib.request.urlretrieve(WEIGHTS_URL, tmp) tmp.replace(target) actual = sha256_of(target) if actual != WEIGHTS_SHA256: sys.exit( f"weights at {target} have sha256 {actual}, expected {WEIGHTS_SHA256}.\n" "The published file changed; nothing was built. Verify the release and update the constant deliberately." ) return targetdef build_torch_model(weights: Path): import torch from facenet_pytorch import InceptionResnetV1 model = InceptionResnetV1(pretrained=None, classify=False, num_classes=VGGFACE2_CLASSES) state = torch.load(weights, map_location="cpu") # The checkpoint carries the classifier head ("logits.*"); with # classify=False the network has no such layer, and an embedding never # touches it. Drop exactly those keys and load the rest strictly. embedding_state = {key: value for key, value in state.items() if not key.startswith("logits.")} missing, unexpected = model.load_state_dict(embedding_state, strict=False) if missing or unexpected: sys.exit(f"the checkpoint does not match InceptionResnetV1: missing {missing}, unexpected {unexpected}") return model.eval()def convert(model, out_package: Path) -> None: import coremltools as ct import torch example = torch.zeros(1, 3, SIDE, SIDE) traced = torch.jit.trace(model, example) mlmodel = ct.convert( traced, inputs=[ ct.ImageType( name="face", shape=(1, 3, SIDE, SIDE), scale=1 / 128.0, bias=[-127.5 / 128.0] * 3, color_layout=ct.colorlayout.RGB, ) ], outputs=[ct.TensorType(name="embedding")], convert_to="mlprogram", minimum_deployment_target=ct.target.macOS14, compute_precision=ct.precision.FLOAT16, ) mlmodel.author = "Tim Esler (facenet-pytorch, MIT); converted for CottonDB" mlmodel.license = "MIT" mlmodel.short_description = "InceptionResnetV1 face embedding, VGGFace2 weights: 160×160 RGB face → 512-d L2-normalised vector" mlmodel.version = MODEL_ID mlmodel.user_defined_metadata["model"] = MODEL_ID mlmodel.user_defined_metadata["dimension"] = str(DIMENSION) mlmodel.user_defined_metadata["weightsSha256"] = WEIGHTS_SHA256 mlmodel.user_defined_metadata["weightsUrl"] = WEIGHTS_URL if out_package.exists(): shutil.rmtree(out_package) mlmodel.save(str(out_package))def check_against_torch(model, out_package: Path) -> float: """Cosine similarity between Core ML and PyTorch on one synthetic face-shaped blob.""" import coremltools as ct import numpy as np import torch from PIL import Image rng = np.random.default_rng(7) ys, xs = np.mgrid[0:SIDE, 0:SIDE] blob = np.exp(-(((xs - 80) / 45) ** 2 + ((ys - 85) / 60) ** 2)) pixels = np.stack( [200 * blob + 30, 160 * blob + 40, 140 * blob + 50], axis=-1 ) + rng.normal(0, 6, (SIDE, SIDE, 3)) pixels = np.clip(pixels, 0, 255).astype(np.uint8) image = Image.fromarray(pixels, "RGB") tensor = torch.from_numpy(pixels.astype(np.float32)).permute(2, 0, 1).unsqueeze(0) with torch.no_grad(): reference = model((tensor - 127.5) / 128.0).numpy()[0] mlmodel = ct.models.MLModel(str(out_package)) produced = np.asarray(mlmodel.predict({"face": image})["embedding"]).reshape(-1).astype(np.float32) if produced.shape[0] != DIMENSION: sys.exit(f"Core ML answered {produced.shape[0]} values, expected {DIMENSION}") cosine = float(np.dot(reference, produced) / (np.linalg.norm(reference) * np.linalg.norm(produced))) return cosinedef compile_model(out_package: Path, out_dir: Path) -> Path: compiled = out_dir / f"{MODEL_NAME}.mlmodelc" if compiled.exists(): shutil.rmtree(compiled) out_dir.mkdir(parents=True, exist_ok=True) result = subprocess.run( ["xcrun", "coremlcompiler", "compile", str(out_package), str(out_dir)], capture_output=True, text=True, ) if result.returncode != 0: sys.exit(f"coremlcompiler failed (Xcode, not just the Command Line Tools, provides it):\n{result.stdout}\n{result.stderr}") if not compiled.is_dir(): sys.exit(f"coremlcompiler produced nothing at {compiled}") return compileddef main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--out", required=True, help="directory that receives FaceEmbedder.mlmodelc (the helper's own directory)") parser.add_argument("--min-cosine", type=float, default=0.99, help="Core ML vs PyTorch agreement required on the check image") args = parser.parse_args() out_dir = Path(args.out).resolve() weights = fetch_weights() model = build_torch_model(weights) package = CACHE / f"{MODEL_NAME}.mlpackage" convert(model, package) cosine = check_against_torch(model, package) if cosine < args.min_cosine: sys.exit(f"Core ML disagrees with PyTorch on the check image: cosine {cosine:.4f} < {args.min_cosine}. Nothing was installed.") compiled = compile_model(package, out_dir) size = sum(p.stat().st_size for p in compiled.rglob("*") if p.is_file()) print(f"built {compiled} — {MODEL_ID}, {DIMENSION}-d, {size / 1e6:.1f} MB, Core ML vs PyTorch cosine {cosine:.4f}")if __name__ == "__main__": main()