File size: 4,513 Bytes
7d7fddc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# SPDX-License-Identifier: Apache-2.0
"""A VisionPilot ONNX graph as plain Python data (``onnx`` only: no onnxruntime, no ttnn, no torch).

The graphs are the published fp32 ONNX files with the batch fixed to 1 and constants folded by ``tools/fold.py``
(onnxruntime's *basic* level: constant folding and Conv + BatchNorm fusion, no provider-specific fused ops), so
every node is a standard ONNX op and every tensor has a static shape.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple

import numpy as np


@dataclass
class Node:
    name: str
    op: str
    inputs: List[str]
    outputs: List[str]
    attrs: Dict[str, Any]

    def attr(self, key: str, default: Any = None) -> Any:
        return self.attrs.get(key, default)


class Graph:
    """Nodes in topological order, constants (initializers and Constant nodes), static shapes and the
    producer / consumer maps."""

    def __init__(self, source: Any):
        import onnx
        from onnx import numpy_helper, shape_inference

        model = source if isinstance(source, onnx.ModelProto) else onnx.load(str(source))
        model = shape_inference.infer_shapes(model)
        g = model.graph
        self.consts: Dict[str, np.ndarray] = {t.name: numpy_helper.to_array(t) for t in g.initializer}
        self.nodes: List[Node] = []
        for n in g.node:
            attrs = {}
            for a in n.attribute:
                v = onnx.helper.get_attribute_value(a)
                if isinstance(v, bytes):
                    v = v.decode()
                elif isinstance(v, onnx.TensorProto):
                    v = numpy_helper.to_array(v)
                attrs[a.name] = v
            if n.op_type == "Constant":
                self.consts[n.output[0]] = np.asarray(attrs["value"])
                continue
            self.nodes.append(Node(n.name or n.output[0], n.op_type, list(n.input), list(n.output), attrs))
        self.shapes: Dict[str, Tuple[int, ...]] = {}
        for v in list(g.value_info) + list(g.input) + list(g.output):
            dims = v.type.tensor_type.shape.dim
            self.shapes[v.name] = tuple(int(d.dim_value) for d in dims)
        for name, arr in self.consts.items():
            self.shapes[name] = tuple(int(s) for s in arr.shape)
        self.inputs: List[str] = [i.name for i in g.input if i.name not in self.consts]
        self.outputs: List[str] = [o.name for o in g.output]
        self.producer: Dict[str, Node] = {o: n for n in self.nodes for o in n.outputs}
        self.consumers: Dict[str, List[Node]] = {}
        for n in self.nodes:
            for i in n.inputs:
                if i:
                    self.consumers.setdefault(i, []).append(n)
        self.by_name: Dict[str, Node] = {n.name: n for n in self.nodes}

    # ---- queries
    def is_const(self, name: str) -> bool:
        return name in self.consts

    def const(self, name: str) -> np.ndarray:
        if name not in self.consts:
            raise KeyError(f"{name!r} is not a constant of the graph")
        return self.consts[name]

    def shape(self, name: str) -> Tuple[int, ...]:
        if name not in self.shapes:
            raise KeyError(f"no static shape for {name!r} (run tools/fold.py on the published ONNX first)")
        return self.shapes[name]

    def users(self, name: str) -> List[Node]:
        return self.consumers.get(name, [])

    def ancestors(self, tensors: Iterable[str]) -> Set[str]:
        """Names of the nodes needed to compute ``tensors``."""
        need: Set[str] = set()
        stack = [t for t in tensors]
        seen: Set[str] = set()
        while stack:
            t = stack.pop()
            if t in seen:
                continue
            seen.add(t)
            n = self.producer.get(t)
            if n is None or n.name in need:
                continue
            need.add(n.name)
            stack.extend(i for i in n.inputs if i and i not in self.consts)
        return need

    def nodes_named(self, names: Set[str]) -> List[Node]:
        """The nodes of ``names`` in graph (topological) order."""
        return [n for n in self.nodes if n.name in names]

    def num_params(self) -> int:
        return int(sum(a.size for a in self.consts.values()))


def scalar(value: Optional[np.ndarray]) -> float:
    a = np.asarray(value)
    if a.size != 1:
        raise ValueError(f"expected a scalar constant, got shape {a.shape}")
    return float(a.reshape(()))