Modern Apps git

← Modern-Apps.git

library:ml: convert SCRFD 500m and MobileFaceNet to .vkml

Commit
0502e44409437374d470e330faf8f30051b77de8
Author
vayun-mathur <[email protected]>
When
2026-08-27 02:27 UTC (3 months ago)
Parents
c83bfe9

Diff

library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex 711c06adde..a8648b88f5 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -31,6 +31,10 @@ pub mod graph {     pub const SELFIE: u32 = 1;     /// U^2-Net portable, 320x320.     pub const U2NETP: u32 = 2;+    /// SCRFD 500M face detection, 640 on the long side.+    pub const SCRFD: u32 = 3;+    /// MobileFaceNet face embedding, 112x112 in, 512-d out.+    pub const MOBILEFACENET: u32 = 4; }  /// One tensor's entry in the table: where it is and what shape it is.
photos/src/main/assets/README.md
diff --git a/photos/src/main/assets/README.md b/photos/src/main/assets/README.mdindex 7d8c65ddf8..c5c4e1b04e 100644--- a/photos/src/main/assets/README.md+++ b/photos/src/main/assets/README.md@@ -23,12 +23,36 @@ upstream export is dynamic-shape; we keep the straight resize to 320×320 that t ncnn path already used, **not** the HuggingFace processor's `keep_aspect_ratio` letterbox, which would change existing behaviour. -## The ncnn face models+## The face models -`scrfd_500m_kps-opt2.{param,bin}` (face detection) and `w600k_mbf.ncnn.{param,bin}`-(face embedding) still run on ncnn, and are not covered here. `:library:ml`-implements only the two pure-CNN vision models; face detection and recognition are-a later phase.+`scrfd_500m.vkml` (face detection) and `w600k_mbf.vkml` (face embedding) are+InsightFace's **buffalo_s** pack, from+https://huggingface.co/immich-app/buffalo_s @ `0ff1751885575e62e084dff70549ce24a11fa5dc`:++| asset | source ONNX | SHA-256 |+|---|---|---|+| `scrfd_500m.vkml` | `detection/model.onnx`, 2,524,817 B | `5e4447f5…d8b4ea3a` |+| `w600k_mbf.vkml` | `recognition/model.onnx`, 13,616,099 B | `9cc6e4a7…b319eb4f` |++**Licence: InsightFace's own, which permits non-commercial research use only** —+https://github.com/deepinsight/insightface/tree/master/python-package#license. This is+*not* Apache-2.0 like the two models above, and it is the one licence constraint among+the bundled weights. These are the same weights the repo already shipped as+`scrfd_500m_kps-opt2.{param,bin}` and `w600k_mbf.ncnn.{param,bin}`, which arrived with+no upstream URL and no licence recorded at all; re-sourcing them from a licensed ONNX+export makes the constraint visible rather than introducing it.++SCRFD runs at 640 on the long side with the short side padded to a multiple of 32, so+its `.vkml` is the only one whose graph is dynamically shaped. MobileFaceNet runs at a+fixed 112×112 and returns a 512-d embedding.++Two nodes are rewritten during conversion rather than needing a shader — see+`scripts/ml/vkml_convert.py`: MobileFaceNet's final `Gemm` becomes a `[512, 64, 7, 7]`+convolution kernel, and the `BatchNormalization` after it is folded into that layer's+weight and bias.++The ncnn `.param`/`.bin` files are still present and still what `FaceRecognizer.kt`+loads; they go once the Kotlin moves across to `:library:ml`.  ## `clip/` 
photos/src/main/assets/scrfd_500m.vkml
diff --git a/photos/src/main/assets/scrfd_500m.vkml b/photos/src/main/assets/scrfd_500m.vkmlnew file mode 100644index 0000000000..a99004a647Binary files /dev/null and b/photos/src/main/assets/scrfd_500m.vkml differ
photos/src/main/assets/w600k_mbf.vkml
diff --git a/photos/src/main/assets/w600k_mbf.vkml b/photos/src/main/assets/w600k_mbf.vkmlnew file mode 100644index 0000000000..330209f9bcBinary files /dev/null and b/photos/src/main/assets/w600k_mbf.vkml differ
scripts/ml/fetch_and_convert.sh
diff --git a/scripts/ml/fetch_and_convert.sh b/scripts/ml/fetch_and_convert.shindex be56955b12..7436ee2134 100644--- a/scripts/ml/fetch_and_convert.sh+++ b/scripts/ml/fetch_and_convert.sh@@ -1,15 +1,23 @@ #!/usr/bin/env bash #-# Refresh the bundled `.vkml` weights that `:library:ml` runs, from the Apache-2.0-# ONNX exports they are converted from.+# Refresh the bundled `.vkml` weights that `:library:ml` runs, from the ONNX exports+# they are converted from. # #   camera/src/main/assets/selfie_segmentation.vkml   MediaPipe Selfie Segmentation #   photos/src/main/assets/u2netp.vkml                U^2-Net portable (saliency)+#   photos/src/main/assets/scrfd_500m.vkml            SCRFD 500M (face detection)+#   photos/src/main/assets/w600k_mbf.vkml             MobileFaceNet (face embedding) #-# Neither ONNX is vendored: it is 2x the size of the fp16 `.vkml` we actually ship-# and nothing reads it at run time. So this is the only record of where the weights-# came from, alongside the README.md next to each asset and the source ONNX SHA-256-# baked into each `.vkml` header.+# The first two are Apache-2.0. The two face models are InsightFace's buffalo_s pack+# under InsightFace's own licence, which permits **non-commercial research use only** —+# see photos/src/main/assets/README.md. They are the same weights the repo already+# shipped as ncnn `.param`/`.bin`, re-sourced from a licensed ONNX export so the+# provenance is recorded rather than absent.+#+# No ONNX is vendored: it is 2x the size of the fp16 `.vkml` we actually ship and+# nothing reads it at run time. So this is the only record of where the weights came+# from, alongside the README.md next to each asset and the source ONNX SHA-256 baked+# into each `.vkml` header. # # The conversion is deliberately not a graph import. `:library:ml` hardcodes each # forward pass in Rust, so `.vkml` carries ordered tensors and nothing else, and@@ -31,6 +39,8 @@ set -euo pipefail MODELS=(   "camera/src/main/assets/selfie_segmentation.vkml selfie 3241ac4ad8aa35bdaf33946776db29f7c283a413aa0b0dacb9483594b4531aad https://huggingface.co/onnx-community/mediapipe_selfie_segmentation/resolve/be49485c8e027524be38591817fc5cd31bd9d00e/onnx/model.onnx"   "photos/src/main/assets/u2netp.vkml             u2netp 309c8469258dda742793dce0ebea8e6dd393174f89934733ecc8b14c76f4ddd8 https://huggingface.co/BritishWerewolf/U-2-Netp/resolve/7112208dbac3a3642496c8d54e2f0f9bb3dc1dc8/onnx/model.onnx"+  "photos/src/main/assets/scrfd_500m.vkml         scrfd  5e4447f50245bbd7966bd6c0fa52938c61474a04ec7def48753668a9d8b4ea3a https://huggingface.co/immich-app/buffalo_s/resolve/0ff1751885575e62e084dff70549ce24a11fa5dc/detection/model.onnx"+  "photos/src/main/assets/w600k_mbf.vkml          mobilefacenet 9cc6e4a75f0e2bf0b1aed94578f144d15175f357bdc05e815e5c4a02b319eb4f https://huggingface.co/immich-app/buffalo_s/resolve/0ff1751885575e62e084dff70549ce24a11fa5dc/recognition/model.onnx" )  if [ ! -f settings.gradle.kts ]; then
scripts/ml/vkml_convert.py
diff --git a/scripts/ml/vkml_convert.py b/scripts/ml/vkml_convert.pyindex 03f3c29eaf..06889ea79e 100644--- a/scripts/ml/vkml_convert.py+++ b/scripts/ml/vkml_convert.py@@ -10,15 +10,30 @@ That makes tensor *order* the entire contract between this script and the Rust, and a reordering would be silently wrong rather than a load failure. So the order is defined mechanically and pinned: -* Order is `Conv`/`ConvTranspose` nodes in ONNX topological order, weight then-  bias. Nothing else is emitted — every other initializer in these two graphs is-  shape-computation scaffolding that folds away at a fixed input size.+* Order is the weighted nodes in ONNX **topological order** — `Conv`/`ConvTranspose`+  weight then bias, `PRelu` slope, `Gemm` weight then bias. Nothing else is emitted:+  every other initializer in these graphs is shape-computation scaffolding that folds+  away at a fixed input size.++  Topological rather than initializer order matters for the nets with `PRelu`: the Rust+  reads a layer as `weight = i, bias = i + 1, slope = i + 2`, which only lines up if a+  slope is emitted immediately after the convolution it follows. * `--check` hashes the whole ordered layer table (shapes *and* the attributes the   Rust hardcodes: dilation, pads, strides, group) into one SHA-256 pinned below.   Any upstream re-export that renames, reorders, retunes or re-pads a single layer   changes that hash and fails, instead of producing a file that loads and infers   nonsense. +Two nodes are rewritten rather than emitted verbatim, because doing it here means the+runtime needs no shader for either:++* A **`Gemm`** over a flattened NCHW map is a convolution whose kernel covers the whole+  spatial extent. MobileFaceNet's `[512, 3136]` becomes `[512, 64, 7, 7]` and the+  existing `conv.comp` computes it, so there is no `InnerProduct` pipeline.+* A trailing **`BatchNormalization`** is folded into the `Gemm` before it. At inference a+  batch norm is a per-channel affine, so `W' = W * gamma / sqrt(var + eps)` and+  `b' = (b - mean) * gamma / sqrt(var + eps) + beta` is exact, not an approximation.+ Weights are stored fp16 with fp32 accumulation in-shader (see `SPEC` below for the byte layout). ONNX tensor layout is preserved verbatim — `[M, C/group, kH, kW]` for `Conv`, `[C, M/group, kH, kW]` for `ConvTranspose` — so nothing here has to agree@@ -36,7 +51,7 @@ import sys  import numpy as np import onnx-from onnx import numpy_helper+from onnx import numpy_helper, shape_inference  # --- .vkml --------------------------------------------------------------------- #@@ -77,6 +92,8 @@ SPEC = __doc__ GRAPHS = {     "selfie": 1,     "u2netp": 2,+    "scrfd": 3,+    "mobilefacenet": 4, }  # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -84,14 +101,45 @@ GRAPHS = { EXPECTED_DIGEST = {     "selfie": "6db422ecfe0af8e37591eb14c195166b2c416649bf9063100bd5bb14eafaad3a",     "u2netp": "f5199e05e4d4e93a6af601d04e3e0516bb68b9f292bb81d474704ea0b4e591d0",+    "scrfd": "d2ce2880a432af03b0ef594029d3ab03d86de54bd0a9f10ea2c8e412309b0f46",+    "mobilefacenet": "40987839aec03378958581deba29ce9fd9dd1ae9aa88d0c7ad04a885a2e2122c", } -# What each graph is exported at. Both nets are fixed-shape by construction; the-# u2netp export is dynamic-shape and its Shape/Gather/Slice/Cast scaffolding only-# folds away at exactly this size, so it is asserted rather than assumed.+# What each graph is exported at, as `[channels, height, width]` after the batch+# dimension. `None` is a dimension the export leaves symbolic, which only SCRFD does:+# it runs at 640 on the long side and whatever the short side pads up to, so baking a+# size in would bake in one photo's aspect ratio.+#+# `outputs` are the graph outputs the Rust forward pass corresponds to; the export may+# declare more (U^2-Netp declares all seven of its side outputs and we read one). GEOMETRY = {-    "selfie": {"input": "pixel_values", "output": "alphas", "size": 256},-    "u2netp": {"input": "input.1", "output": "1959", "size": 320},+    "selfie": {+        "input": "pixel_values",+        "outputs": ["alphas"],+        "shape": [3, 256, 256],+    },+    "u2netp": {+        "input": "input.1",+        "outputs": ["1959"],+        "shape": [3, 320, 320],+    },+    # Nine: score, box and keypoint maps at strides 8, 16 and 32. The Rust reads the+    # convolution outputs feeding these rather than the reshaped tensors themselves,+    # because a Transpose/Reshape is a relabelling that NCHW indexing does for free.+    "scrfd": {+        "input": "input.1",+        "outputs": [+            "443", "468", "493",+            "446", "471", "496",+            "449", "474", "499",+        ],+        "shape": [3, None, None],+    },+    "mobilefacenet": {+        "input": "input.1",+        "outputs": ["516"],+        "shape": [3, 112, 112],+    }, }  # Op-type counts, as a coarse first check that the graph is the one we lowered by@@ -107,63 +155,213 @@ EXPECTED_OPS = {         "Relu": 112, "Sigmoid": 7, "Shape": 114, "Gather": 76, "Unsqueeze": 76,         "Slice": 38, "Cast": 38, "Constant": 266,     },+    "scrfd": {+        "Conv": 60, "Relu": 41, "Sigmoid": 3, "Add": 4, "Resize": 2, "Concat": 2,+        "Reshape": 9, "Transpose": 9, "Shape": 6, "Gather": 4, "Unsqueeze": 4,+        "Slice": 2,+    },+    "mobilefacenet": {+        "Conv": 49, "PRelu": 34, "Add": 12, "BatchNormalization": 1, "Flatten": 1,+        "Gemm": 1,+    }, }   class Layer:-    """One `Conv`/`ConvTranspose`, as the Rust forward pass needs to see it."""--    def __init__(self, index, node, weight, bias):-        attrs = {a.name: a for a in node.attribute}--        def ints(name, default):-            return list(attrs[name].ints) if name in attrs else list(default)+    """One weighted node, as the Rust forward pass needs to see it.""" +    def __init__(self, index, op, name, key, first_tensor, tensor_count):         self.index = index-        self.op = node.op_type-        self.name = node.output[0]-        self.weight_shape = list(weight.shape)-        self.bias_shape = list(bias.shape) if bias is not None else None-        self.kernel = ints("kernel_shape", weight.shape[2:])-        self.dilations = ints("dilations", (1, 1))-        # ONNX orders pads [top, left, bottom, right].-        self.pads = ints("pads", (0, 0, 0, 0))-        self.strides = ints("strides", (1, 1))-        self.group = attrs["group"].i if "group" in attrs else 1+        self.op = op+        self.name = name+        self._key = key+        # Where this layer's tensors start in the `.vkml` table, and how many it has.+        # The Rust indexes by tensor, and with `PRelu` in the mix that is no longer+        # `2 * layer` — so --print-layers reports it rather than leaving a transcriber+        # to count.+        self.first_tensor = first_tensor+        self.tensor_count = tensor_count      def key(self):         """Everything the Rust hardcodes about this layer, as a stable string."""-        return (-            f"{self.op} w={self.weight_shape} b={self.bias_shape} "-            f"k={self.kernel} d={self.dilations} p={self.pads} "-            f"s={self.strides} g={self.group}"-        )+        return self._key+++def convolution_key(node, weight, bias):+    """The digest key for a `Conv`/`ConvTranspose`. +    Byte-for-byte the string the first version of this script produced, so the pinned+    selfie and u2netp digests survive every later addition here.+    """+    attrs = {a.name: a for a in node.attribute} -def collect_layers(graph):-    """Conv/ConvTranspose in topological order, with their weight and bias."""+    def ints(name, default):+        return list(attrs[name].ints) if name in attrs else list(default)++    return (+        f"{node.op_type} w={list(weight.shape)} "+        f"b={list(bias.shape) if bias is not None else None} "+        f"k={ints('kernel_shape', weight.shape[2:])} "+        f"d={ints('dilations', (1, 1))} p={ints('pads', (0, 0, 0, 0))} "+        f"s={ints('strides', (1, 1))} "+        f"g={attrs['group'].i if 'group' in attrs else 1}"+    )+++def inferred_shapes(model):+    """Every tensor's shape, for the fixed-shape graphs. Empty where inference fails."""+    try:+        inferred = shape_inference.infer_shapes(model)+    except Exception:+        return {}+    everything = list(inferred.graph.value_info) + list(inferred.graph.input)+    return {+        vi.name: [d.dim_value for d in vi.type.tensor_type.shape.dim]+        for vi in everything+    }+++def flatten_source_shape(node, graph, shapes):+    """`[c, h, w]` of the map a `Gemm`'s flattened input came from.++    This is what lets a `Gemm` be emitted as a convolution kernel. It is read from the+    graph rather than assumed, because getting it wrong reshapes the fully-connected+    weight into the wrong kernel and produces a plausible-looking embedding.+    """+    producer = next((n for n in graph.node if node.input[0] in n.output), None)+    if producer is None or producer.op_type != "Flatten":+        raise SystemExit(+            f"{node.output[0]}: a Gemm whose input is not a Flatten. Only a Gemm over a "+            "flattened feature map can be emitted as a convolution."+        )+    shape = shapes.get(producer.input[0])+    if not shape or len(shape) != 4 or 0 in shape[1:]:+        raise SystemExit(+            f"{node.output[0]}: cannot infer the shape feeding {producer.output[0]}, "+            f"got {shape}. A Gemm can only be reshaped where the map's size is static."+        )+    return list(shape[1:])+++def fold_batch_norm(node, inits, weight, bias):+    """Fold a `BatchNormalization` into the weight and bias of the layer before it.++    At inference a batch norm is `gamma * (x - mean) / sqrt(var + eps) + beta`, a+    per-output-channel affine, so pushing it into the preceding layer is exact. Doing it+    here rather than in a shader is why the runtime has no batch-norm pipeline.+    """+    attrs = {a.name: a for a in node.attribute}+    epsilon = attrs["epsilon"].f if "epsilon" in attrs else 1e-5+    missing = [n for n in node.input[1:] if n not in inits]+    if missing:+        raise SystemExit(f"{node.output[0]}: batch norm parameter {missing} is computed")+    gamma = numpy_helper.to_array(inits[node.input[1]]).astype(np.float64)+    beta = numpy_helper.to_array(inits[node.input[2]]).astype(np.float64)+    mean = numpy_helper.to_array(inits[node.input[3]]).astype(np.float64)+    var = numpy_helper.to_array(inits[node.input[4]]).astype(np.float64)+    scale = gamma / np.sqrt(var + epsilon)+    # fp64 for the fold itself: the division by sqrt(var) can be large, and this is the+    # one place the file's values are computed rather than copied.+    folded_weight = weight.astype(np.float64) * scale.reshape([-1] + [1] * (weight.ndim - 1))+    folded_bias = (bias.astype(np.float64) - mean) * scale + beta+    return folded_weight, folded_bias+++def collect_layers(model):+    """The weighted nodes in topological order, with the tensors each contributes."""+    graph = model.graph     inits = {i.name: i for i in graph.initializer}+    shapes = inferred_shapes(model)+    array = lambda name: numpy_helper.to_array(inits[name])  # noqa: E731++    # Which node's output each BatchNormalization consumes, so the layer producing it+    # can absorb it.+    batch_norms = {n.input[0]: n for n in graph.node if n.op_type == "BatchNormalization"}+    folded = set()+     layers = []     tensors = []     for node in graph.node:-        if node.op_type not in ("Conv", "ConvTranspose"):-            continue-        missing = [n for n in node.input[1:] if n not in inits]-        if missing:-            raise SystemExit(-                f"{node.output[0]}: weight/bias {missing} is not an initializer. "-                "A computed weight means this is not the frozen export we lower."+        first_tensor = len(tensors)+        if node.op_type in ("Conv", "ConvTranspose"):+            missing = [n for n in node.input[1:] if n not in inits]+            if missing:+                raise SystemExit(+                    f"{node.output[0]}: weight/bias {missing} is not an initializer. "+                    "A computed weight means this is not the frozen export we lower."+                )+            weight = array(node.input[1])+            bias = array(node.input[2]) if len(node.input) > 2 else None+            if bias is None:+                raise SystemExit(+                    f"{node.output[0]}: no bias. The shaders always add one, so a "+                    "bias-less layer would need a zero tensor synthesised here."+                )+            key = convolution_key(node, weight, bias)+            tensors.append(weight)+            tensors.append(bias)+        elif node.op_type == "PRelu":+            if node.input[1] not in inits:+                raise SystemExit(f"{node.output[0]}: a computed PRelu slope")+            slope = array(node.input[1])+            key = f"PRelu s={list(slope.shape)}"+            tensors.append(slope)+        elif node.op_type == "Gemm":+            attrs = {a.name: a for a in node.attribute}+            alpha = attrs["alpha"].f if "alpha" in attrs else 1.0+            beta = attrs["beta"].f if "beta" in attrs else 1.0+            trans_a = attrs["transA"].i if "transA" in attrs else 0+            trans_b = attrs["transB"].i if "transB" in attrs else 0+            if (alpha, beta, trans_a, trans_b) != (1.0, 1.0, 0, 1):+                raise SystemExit(+                    f"{node.output[0]}: Gemm alpha={alpha} beta={beta} transA={trans_a} "+                    f"transB={trans_b}; only the plain `x @ W.T + b` form is lowered."+                )+            missing = [n for n in node.input[1:] if n not in inits]+            if missing:+                raise SystemExit(f"{node.output[0]}: Gemm operand {missing} is computed")+            weight = array(node.input[1])+            bias = array(node.input[2])+            batch_norm = batch_norms.get(node.output[0])+            if batch_norm is not None:+                weight, bias = fold_batch_norm(batch_norm, inits, weight, bias)+                folded.add(batch_norm.output[0])+            spatial = flatten_source_shape(node, graph, shapes)+            expected = int(np.prod(spatial))+            if weight.shape[1] != expected:+                raise SystemExit(+                    f"{node.output[0]}: Gemm weight is {list(weight.shape)} but its input "+                    f"flattens {spatial} = {expected} values"+                )+            weight = weight.reshape([weight.shape[0]] + spatial)+            key = (+                f"Gemm w={list(weight.shape)} b={list(bias.shape)} "+                f"bn={batch_norm is not None}"             )-        weight = numpy_helper.to_array(inits[node.input[1]])-        bias = numpy_helper.to_array(inits[node.input[2]]) if len(node.input) > 2 else None-        if bias is None:-            raise SystemExit(-                f"{node.output[0]}: no bias. The shaders always add one, so a "-                "bias-less layer would need a zero tensor synthesised here."+            tensors.append(weight)+            tensors.append(bias)+        elif node.op_type == "BatchNormalization":+            # Folded above, when the layer it follows was emitted. One that was not is a+            # batch norm somewhere in the middle of the graph, which nothing here can+            # absorb and no shader implements.+            if node.output[0] not in folded:+                raise SystemExit(+                    f"{node.output[0]}: a BatchNormalization that does not follow a Gemm. "+                    "Only a trailing batch norm can be folded away."+                )+            continue+        else:+            continue+        layers.append(+            Layer(+                len(layers),+                node.op_type,+                node.output[0],+                key,+                first_tensor,+                len(tensors) - first_tensor,             )-        layers.append(Layer(len(layers), node, weight, bias))-        tensors.append(weight)-        tensors.append(bias)+        )     return layers, tensors  @@ -178,20 +376,26 @@ def layer_table_digest(layers): def check_graph(model, graph_id_name):     graph = model.graph     want = GEOMETRY[graph_id_name]-    size = want["size"]      names = [i.name for i in graph.input]     if names != [want["input"]]:         raise SystemExit(f"inputs are {names}, expected [{want['input']!r}]")     dims = [d.dim_value or d.dim_param for d in graph.input[0].type.tensor_type.shape.dim]-    # Batch may be symbolic; the spatial dims may not be, because every folded-    # Resize target and pad below was resolved at this exact size.-    if list(dims[1:]) != [3, size, size]:-        raise SystemExit(f"input shape {dims}, expected [batch, 3, {size}, {size}]")+    # Batch may be symbolic. A spatial dim may be too, but only where the expected+    # shape says so: for the fixed-size nets every folded Resize target and pad below+    # was resolved at exactly this size, so a dynamic one would silently mislower.+    got = list(dims[1:])+    expect = want["shape"]+    mismatched = len(got) != len(expect) or any(+        e is not None and g != e for g, e in zip(got, expect)+    )+    if mismatched:+        raise SystemExit(f"input shape {dims}, expected [batch] + {expect}")      outputs = [o.name for o in graph.output]-    if want["output"] not in outputs:-        raise SystemExit(f"outputs are {outputs}, expected {want['output']!r} among them")+    absent = [o for o in want["outputs"] if o not in outputs]+    if absent:+        raise SystemExit(f"outputs are {outputs}, expected {absent} among them")      counts = {}     for node in graph.node:@@ -254,7 +458,7 @@ def main():      model = onnx.load(args.onnx)     check_graph(model, args.graph)-    layers, tensors = collect_layers(model.graph)+    layers, tensors = collect_layers(model)      digest = layer_table_digest(layers)     if args.print_digest:@@ -275,7 +479,7 @@ def main():      if args.print_layers:         for layer in layers:-            print(f"{layer.index:4d} {layer.key()}  # {layer.name}")+            print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()}  # {layer.name}")      blob, count = build(layers, tensors, GRAPHS[args.graph], onnx_sha256)     if args.out: