Cotton code
196 lines · 9.1 KB · PythonRaw
#!/usr/bin/env python3"""Cotton Albums' face identity models: convert to Core ML, and measure them on synthetic faces.    python scripts/albums-face-models.py convert --models <dir> --out <dir>    python scripts/albums-face-models.py bench --models <dir> --faces <HyperFace dir> [--people 200]    python scripts/albums-face-models.py export-hyperface --models <dir>      (then convert/bench --only hyperface)Needs Python 3.12 with torch, onnx, onnx2torch, coremltools, onnxruntime and numpy (not the repo's own tooling: runit from a venv of its own). Nothing here touches a person's photos: the faces are HyperFace's (Zenodo 15087238,CC BY-SA 4.0), 112 px pictures of made-up people already aligned on ArcFace's five-point template.The models (assets/design/albums/RESEARCH.md §2 and the lane's report):  sface     OpenCV Zoo face_recognition_sface_2021dec.onnx, Apache 2.0, 128 numbers, RGB 0..255 in.  auraface  fal/AuraFace-v1 glintr100.onnx (that file only), Apache 2.0, 512 numbers, (x - 127.5) / 127.5 in.convert: each ONNX model to a Core ML program (fp16 weights, and 8-bit palettised weights), compiled to .mlmodelcfor the app's bundle, checked against onnxruntime on the same crops (cosine of the two vectors).bench: verification on every identity's 64 pictures at full size and with the face shrunk to 64, 48, 32 and 24 pxacross and brought back to 112 (what a small face in a photo gives the model): TAR at FAR 1e-3 over all genuine anda sample of impostor pairs, and rank-1 identification against a gallery of each person's first 5 pictures."""import argparseimport jsonimport randomimport sysimport timefrom pathlib import Pathimport numpy as npfrom PIL import ImageMODELS = {    "sface": dict(onnx="sface.onnx", scale=1.0, shift=0.0, file="SFace"),    "auraface": dict(onnx="auraface_glintr100.onnx", scale=1 / 127.5, shift=-1.0, file="AuraFace"),    # Idiap HyperFace-50k-StyleGAN (MIT weights; trained only on HyperFace's synthetic faces): AdaFace's IR-50, BGR in.    # `export-hyperface` writes its ONNX from the published checkpoint first.    "hyperface": dict(onnx="hyperface50k.onnx", scale=1 / 127.5, shift=-1.0, file="HyperFace50k", bgr=True),}def export_hyperface(models_dir):    """HuggingFace Idiap/HyperFace-50k-StyleGAN's Lightning checkpoint -> ONNX (the embedding, already unit length).    Needs AdaFace's net.py (MIT, github.com/mk-minchul/AdaFace) in <models>/adaface/."""    import torch    sys.path.insert(0, str(Path(models_dir) / "adaface"))    import net    ck = torch.load(str(Path(models_dir) / "hyperface50k.ckpt"), map_location="cpu", weights_only=False)    weights = {k[len("model."):]: v for k, v in ck["state_dict"].items() if k.startswith("model.")}    backbone = net.build_model("ir_50")    backbone.load_state_dict(weights)    backbone.eval()    class Embedding(torch.nn.Module):        def __init__(self, b):            super().__init__()            self.b = b        def forward(self, x):            return self.b(x)[0]    torch.onnx.export(Embedding(backbone), torch.zeros(1, 3, 112, 112), str(Path(models_dir) / "hyperface50k.onnx"),                      input_names=["face"], output_names=["vector"], dynamic_axes={"face": {0: "n"}, "vector": {0: "n"}},                      opset_version=17, dynamo=False)def prep(img, m):    """112 px RGB picture -> 1x3x112x112 float in the model's own scale."""    a = np.asarray(img.convert("RGB").resize((112, 112), Image.BICUBIC), np.float32)    if m.get("bgr"):        a = a[:, :, ::-1]    a = a * m["scale"] + m["shift"]    return np.ascontiguousarray(a.transpose(2, 0, 1)[None])def shrink(img, px):    if px >= 112:        return img    return img.resize((px, px), Image.BILINEAR).resize((112, 112), Image.BICUBIC)def convert(models_dir, out_dir):    import coremltools as ct    import onnx    import onnxruntime as ort    import torch    from coremltools.optimize.coreml import OpPalettizerConfig, OptimizationConfig, palettize_weights    from onnx2torch import convert as to_torch    out = Path(out_dir)    out.mkdir(parents=True, exist_ok=True)    report = {}    sample = np.random.default_rng(0).uniform(0, 255, (1, 3, 112, 112)).astype(np.float32)    for name, m in MODELS.items():        path = Path(models_dir) / m["onnx"]        model = onnx.load(str(path))        net = to_torch(model).eval()        x = torch.from_numpy(sample * m["scale"] + m["shift"])        traced = torch.jit.trace(net, x)        for kind in ("fp16", "pal8"):            ml = ct.convert(traced, inputs=[ct.TensorType(name="face", shape=(1, 3, 112, 112))],                            outputs=[ct.TensorType(name="vector")], convert_to="mlprogram",                            compute_precision=ct.precision.FLOAT16, minimum_deployment_target=ct.target.iOS18)            if kind == "pal8":                ml = palettize_weights(ml, OptimizationConfig(global_config=OpPalettizerConfig(mode="kmeans", nbits=8)))            package = out / f"{m['file']}-{kind}.mlpackage"            ml.save(str(package))            # Agreement with the ONNX original on random and real-looking input.            session = ort.InferenceSession(str(path))            want = session.run(None, {session.get_inputs()[0].name: x.numpy()})[0][0]            got = ml.predict({"face": x.numpy()})["vector"].reshape(-1)            cos = float(np.dot(want, got) / (np.linalg.norm(want) * np.linalg.norm(got)))            size = sum(f.stat().st_size for f in package.rglob("*") if f.is_file())            report[f"{name}-{kind}"] = dict(cosine_vs_onnx=round(cos, 5), bytes=size)            print(name, kind, report[f"{name}-{kind}"], flush=True)    known = json.loads((out / "convert.json").read_text()) if (out / "convert.json").exists() else {}    (out / "convert.json").write_text(json.dumps({**known, **report}, indent=2))def embed_all(session, m, pictures):    name = session.get_inputs()[0].name    out = []    for i in range(0, len(pictures), 64):        batch = np.concatenate([prep(p, m) for p in pictures[i:i + 64]])        try:            v = session.run(None, {name: batch})[0]        except Exception:            v = np.concatenate([session.run(None, {name: b[None]})[0] for b in batch])        out.append(v)    v = np.concatenate(out).reshape(len(pictures), -1)    return v / np.linalg.norm(v, axis=1, keepdims=True)def bench(models_dir, faces_dir, people, out):    import onnxruntime as ort    rng = random.Random(0)    ids = sorted(p for p in Path(faces_dir).iterdir() if p.is_dir() and len(list(p.iterdir())) >= 64)[:people]    pictures, labels = [], []    for n, d in enumerate(ids):        for f in sorted(d.iterdir(), key=lambda p: int(p.stem) if p.stem.isdigit() else 0)[:64]:            pictures.append(Image.open(f).convert("RGB"))            labels.append(n)    labels = np.array(labels)    results = {}    for name, m in MODELS.items():        session = ort.InferenceSession(str(Path(models_dir) / m["onnx"]), providers=["CPUExecutionProvider"])        for px in (112, 64, 48, 32, 24):            started = time.time()            v = embed_all(session, m, [shrink(p, px) for p in pictures])            per_face = (time.time() - started) / len(pictures) * 1000            sims = v @ v.T            same = labels[:, None] == labels[None, :]            iu = np.triu_indices(len(labels), 1)            genuine = sims[iu][same[iu]]            impostor = sims[iu][~same[iu]]            impostor = np.random.default_rng(1).choice(impostor, size=min(len(impostor), 2_000_000), replace=False)            threshold = np.quantile(impostor, 1 - 1e-3)            tar = float((genuine > threshold).mean())            # Rank-1: gallery = each person's first 5 pictures (their mean), probes = the rest.            gallery = np.stack([v[labels == k][:5].mean(0) for k in range(len(ids))])            gallery /= np.linalg.norm(gallery, axis=1, keepdims=True)            probes = np.concatenate([np.where(labels == k)[0][5:] for k in range(len(ids))])            rank1 = float((np.argmax(v[probes] @ gallery.T, axis=1) == labels[probes]).mean())            results[f"{name}@{px}"] = dict(tar_at_far_1e3=round(tar, 4), threshold=round(float(threshold), 4),                                           rank1=round(rank1, 4), mac_cpu_ms_per_face=round(per_face, 2))            print(name, px, results[f"{name}@{px}"], flush=True)    results["_"] = dict(people=len(ids), pictures=len(pictures), genuine_pairs=int(len(genuine)))    Path(out).write_text(json.dumps(results, indent=2))def main():    ap = argparse.ArgumentParser()    ap.add_argument("what", choices=["convert", "bench", "export-hyperface"])    ap.add_argument("--only", help="comma-separated model names")    ap.add_argument("--models", required=True)    ap.add_argument("--out")    ap.add_argument("--faces")    ap.add_argument("--people", type=int, default=200)    a = ap.parse_args()    if a.only:        for name in list(MODELS):            if name not in a.only.split(","):                del MODELS[name]    if a.what == "export-hyperface":        export_hyperface(a.models)    elif a.what == "convert":        convert(a.models, a.out)    else:        bench(a.models, a.faces, a.people, a.out or "bench.json")if __name__ == "__main__":    sys.exit(main())