Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
 
import itertools
from collections.abc import Sequence
from typing import Any
 
import numpy as np
from onnx import GraphProto, NodeProto, TensorProto, helper, numpy_helper
 
 
def _get_attribute(node: NodeProto, attr_name: str, default_value: Any = None) -> Any:
    """Get attribute value from node by attribute key."""
    found = [attr for attr in node.attribute if attr.name == attr_name]
    if found:
        return helper.get_attribute_value(found[0])
    return default_value
 
 
def _to_numpy_array(node: Any) -> np.ndarray:
    """Convert Constant node or TensorProto to Python value."""
    tensor = node
    if isinstance(node, NodeProto):
        tensor = _get_attribute(node, "value")
    assert isinstance(tensor, TensorProto)
    return numpy_helper.to_array(tensor).tolist()
 
 
class GraphMatcher:
    """Sub-graph matcher with given pattern.
 
    GraphMatcher takes an ONNX graph to initialize. It tries to match sub-graphs to a given pattern and yield
    matched sub-graphs (a list of matched nodes for each sub-graph) one by one.
 
    Pattern is described by a list. Each entry of the list is a Tuple:
 
        Tuple[str, bool, List[Tuple[int, int, int]]], e.g., ("FusedMatMul", False, [(2, 0, 1), (15, 0, 0)])
 
        * First string is the Op type, e.g., "FusedMatMul".
        * Second bool indicates it's producer node or consumer node for source node.
        * There is a list to describe the edge infos of this node to other nodes, each edge is a tuple with 3 integers,
          first integer is the index of the target node in the list, second integer is the output index of the edge,
          and third integer is the input index of the edge.
 
    For each entry, GraphMatcher used the first edge to lookup target node, and try to use make sure the sug-graph also
    matches rest edge infos.
 
    Note that when lookup target node, it will only take the first matched node as target node. For example, if a source
    node has multiple "MatMul" consumers nodes consuming same output, only the first "MatMul" node will be returned.
    You need to avoid using such confusing edge info as the first edge info for node lookup. Try to use other edge to
    avoid such confusion if possible.
    """
 
    def __init__(self, graph: GraphProto):
        self._graph: GraphProto = graph
        self._op_type_to_nodes: dict[str, list[NodeProto]] = {}
        self._consumer_count: dict[str, int] = {}
        for node in graph.node:
            if node.op_type not in self._op_type_to_nodes:
                self._op_type_to_nodes[node.op_type] = []
            self._op_type_to_nodes[node.op_type].append(node)
            for input in node.input:
                self._consumer_count[input] = self._consumer_count.get(input, 0) + 1
 
    def _get_producer(self, arg: str, op_type: str, output_idx: int):
        for node in self._op_type_to_nodes.get(op_type, []):
            if (output_idx >= 0 and len(node.output) > output_idx and node.output[output_idx] == arg) or (
                output_idx == -1 and arg in node.output
            ):
                return node
        return None
 
    def _get_consumer(self, arg: str, op_type: str, input_idx: int):
        for node in self._op_type_to_nodes.get(op_type, []):
            if (input_idx >= 0 and len(node.input) > input_idx and node.input[input_idx] == arg) or (
                input_idx == -1 and arg in node.input
            ):
                return node
        return None
 
    def get_consumer_count(self, arg: str):
        return self._consumer_count.get(arg, 0)
 
    def get_constant_value(self, arg: str):
        node_or_initializer = None
        if "Constant" in self._op_type_to_nodes:
            for node in self._op_type_to_nodes["Constant"]:
                if arg in node.output:
                    node_or_initializer = node
                    break
        if node_or_initializer is None:
            for initializer in self._graph.initializer:
                if arg == initializer.name:
                    node_or_initializer = initializer
                    break
        if node_or_initializer is None:
            return None
        return _to_numpy_array(node_or_initializer)
 
    def get_type_and_shape(self, arg: str):
        value_infos = [
            value_info
            for value_info in itertools.chain(self._graph.input, self._graph.value_info)
            if value_info.name == arg
        ]
        if len(value_infos) > 0 and value_infos[0].type.tensor_type.HasField("shape"):
            shape = []
            for dim in value_infos[0].type.tensor_type.shape.dim:
                if dim.dim_param:
                    shape.append(dim.dim_param)
                else:
                    shape.append(dim.dim_value)
            return value_infos[0].type.tensor_type.elem_type, shape
        initializers = [initializer for initializer in self._graph.initializer if initializer.name == arg]
        if len(initializers) > 0:
            return initializers[0].data_type, initializers[0].dims
        return None, None
 
    def _match_pattern(self, node: NodeProto, pattern: list[tuple[str, bool, list[tuple[int, int, int]]]]):
        nodes = [node]
        for i in range(1, len(pattern)):
            next_op_type = pattern[i][0]
            is_producer = pattern[i][1]
            node_idx, output_idx, input_idx = pattern[i][2][0]
            next_node = (
                self._get_producer(nodes[node_idx].input[input_idx], next_op_type, output_idx)
                if is_producer
                else self._get_consumer(nodes[node_idx].output[output_idx], next_op_type, input_idx)
            )
            if next_node is None:
                return []
            for j in range(1, len(pattern[i][2])):
                node_idx, output_idx, input_idx = pattern[i][2][j]
                assert output_idx >= 0 and input_idx >= 0
                if (not is_producer and nodes[node_idx].output[output_idx] != next_node.input[input_idx]) or (
                    is_producer and next_node.output[output_idx] != nodes[node_idx].input[input_idx]
                ):
                    return []
            nodes.append(next_node)
        return nodes
 
    def match_pattern(self, pattern: list[tuple[str, bool, list[tuple[int, int, int]]]]):
        for node in self._op_type_to_nodes.get(pattern[0][0], []):
            result = self._match_pattern(node, pattern)
            if len(result) == len(pattern):
                yield result
 
 
def check_attribute_value(node: NodeProto, attr_name: str, expected_value: Any):
    """Check if the attribute of given node has expected value."""
    value = _get_attribute(node, attr_name)
    return value == expected_value
 
 
def make_constant_node(name: str, dtype: TensorProto.DataType, dims: Sequence[int], vals: Any):
    """Create a constant node with given constant tensor (data type, shape, and data)."""
    return helper.make_node(
        "Constant",
        inputs=[],
        outputs=[name],
        value=helper.make_tensor(name=name, data_type=dtype, dims=dims, vals=vals),
    )
 
 
def update_graph(
    graph: GraphProto,
    nodes_to_remove: list[NodeProto],
    nodes_to_add: list[NodeProto],
    new_value_infos: list[TensorProto] = [],  # noqa: B006
):
    """Update an ONNX graph by removing some nodes, and adding some new nodes and value infos."""
    nodes = [node for node in graph.node if node not in nodes_to_remove]
    nodes.extend(nodes_to_add)
    graph.ClearField("node")
    graph.node.extend(nodes)
    if len(new_value_infos) > 0:
        graph.value_info.extend(new_value_infos)