Cotton code
829 lines · 37.9 KB · PythonRaw
#!/usr/bin/env python3"""Cotton Albums' face models to LiteRT (.tflite), with no TensorFlow: OpenCV Zoo's ONNX (YuNet, SFace) and HyperFace-50kfrom the iPhone's own pinned Core ML archive (its MIL program and weight blobs read as they are).The two models are small, plain graphs, so this writes the LiteRT flatbuffer itself from the ONNX weights:  SFace  face_recognition_sface_2021dec.onnx (Apache 2.0): 112x112 RGB 0..255 in, 128 numbers out.         Batch norms are folded into the convolutions and the last two into the dense layer; the weights are         kept as float16 and computed in float32 (a DEQUANTIZE in front of each, run once at load).  YuNet  face_detection_yunet_2023mar.onnx (MIT): fixed square input (default 160), BGR 0..255 in, the 12 heads         out (cls, obj, bbox, kps at strides 8, 16, 32), each [1, cells, k] as in ONNX. Weights float32 (0.3 MB).ONNX is NCHW, LiteRT NHWC: weights are transposed, ONNX's symmetric stride-2 padding becomes an explicit PAD (TF'sSAME pads the other side), and YuNet's Transpose+Reshape heads become one Reshape.Needs: onnx, numpy, flatbuffers, tflite (the schema's Python classes). Check with onnxruntime and ai-edge-litert:    python -I convert.py sface <in.onnx> <out.tflite>    python -I convert.py yunet <in.onnx> <out.tflite> [side]    python -I convert.py check-sface <in.onnx> <out.tflite>    python -I convert.py check-yunet <in.onnx> <out.tflite> [side]    python -I convert.py hyperface <HyperFace50k-pal8.mlmodelc.tar> <out.tflite>       (scripts/albums/face-model-android.sh)    python -I convert.py check-hyperface <archive> <out.tflite> <112px crops...>      (needs coremltools, ai-edge-litert, pillow)    python -I convert.py vectors-hyperface <archive> <yunet.tflite> <align dir> <SFHQ faces...>   (writes hyperface.json)"""import sysimport flatbuffersimport numpy as npimport tflitefrom tflite import (BuiltinOperator as BO, BuiltinOptions as BOpt, TensorType as TT, Padding,                    ActivationFunctionType as Act)class Writer:    """A LiteRT model of one subgraph, written straight into the schema."""    def __init__(self):        self.buffers = [b""]  # buffer 0 is the empty one        self.tensors = []     # (name, shape, type, buffer)        self.ops = []         # (opcode index, inputs, outputs, options type, options builder fn)        self.codes = []       # (builtin, version)        self.inputs = []        self.outputs = []    def tensor(self, name, shape, ttype=TT.FLOAT32, data=None):        buf = 0        if data is not None:            self.buffers.append(np.ascontiguousarray(data).tobytes())            buf = len(self.buffers) - 1        self.tensors.append((name, list(int(s) for s in shape), ttype, buf))        return len(self.tensors) - 1    def const(self, name, array, half=False):        """A constant float tensor; with half, kept float16 behind a DEQUANTIZE."""        array = np.asarray(array, dtype=np.float32)        if not half:            return self.tensor(name, array.shape, TT.FLOAT32, array)        h = self.tensor(name + "_f16", array.shape, TT.FLOAT16, array.astype(np.float16))        f = self.tensor(name, array.shape)        self.op(BO.DEQUANTIZE, [h], [f], version=3)        return f    def ints(self, name, values):        a = np.asarray(values, dtype=np.int32)        return self.tensor(name, a.shape, TT.INT32, a)    def code(self, builtin, version):        key = (builtin, version)        if key not in self.codes:            self.codes.append(key)        return self.codes.index(key)    def op(self, builtin, ins, outs, options=None, opts_type=0, version=1):        self.ops.append((self.code(builtin, version), ins, outs, opts_type, options))    def build(self, description="cotton albums"):        b = flatbuffers.Builder(1 << 20)        def ivec(start, values):            start(b, len(values))            for v in reversed(values):                b.PrependInt32(v)            return b.EndVector()        # Buffers: data first (vectors), then tables.        datas = []        for raw in self.buffers:            if raw:                b.StartVector(1, len(raw), 16)                b.head = b.head - len(raw)                b.Bytes[b.head:b.head + len(raw)] = raw                datas.append(b.EndVector())            else:                datas.append(None)        bufs = []        for d in datas:            tflite.BufferStart(b)            if d is not None:                tflite.BufferAddData(b, d)            bufs.append(tflite.BufferEnd(b))        tens = []        for name, shape, ttype, buf in self.tensors:            n = b.CreateString(name)            s = ivec(tflite.TensorStartShapeVector, shape)            tflite.TensorStart(b)            tflite.TensorAddShape(b, s)            tflite.TensorAddType(b, ttype)            tflite.TensorAddBuffer(b, buf)            tflite.TensorAddName(b, n)            tens.append(tflite.TensorEnd(b))        ops = []        for code, ins, outs, opts_type, options in self.ops:            o = options(b) if options else None            iv = ivec(tflite.OperatorStartInputsVector, ins)            ov = ivec(tflite.OperatorStartOutputsVector, outs)            tflite.OperatorStart(b)            tflite.OperatorAddOpcodeIndex(b, code)            tflite.OperatorAddInputs(b, iv)            tflite.OperatorAddOutputs(b, ov)            if o is not None:                tflite.OperatorAddBuiltinOptionsType(b, opts_type)                tflite.OperatorAddBuiltinOptions(b, o)            ops.append(tflite.OperatorEnd(b))        def tvec(start, items):            start(b, len(items))            for t in reversed(items):                b.PrependUOffsetTRelative(t)            return b.EndVector()        tv = tvec(tflite.SubGraphStartTensorsVector, tens)        opv = tvec(tflite.SubGraphStartOperatorsVector, ops)        iv = ivec(tflite.SubGraphStartInputsVector, self.inputs)        ov = ivec(tflite.SubGraphStartOutputsVector, self.outputs)        name = b.CreateString("main")        tflite.SubGraphStart(b)        tflite.SubGraphAddTensors(b, tv)        tflite.SubGraphAddOperators(b, opv)        tflite.SubGraphAddInputs(b, iv)        tflite.SubGraphAddOutputs(b, ov)        tflite.SubGraphAddName(b, name)        sg = tflite.SubGraphEnd(b)        codes = []        for builtin, version in self.codes:            tflite.OperatorCodeStart(b)            tflite.OperatorCodeAddDeprecatedBuiltinCode(b, min(builtin, 127))            tflite.OperatorCodeAddBuiltinCode(b, builtin)            tflite.OperatorCodeAddVersion(b, version)            codes.append(tflite.OperatorCodeEnd(b))        cv = tvec(tflite.ModelStartOperatorCodesVector, codes)        sgv = tvec(tflite.ModelStartSubgraphsVector, [sg])        bv = tvec(tflite.ModelStartBuffersVector, bufs)        desc = b.CreateString(description)        tflite.ModelStart(b)        tflite.ModelAddVersion(b, 3)        tflite.ModelAddOperatorCodes(b, cv)        tflite.ModelAddSubgraphs(b, sgv)        tflite.ModelAddDescription(b, desc)        tflite.ModelAddBuffers(b, bv)        m = tflite.ModelEnd(b)        b.Finish(m, file_identifier=b"TFL3")        return bytes(b.Output())    # ---- ops ----    def conv(self, x, w_oihw, bias, stride, pad, group, shape_in, act=Act.NONE, half=False, name="conv"):        """ONNX Conv (pads symmetric) on an NHWC tensor of shape_in [1,H,W,C]; returns (tensor, shape)."""        o, i, kh, kw = w_oihw.shape        _, h, wd, c = shape_in        if pad and not (stride == 1 and kh == 2 * pad + 1):            padded = [1, h + 2 * pad, wd + 2 * pad, c]            p = self.tensor(name + "_pad", padded)            self.op(BO.PAD, [x, self.ints(name + "_pads", [[0, 0], [pad, pad], [pad, pad], [0, 0]])], [p])            x, h, wd, padding = p, h + 2 * pad, wd + 2 * pad, Padding.VALID            oh, ow = (h - kh) // stride + 1, (wd - kw) // stride + 1        elif pad:            padding = Padding.SAME            oh, ow = h, wd        else:            padding = Padding.VALID            oh, ow = (h - kh) // stride + 1, (wd - kw) // stride + 1        depthwise = group > 1        if depthwise:            assert group == c == o and i == 1, (group, c, o, i)            wt = self.const(name + "_w", w_oihw.transpose(1, 2, 3, 0), half)  # [1, kh, kw, O]        else:            assert group == 1            wt = self.const(name + "_w", w_oihw.transpose(0, 2, 3, 1), half)  # [O, kh, kw, I]        bt = self.const(name + "_b", bias if bias is not None else np.zeros(o, np.float32))        out_shape = [1, oh, ow, o]        y = self.tensor(name, out_shape)        def opts(b):            if depthwise:                tflite.DepthwiseConv2DOptionsStart(b)                tflite.DepthwiseConv2DOptionsAddPadding(b, padding)                tflite.DepthwiseConv2DOptionsAddStrideW(b, stride)                tflite.DepthwiseConv2DOptionsAddStrideH(b, stride)                tflite.DepthwiseConv2DOptionsAddDepthMultiplier(b, 1)                tflite.DepthwiseConv2DOptionsAddFusedActivationFunction(b, act)                tflite.DepthwiseConv2DOptionsAddDilationWFactor(b, 1)                tflite.DepthwiseConv2DOptionsAddDilationHFactor(b, 1)                return tflite.DepthwiseConv2DOptionsEnd(b)            tflite.Conv2DOptionsStart(b)            tflite.Conv2DOptionsAddPadding(b, padding)            tflite.Conv2DOptionsAddStrideW(b, stride)            tflite.Conv2DOptionsAddStrideH(b, stride)            tflite.Conv2DOptionsAddFusedActivationFunction(b, act)            tflite.Conv2DOptionsAddDilationWFactor(b, 1)            tflite.Conv2DOptionsAddDilationHFactor(b, 1)            return tflite.Conv2DOptionsEnd(b)        if depthwise:            self.op(BO.DEPTHWISE_CONV_2D, [x, wt, bt], [y], opts, BOpt.DepthwiseConv2DOptions)        else:            self.op(BO.CONV_2D, [x, wt, bt], [y], opts, BOpt.Conv2DOptions)        return y, out_shape    def reshape(self, x, shape, name):        y = self.tensor(name, shape)        s = self.ints(name + "_shape", shape)        def opts(b):            tflite.ReshapeOptionsStartNewShapeVector(b, len(shape))            for v in reversed(shape):                b.PrependInt32(v)            ns = b.EndVector()            tflite.ReshapeOptionsStart(b)            tflite.ReshapeOptionsAddNewShape(b, ns)            return tflite.ReshapeOptionsEnd(b)        self.op(BO.RESHAPE, [x, s], [y], opts, BOpt.ReshapeOptions)        return y    def binary(self, kind, a, c, shape, name):        y = self.tensor(name, shape)        start, end, add_act, ot = {            BO.ADD: (tflite.AddOptionsStart, tflite.AddOptionsEnd, tflite.AddOptionsAddFusedActivationFunction, BOpt.AddOptions),            BO.SUB: (tflite.SubOptionsStart, tflite.SubOptionsEnd, tflite.SubOptionsAddFusedActivationFunction, BOpt.SubOptions),            BO.MUL: (tflite.MulOptionsStart, tflite.MulOptionsEnd, tflite.MulOptionsAddFusedActivationFunction, BOpt.MulOptions),        }[kind]        def opts(b):            start(b)            add_act(b, Act.NONE)            return end(b)        self.op(kind, [a, c], [y], opts, ot)        return ydef onnx_parts(path):    import onnx    from onnx import numpy_helper    m = onnx.load(path)    init = {t.name: numpy_helper.to_array(t).astype(np.float32) for t in m.graph.initializer}    attrs = lambda n: {a.name: onnx.helper.get_attribute_value(a) for a in n.attribute}    return m.graph, init, attrsdef fold_bn(init, bn, eps):    g, beta, mean, var = (init[i] for i in bn.input[1:5])    s = g / np.sqrt(var + eps)    return s, beta - mean * sdef convert_sface(src, dst):    graph, init, attrs = onnx_parts(src)    nodes = list(graph.node)    w = Writer()    x = w.tensor("data", [1, 112, 112, 3])    w.inputs = [x]    shape = [1, 112, 112, 3]    i = 0    # Sub and Mul by scalars: kept as ops (RGB 0..255 in, as OpenCV feeds it).    assert nodes[0].op_type == "Sub" and nodes[1].op_type == "Mul"    sub = w.const("sub_k", init[nodes[0].input[1]].reshape([]))    x = w.binary(BO.SUB, x, sub, shape, "sub")    mul = w.const("mul_k", init[nodes[1].input[1]].reshape([]))    x = w.binary(BO.MUL, x, mul, shape, "mul")    i = 2    n_conv = 0    while nodes[i].op_type == "Conv":        c, bn, pr = nodes[i], nodes[i + 1], nodes[i + 2]        assert bn.op_type == "BatchNormalization" and pr.op_type == "PRelu", (bn.op_type, pr.op_type)        a = attrs(c)        wt = init[c.input[1]]        bias = init[c.input[2]] if len(c.input) > 2 else np.zeros(wt.shape[0], np.float32)        s, t = fold_bn(init, bn, attrs(bn).get("epsilon", 1e-5))        wt = wt * s[:, None, None, None]        bias = bias * s + t        stride = a["strides"][0]        pad = a["pads"][0]        assert len(set(a["pads"])) == 1 and a["strides"][0] == a["strides"][1]        x, shape = w.conv(x, wt, bias, stride, pad, a.get("group", 1), shape, half=True, name=f"conv{n_conv}")        alpha = init[pr.input[1]].reshape(1, 1, -1)        al = w.const(f"prelu{n_conv}_a", alpha)        y = w.tensor(f"prelu{n_conv}", shape)        w.op(BO.PRELU, [x, al], [y])        x = y        n_conv += 1        i += 3    # bn1 (over 1024 channels at 7x7), dropout, flatten (NCHW order), gemm, fc1 bn.    bn1, drop, flat, gemm, fc1 = nodes[i:i + 5]    assert [n.op_type for n in nodes[i:i + 5]] == ["BatchNormalization", "Dropout", "Flatten", "Gemm", "BatchNormalization"]    s1, t1 = fold_bn(init, bn1, attrs(bn1)["epsilon"])    _, h, wd, c = shape    W = init[gemm.input[1]]  # [128, C*H*W] in NCHW flatten order    b = init[gemm.input[2]]    W4 = W.reshape(-1, c, h, wd)    b = b + np.einsum("ochw,c->o", W4, t1)    W4 = W4 * s1[None, :, None, None]    Wn = W4.transpose(0, 2, 3, 1).reshape(W.shape[0], -1)  # NHWC flatten order    s2, t2 = fold_bn(init, fc1, attrs(fc1)["epsilon"])    Wn = Wn * s2[:, None]    b = b * s2 + t2    flat_t = w.reshape(x, [1, h * wd * c], "flatten")    wt = w.const("fc_w", Wn, half=True)    bt = w.const("fc_b", b)    out = w.tensor("fc1", [1, Wn.shape[0]])    def fc_opts(bb):        tflite.FullyConnectedOptionsStart(bb)        tflite.FullyConnectedOptionsAddFusedActivationFunction(bb, Act.NONE)        return tflite.FullyConnectedOptionsEnd(bb)    w.op(BO.FULLY_CONNECTED, [flat_t, wt, bt], [out], fc_opts, BOpt.FullyConnectedOptions)    w.outputs = [out]    open(dst, "wb").write(w.build("sface-2021dec-f16: OpenCV Zoo face_recognition_sface_2021dec (Apache 2.0), weights float16"))def convert_yunet(src, dst, side=160):    graph, init, attrs = onnx_parts(src)    w = Writer()    x = w.tensor("input", [1, side, side, 3])    w.inputs = [x]    env = {graph.input[0].name: (x, [1, side, side, 3])}    consts = dict(init)    pending_reshape = {}  # a Transpose(0,2,3,1) output: the NHWC tensor itself    for n in graph.node:        a = attrs(n)        op = n.op_type        name = n.output[0]        if op == "Conv":            t, shape = env[n.input[0]]            wt = consts[n.input[1]]            bias = consts[n.input[2]] if len(n.input) > 2 else None            pads = a.get("pads", [0, 0, 0, 0])            assert len(set(pads)) == 1, pads            y, s = w.conv(t, wt, bias, a.get("strides", [1, 1])[0], pads[0], a.get("group", 1), shape, name=name)            env[name] = (y, s)        elif op == "Relu":            t, shape = env[n.input[0]]            y = w.tensor(name, shape)            w.op(BO.RELU, [t], [y])            env[name] = (y, shape)        elif op == "Sigmoid":            t, shape = env[n.input[0]]            y = w.tensor(name, shape)            w.op(BO.LOGISTIC, [t], [y])            env[name] = (y, shape)        elif op == "MaxPool":            t, shape = env[n.input[0]]            k, st = a["kernel_shape"][0], a["strides"][0]            pads = a.get("pads", [0, 0, 0, 0])            assert pads[0] == 0 and len(set(pads)) == 1, pads            _, h, wd, c = shape            s = [1, (h - k) // st + 1, (wd - k) // st + 1, c]            y = w.tensor(name, s)            def opts(b, k=k, st=st):                tflite.Pool2DOptionsStart(b)                tflite.Pool2DOptionsAddPadding(b, Padding.VALID)                tflite.Pool2DOptionsAddStrideW(b, st)                tflite.Pool2DOptionsAddStrideH(b, st)                tflite.Pool2DOptionsAddFilterWidth(b, k)                tflite.Pool2DOptionsAddFilterHeight(b, k)                tflite.Pool2DOptionsAddFusedActivationFunction(b, Act.NONE)                return tflite.Pool2DOptionsEnd(b)            w.op(BO.MAX_POOL_2D, [t], [y], opts, BOpt.Pool2DOptions)            env[name] = (y, s)        elif op == "Resize":            t, shape = env[n.input[0]]            assert a.get("mode", b"nearest") in (b"nearest", "nearest"), a            _, h, wd, c = shape            s = [1, h * 2, wd * 2, c]            y = w.tensor(name, s)            size = w.ints(name + "_size", [h * 2, wd * 2])            def opts(b):                tflite.ResizeNearestNeighborOptionsStart(b)                tflite.ResizeNearestNeighborOptionsAddAlignCorners(b, False)                tflite.ResizeNearestNeighborOptionsAddHalfPixelCenters(b, False)                return tflite.ResizeNearestNeighborOptionsEnd(b)            w.op(BO.RESIZE_NEAREST_NEIGHBOR, [t, size], [y], opts, BOpt.ResizeNearestNeighborOptions)            env[name] = (y, s)        elif op == "Add":            (t1, s1), (t2, s2) = env[n.input[0]], env[n.input[1]]            assert s1 == s2            env[name] = (w.binary(BO.ADD, t1, t2, s1, name), s1)        elif op == "Transpose":            assert list(a["perm"]) == [0, 2, 3, 1], a            env[name] = env[n.input[0]]  # NHWC already            pending_reshape[name] = True        elif op == "Reshape":            assert n.input[0] in pending_reshape, n.input[0]            t, shape = env[n.input[0]]            _, h, wd, c = shape            env[name] = (w.reshape(t, [1, h * wd, c], name), [1, h * wd, c])        else:            raise SystemExit(f"yunet: no conversion for {op}")    out_names = [o.name for o in graph.output]    w.outputs = [env[o][0] for o in out_names]    open(dst, "wb").write(w.build(f"yunet-2023mar-{side}: OpenCV Zoo face_detection_yunet_2023mar (MIT), input {side}x{side} BGR 0..255"))# ---- HyperFace-50k: the iPhone's own pinned Core ML file, read as it is ----def read_mlmodelc(src):    """The pinned archive (a tar of the .mlmodelc) or its folder -> (ops, weight bytes). Each op is    (out_name, out_type, out_shape, op, args); an arg is a variable's name or a constant's value (numpy or python)."""    import io    import re    import tarfile    from pathlib import Path    files = {}    if str(src).endswith(".tar"):        with tarfile.open(src) as t:            for m in t.getmembers():                if m.isfile() and m.name.endswith(("model.mil", "weights/weight.bin")):                    files[m.name.rsplit("/", 2)[-1] if m.name.endswith(".mil") else "weight.bin"] = t.extractfile(m).read()    else:        files["model.mil"] = (Path(src) / "model.mil").read_bytes()        files["weight.bin"] = (Path(src) / "weights/weight.bin").read_bytes()    mil, blob = files["model.mil"].decode(), files["weight.bin"]    assert int.from_bytes(blob[4:8], "little") == 2, "weight.bin: not MIL blob storage version 2"    dtypes = {"fp16": np.float16, "fp32": np.float32, "uint8": np.uint8, "int8": np.int8, "int32": np.int32}    def blobfile(ttype, shape, offset):        # Each blob's 64-byte header: sentinel 0xDEADBEEF, dtype, size, then where its data starts.        assert int.from_bytes(blob[offset:offset + 4], "little") == 0xDEADBEEF, offset        size = int.from_bytes(blob[offset + 8:offset + 16], "little")        at = int.from_bytes(blob[offset + 16:offset + 24], "little")        a = np.frombuffer(blob[at:at + size], dtype=dtypes[ttype])        return a.reshape(shape).copy()    scalar = re.compile(r"^(fp16|fp32|int32|bool|string)\((.*)\)$")    tensor_lit = re.compile(r"^tensor<(\w+), \[([0-9, ]*)\]>\((.*)\)$")    blobref = re.compile(r"^BLOBFILE\(path = string\(\"[^\"]+\"\), offset = uint64\((\d+)\)\)$")    def value(text):        text = text.strip()        m = tensor_lit.match(text)        if m:            ttype, shape = m.group(1), [int(x) for x in m.group(2).split(",") if x.strip()]            inner = m.group(3)            b = blobref.match(inner)            if b:                return blobfile(ttype, shape, int(b.group(1)))            vals = [float.fromhex(v) if "0x" in v else float(v) for v in inner.strip("[]").split(",") if v.strip()]            return np.array(vals, dtype=dtypes[ttype]).reshape(shape)        m = scalar.match(text)        if m:            kind, v = m.groups()            if kind == "string":                return v.strip('"')            if kind == "bool":                return v == "true"            if kind == "int32":                return int(v)            return float.fromhex(v) if "0x" in v else float(v)        return text  # a variable's name    def split_args(text):        out, depth, cur = [], 0, ""        for ch in text:            if ch in "([<":                depth += 1            elif ch in ")]>":                depth -= 1            if ch == "," and depth == 0:                out.append(cur)                cur = ""            else:                cur += ch        if cur.strip():            out.append(cur)        return out    line_re = re.compile(r"^\s*(tensor<(\w+), \[([0-9, ]*)\]>|\w+) (\w+) = (\w+)\((.*)\)\[name = string\(\"[^\"]*\"\)(?:, val = (.*))?\];$")    consts, ops = {}, []    for line in mil.splitlines():        m = line_re.match(line)        if not m:            continue        _, ttype, shape, name, op, args, val = m.groups()        shape = [int(x) for x in shape.split(",")] if shape else []        if op == "const":            consts[name] = value(val)            continue        parsed = {}        for a in split_args(args):            k, v = a.split("=", 1)            v = value(v)            parsed[k.strip()] = consts.get(v, v) if isinstance(v, str) else v        if op == "constexpr_lut_to_dense":            lut = parsed["lut"].astype(np.float32).reshape(-1)            assert lut.size == 256, "only one palette of 256 per tensor is read"            consts[name] = lut[parsed["indices"].astype(np.int64)].reshape(shape)            continue        ops.append((name, ttype, shape, op, parsed))    return opsdef convert_hyperface(src, dst):    """HyperFace-50k (Idiap, MIT; AdaFace IR-50, 512 numbers) from the iPhone's pinned Core ML file to LiteRT, so both    phones run the same weights: the 8-bit palette expanded to the very float16 values Core ML computes with.    Input 1x112x112x3, channels BLUE, GREEN, RED, each (x - 127.5) / 127.5 (the align contract's model input), the    ArcFace-aligned crop. Output 1x512, NOT unit length (the phone divides by the length, as the Core ML model's last    two ops do). Weights float16 behind DEQUANTIZE, computed float32; batch norms in front of a padded convolution    stay as MUL and ADD (folding them into it would change the border), the two after the body go into the dense layer."""    ops = read_mlmodelc(src)    w = Writer()    x = w.tensor("face", [1, 112, 112, 3])    w.inputs = [x]    env = {"face": (x, [1, 112, 112, 3])}    n = 0    def fresh(base):        nonlocal n        n += 1        return f"{base}_{n}"    i = 0    while i < len(ops):        name, _, shape, op, a = ops[i]        if op == "conv":            t, s = env[a["x"]]            pads = list(a["pad"])            if a["pad_type"] == "valid":                pads = [0, 0, 0, 0]            assert a["pad_type"] in ("custom", "valid") and len(set(pads)) == 1 and a["groups"] == 1, (name, pads)            assert list(a["dilations"]) == [1, 1] and a["strides"][0] == a["strides"][1]            wt = np.asarray(a["weight"], np.float32)            bias = np.asarray(a["bias"], np.float32) if "bias" in a else None            y, ys = w.conv(t, wt, bias, int(a["strides"][0]), int(pads[0]), 1, s, half=True, name=fresh("conv"))            assert ys == [1, shape[2], shape[3], shape[1]], (name, ys, shape)            env[name] = (y, ys)        elif op == "prelu":            t, s = env[a["x"]]            al = w.const(fresh("prelu_a"), np.asarray(a["alpha"], np.float32).reshape(1, 1, -1))            y = w.tensor(fresh("prelu"), s)            w.op(BO.PRELU, [t, al], [y])            env[name] = (y, s)        elif op == "max_pool":            t, s = env[a["x"]]            k, st = list(a["kernel_sizes"]), list(a["strides"])            assert k == [1, 1] and list(a["pad"]) == [0, 0, 0, 0] and st[0] == st[1], (name, k, st)            if st[0] == 1:                env[name] = (t, s)            else:                ys = [1, (s[1] - 1) // st[0] + 1, (s[2] - 1) // st[0] + 1, s[3]]                y = w.tensor(fresh("pool"), ys)                def opts(b, st=st[0]):                    tflite.Pool2DOptionsStart(b)                    tflite.Pool2DOptionsAddPadding(b, Padding.VALID)                    tflite.Pool2DOptionsAddStrideW(b, st)                    tflite.Pool2DOptionsAddStrideH(b, st)                    tflite.Pool2DOptionsAddFilterWidth(b, 1)                    tflite.Pool2DOptionsAddFilterHeight(b, 1)                    tflite.Pool2DOptionsAddFusedActivationFunction(b, Act.NONE)                    return tflite.Pool2DOptionsEnd(b)                w.op(BO.MAX_POOL_2D, [t], [y], opts, BOpt.Pool2DOptions)                env[name] = (y, ys)        elif op == "add":            (t1, s1), (t2, s2) = env[a["x"]], env[a["y"]]            assert s1 == s2            env[name] = (w.binary(BO.ADD, t1, t2, s1, fresh("add")), s1)        elif op == "batch_norm" and ops[i + 1][3] != "reshape":            t, s = env[a["x"]]            sc = np.asarray(a["gamma"], np.float32) / np.sqrt(np.asarray(a["variance"], np.float32) + np.float32(a["epsilon"]))            sh = np.asarray(a["beta"], np.float32) - np.asarray(a["mean"], np.float32) * sc            y = w.binary(BO.MUL, t, w.const(fresh("bn_s"), sc), s, fresh("bn_mul"))            env[name] = (w.binary(BO.ADD, y, w.const(fresh("bn_t"), sh), s, fresh("bn_add")), s)        elif op == "batch_norm":            # The tail: batch norm 2d, flatten (NCHW order), linear, expand, batch norm 1d, squeeze, then unit length.            tail = [o[3] for o in ops[i:]]            assert tail == ["batch_norm", "reshape", "linear", "expand_dims", "batch_norm", "squeeze", "reduce_l2_norm", "real_div"], tail            t, s = env[a["x"]]            _, h, wd, c = s            s1 = np.asarray(a["gamma"], np.float32) / np.sqrt(np.asarray(a["variance"], np.float32) + np.float32(a["epsilon"]))            t1 = np.asarray(a["beta"], np.float32) - np.asarray(a["mean"], np.float32) * s1            lin = ops[i + 2][4]            W = np.asarray(lin["weight"], np.float32)  # [512, C*H*W], NCHW flatten order            b = np.asarray(lin["bias"], np.float32)            W4 = W.reshape(-1, c, h, wd)            b = b + np.einsum("ochw,c->o", W4, t1)            W4 = W4 * s1[None, :, None, None]            Wn = W4.transpose(0, 2, 3, 1).reshape(W.shape[0], -1)  # NHWC flatten order            bn = ops[i + 4][4]            s2 = np.asarray(bn["gamma"], np.float32) / np.sqrt(np.asarray(bn["variance"], np.float32) + np.float32(bn["epsilon"]))            t2 = np.asarray(bn["beta"], np.float32) - np.asarray(bn["mean"], np.float32) * s2            Wn = Wn * s2[:, None]            b = b * s2 + t2            flat = w.reshape(t, [1, h * wd * c], "flatten")            out = w.tensor("vector", [1, Wn.shape[0]])            def fc_opts(bb):                tflite.FullyConnectedOptionsStart(bb)                tflite.FullyConnectedOptionsAddFusedActivationFunction(bb, Act.NONE)                return tflite.FullyConnectedOptionsEnd(bb)            w.op(BO.FULLY_CONNECTED, [flat, w.const("fc_w", Wn, half=True), w.const("fc_b", b)], [out], fc_opts, BOpt.FullyConnectedOptions)            w.outputs = [out]            break        else:            raise SystemExit(f"hyperface: no conversion for {op} ({name})")        i += 1    open(dst, "wb").write(w.build("hyperface-50k-stylegan-pal8: Idiap HyperFace-50k-StyleGAN (MIT), from the pinned Core ML "                                  "HyperFace50k-pal8.mlmodelc; input 1x112x112x3 BGR (x-127.5)/127.5; output 1x512, not unit length"))def hyperface_input(rgb):    """112x112x3 RGB bytes -> the model's input: blue first, (x - 127.5) / 127.5 (the align contract)."""    a = np.asarray(rgb, np.float32)[:, :, ::-1]    return (a - 127.5) / 127.5def check_hyperface(src, dst, pictures):    """The LiteRT file against the pinned Core ML model itself (this Mac's Core ML, CPU only) on the given 112 px    crops: the cosine of each pair. Core ML computes in float16 here as on the iPhone; LiteRT in float32."""    import tarfile    import tempfile    from pathlib import Path    import coremltools as ct    from ai_edge_litert.interpreter import Interpreter, OpResolverType    from PIL import Image    tmp = tempfile.mkdtemp()    if str(src).endswith(".tar"):        with tarfile.open(src) as t:            t.extractall(tmp, filter="data")        src = next(Path(tmp).glob("*.mlmodelc"))    ml = ct.models.CompiledMLModel(str(src), compute_units=ct.ComputeUnit.CPU_ONLY)    it = None    if dst:        it = Interpreter(model_path=dst, experimental_op_resolver_type=OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES)        it.allocate_tensors()    worst, out = 1.0, {}    for p in pictures:        rgb = np.asarray(Image.open(p).convert("RGB"))        assert rgb.shape == (112, 112, 3), (p, rgb.shape)        x = hyperface_input(rgb)        want = ml.predict({"face": x.transpose(2, 0, 1)[None].astype(np.float32)})["vector"].reshape(-1).astype(np.float64)        if it is None:            out[Path(p).name] = (want / np.linalg.norm(want), None, None)            continue        it.set_tensor(it.get_input_details()[0]["index"], x[None])        it.invoke()        got = it.get_tensor(it.get_output_details()[0]["index"])[0].astype(np.float64)        cos = float(want @ got / np.linalg.norm(want) / np.linalg.norm(got))        worst = min(worst, cos)        out[Path(p).name] = (want / np.linalg.norm(want), got / np.linalg.norm(got), cos)        print(f"  {Path(p).name}: cosine {cos:.6f}")    if it is not None:        print(f"hyperface: worst cosine to Core ML {worst:.6f} over {len(pictures)} crops")    return outdef yunet_points(yunet, rgb):    """YuNet (160 px, the app's own file) on a whole square picture: the best face's five points in the picture's    pixel-index coordinates, in the contract's order. The same decoding as the phone's YuNet.decode."""    from ai_edge_litert.interpreter import Interpreter, OpResolverType    from PIL import Image    h, w, _ = rgb.shape    side = 160    it = Interpreter(model_path=yunet, experimental_op_resolver_type=OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES)    it.allocate_tensors()    small = np.asarray(Image.fromarray(rgb).resize((side, side), Image.BILINEAR), np.float32)[:, :, ::-1]    it.set_tensor(it.get_input_details()[0]["index"], small[None].copy())    it.invoke()    outs = {d["name"]: it.get_tensor(d["index"])[0] for d in it.get_output_details()}    best = None    for st in (8, 16, 32):        cols = side // st        cls, obj, kps = outs[f"cls_{st}"], outs[f"obj_{st}"], outs[f"kps_{st}"]        for i in range(cols * cols):            score = float(np.sqrt(np.clip(cls[i, 0], 0, 1) * np.clip(obj[i, 0], 0, 1)))            if best is None or score > best[0]:                r, c = divmod(i, cols)                pts = [(kps[i, n] + (c if n % 2 == 0 else r)) * st for n in range(10)]                best = (score, pts)    score, p = best    k = w / side    # YuNet's input pixel i is the picture's continuous (i + 0.5) * k: to the picture's pixel index.    pts = np.array([(p[n] + 0.5) * k - 0.5 for n in range(10)]).reshape(5, 2)    eyes = sorted(pts[:2].tolist())    mouth = sorted(pts[3:5].tolist())    return score, np.array(eyes + [pts[2].tolist()] + mouth)def vectors_hyperface(src, yunet, out_dir, faces):    """The agreement test's vectors (iPhone and Android, DECISIONS "Faces": the same crops on both phones within 1e-3    cosine): each synthetic face (SFHQ part 3, CC0) found by YuNet, cropped by the align contract (README.md beside    vectors.json) and saved as a 112 px PNG; then each crop, the contract's six expected crops too, through the    pinned Core ML model on this Mac. Writes hyperface.json: the model's sha256 and, per crop, its raw-RGB sha256 and    the unit vector."""    import hashlib    import importlib.util    import json    from pathlib import Path    from PIL import Image    here = Path(__file__).resolve().parent    spec = importlib.util.spec_from_file_location("align", here.parent / "albums-align-vectors.py")    align = importlib.util.module_from_spec(spec)    spec.loader.exec_module(align)    out = Path(out_dir)    template = np.array(align.TEMPLATE if hasattr(align, "TEMPLATE") else                        [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041]])    crops = sorted(str(p) for p in out.glob("*-crop.png"))    for f in faces:        rgb = np.asarray(Image.open(f).convert("RGB"))        score, pts = yunet_points(yunet, rgb)        assert score > 0.8, (f, score)        a, b, tx, ty = align.similarity(pts, template)        name = out / ("face-" + Path(f).stem + ".png")        Image.fromarray(align.crop(rgb.astype(np.float64), a, b, tx, ty)).save(name)        crops.append(str(name))    got = check_hyperface(src, None, crops)    cases = []    for p in crops:        rgb = np.asarray(Image.open(p).convert("RGB"))        want = got[Path(p).name][0]        cases.append({"crop": Path(p).name, "crop_rgb_sha256": hashlib.sha256(rgb.tobytes()).hexdigest(),                      "vector": [round(float(v), 7) for v in want]})    sha = hashlib.sha256(Path(src).read_bytes()).hexdigest()    (out / "hyperface.json").write_text(json.dumps({        "about": "HyperFace-50k's vectors for the two-phone agreement test (scripts/albums/convert.py vectors-hyperface): "                 "each crop through the pinned Core ML model (CPU, as computed in float16), unit length.",        "model": "hyperface-50k-stylegan-pal8", "model_sha256": sha,        "input": "the crop's RGB bytes, blue channel first, (x - 127.5) / 127.5",        "tolerance": {"cosine_min": 0.999, "why": "DECISIONS.md Testing, Faces: agreement within 1e-3 cosine"},        "cases": cases}, indent=1))    print(f"hyperface.json: {len(cases)} crops")def check_sface(src, dst):    import onnxruntime as ort    from ai_edge_litert.interpreter import Interpreter    sess = ort.InferenceSession(src)    it = Interpreter(model_path=dst, experimental_op_resolver_type=__import__("ai_edge_litert.interpreter", fromlist=["x"]).OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES)    it.allocate_tensors()    rng = np.random.default_rng(1)    worst = 0.0    for k in range(8):        img = rng.integers(0, 256, (112, 112, 3)).astype(np.float32)        if k % 2:  # smoother pictures, nearer a face's statistics            img = np.cumsum(np.cumsum(rng.normal(0, 4, (112, 112, 3)), 0), 1)            img = np.clip(img - img.min(), 0, 255).astype(np.float32)        ref = sess.run(None, {"data": img.transpose(2, 0, 1)[None]})[0][0]        it.set_tensor(it.get_input_details()[0]["index"], img[None])        it.invoke()        got = it.get_tensor(it.get_output_details()[0]["index"])[0]        cos = float(ref @ got / np.linalg.norm(ref) / np.linalg.norm(got))        worst = max(worst, 1 - cos)        print(f"  sample {k}: cosine {cos:.7f}  max abs {np.abs(ref - got).max():.5f}")    print(f"sface: worst cosine distance to onnxruntime fp32 {worst:.2e}")def check_yunet(src, dst, side=160):    import onnx    import onnxruntime as ort    from ai_edge_litert.interpreter import Interpreter, OpResolverType    from onnx import numpy_helper    # ONNX's own shapes are fixed at 640: make a copy with the side asked by rewriting the input and reshapes' targets.    m = onnx.load(src)    m.graph.input[0].type.tensor_type.shape.dim[2].dim_value = side    m.graph.input[0].type.tensor_type.shape.dim[3].dim_value = side    for o in m.graph.output:        for d in o.type.tensor_type.shape.dim:            d.dim_param = "x"    for init in m.graph.initializer:        arr = numpy_helper.to_array(init)        if arr.dtype == np.int64 and arr.shape == (3,) and arr[0] == 1:            init.CopyFrom(numpy_helper.from_array(np.array([1, -1, arr[2]], np.int64), init.name))    sess = ort.InferenceSession(m.SerializeToString())    it = Interpreter(model_path=dst, experimental_op_resolver_type=OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES)    it.allocate_tensors()    rng = np.random.default_rng(2)    img = np.clip(np.cumsum(np.cumsum(rng.normal(0, 3, (side, side, 3)), 0), 1), 0, 255).astype(np.float32)    ref = sess.run(None, {"input": img.transpose(2, 0, 1)[None]})    it.set_tensor(it.get_input_details()[0]["index"], img[None])    it.invoke()    outs = {d["name"]: it.get_tensor(d["index"]) for d in it.get_output_details()}    names = [o.name for o in m.graph.output]    worst = 0.0    for nm, r in zip(names, ref):        g = outs[nm]        assert g.shape == r.shape, (nm, g.shape, r.shape)        worst = max(worst, float(np.abs(g - r).max()))    print(f"yunet {side}: worst abs difference over the 12 heads {worst:.2e}")if __name__ == "__main__":    what = sys.argv[1]    if what == "sface":        convert_sface(sys.argv[2], sys.argv[3])    elif what == "yunet":        convert_yunet(sys.argv[2], sys.argv[3], int(sys.argv[4]) if len(sys.argv) > 4 else 160)    elif what == "check-sface":        check_sface(sys.argv[2], sys.argv[3])    elif what == "hyperface":        convert_hyperface(sys.argv[2], sys.argv[3])    elif what == "vectors-hyperface":        vectors_hyperface(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5:])    elif what == "check-hyperface":        check_hyperface(sys.argv[2], sys.argv[3], sys.argv[4:])    elif what == "check-yunet":        check_yunet(sys.argv[2], sys.argv[3], int(sys.argv[4]) if len(sys.argv) > 4 else 160)    else:        raise SystemExit(__doc__)