utils.py 9.23 KB
Newer Older
1
2
3
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

4
5
6
7
from typing import Optional

from typing_extensions import TypeGuard

8
from nni.nas.execution.common import Cell, Model, Graph, Node, Edge
9
10


11
def build_full_name(prefix, name, seq=None):
QuanluZhang's avatar
QuanluZhang committed
12
13
    if isinstance(name, list):
        name = '__'.join(name)
14
    if seq is None:
15
        return '{}__{}'.format(prefix, name)
16
    else:
17
18
        return '{}__{}{}'.format(prefix, name, str(seq))

19

20
21
22
23
24
25
26
27
28
def build_python_name(prefix, name):
    if isinstance(name, list):
        name = '.'.join(name)
    if prefix:
        return '{}.{}'.format(prefix, name)
    else: # predix could be None
        return name


29
30
31
32
def build_cand_name(name, label):
    return f'layerchoice_{label}_{name}'


33
34
35
36
37
def _convert_name(name: str) -> str:
    """
    Convert the names using separator '.' to valid variable name in code
    """
    return name.replace('.', '__')
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


def _extract_info_from_trace_node(trace_node):
    """
    Extract parameters from a trace node.

    Parameters
    ----------
    trace_node: torch._C.Value
    """
    input_shape = []
    output_shape = []

    inputs = list(trace_node.inputs())

    # cat input tensors are in a strange place
    if trace_node.kind() == 'aten::cat':
        input_shape = [input.type().sizes() for input in inputs[0].node().inputs()]
    else:
        for _input in inputs:
            input_type = _input.type()
            if input_type.kind() == 'TensorType':
                shape = input_type.sizes()
                if shape:
                    input_shape.append(shape)

    for _output in trace_node.outputs():
        output_type = _output.type()
        if output_type.kind() == 'TensorType':
            shape = output_type.sizes()
            if shape:
                output_shape.append(shape)

71
    shape_parameters = {
72
73
74
75
76
        'input_shape': input_shape,
        'output_shape': output_shape,
    }

    if trace_node.kind() == 'aten::cat':
77
78
79
80
        parameters = {'dim': inputs[1].toIValue()}
        return shape_parameters, parameters
    else:
        return shape_parameters, None
81
82


83
def is_layerchoice_node(ir_node: Optional[Node]) -> TypeGuard[Node]:
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
    if ir_node is not None and isinstance(ir_node.operation, Cell) and ir_node.operation.parameters.get('mutation') == 'layerchoice':
        return True
    else:
        return False


def get_full_name_by_scope_name(ir_model: Model, scope_names, prefix=''):
    full_name = prefix

    for last_scope in range(len(scope_names)):
        ir_node = ir_model.get_node_by_name(full_name)
        # check if it's layerchoice
        if is_layerchoice_node(ir_node):
            full_name = f'layerchoice_{ir_node.operation.parameters["label"]}_{scope_names[last_scope]}'
        else:
            full_name = build_full_name(full_name, scope_names[last_scope])

    return full_name


def match_node(ir_model: Model, torch_node, prefix=''):
    """
    Match the corresponding node of a torch._C.Value
    """
    scope_names = torch_node.scopeName().split('/')[-1].split('.')[1:]
    full_name = get_full_name_by_scope_name(ir_model, scope_names, prefix)
    # handle the case when node is not nn.Module, but directly used in forward()
    # Because name can't be directly matched, so I use a hacky way.
    # I match the first unshaped node of that kind
    graph = ir_model.graphs.get(full_name)
    if graph is not None:
        for node in graph.get_nodes_by_type(torch_node.kind()):
116
            if not node.operation.attributes['input_shape']:
117
118
119
120
121
122
123
                return node
        return None
    else:
        return ir_model.get_node_by_name(full_name)


def _without_shape_info(node: Node):
124
    return not node.operation.attributes['input_shape'] and not node.operation.attributes['output_shape']
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259


def flatten_model_graph(ir_model: Model):
    """
    Flatten the subgraph into root graph.
    """
    def _flatten(graph: Graph):
        """
        flatten this graph
        """
        model = graph.model
        node_to_remove = []

        for node in graph.hidden_nodes:
            node_graph = model.graphs.get(node.name)
            if node_graph is not None:
                _flatten(node_graph)

                # flatten node graph into this graph
                id_to_new_node = {}
                for node_graph_node in node_graph.hidden_nodes:
                    new_node = Node(graph, node_graph_node.id, node_graph_node.name, node_graph_node.operation, _internal=True)
                    new_node.update_label(node_graph_node.label)
                    new_node._register()
                    id_to_new_node[new_node.id] = new_node

                # reconnect node edges
                for in_edge in node.incoming_edges:
                    graph.del_edge(in_edge)
                    for input_node_edge in node_graph.input_node.outgoing_edges:
                        if input_node_edge.head_slot == in_edge.tail_slot:
                            graph.add_edge(
                                head=(in_edge.head, in_edge.head_slot),
                                tail=(id_to_new_node[input_node_edge.tail.id], input_node_edge.tail_slot))

                for out_edge in node.outgoing_edges:
                    graph.del_edge(out_edge)
                    for output_node_edge in node_graph.output_node.incoming_edges:
                        if output_node_edge.head_slot == out_edge.tail_slot:
                            graph.add_edge(
                                head=(id_to_new_node[output_node_edge.head.id], output_node_edge.head_slot),
                                tail=(out_edge.tail, out_edge.tail_slot))

                for edge in node_graph.edges:
                    if edge.head == node_graph.input_node or edge.tail == node_graph.output_node:
                        continue
                    new_head = id_to_new_node[edge.head.id]
                    new_tail = id_to_new_node[edge.tail.id]
                    Edge((new_head, edge.head_slot), (new_tail, edge.tail_slot), _internal=True)._register()

                node_to_remove.append(node)
                del model.graphs[node.name]

        for node in node_to_remove:
            node.remove()

    new_ir_model = ir_model.fork()
    _flatten(new_ir_model.root_graph)

    # remove subgraphs
    new_ir_model.graphs = {new_ir_model._root_graph_name: new_ir_model.root_graph}
    return new_ir_model


def flatten_model_graph_without_layerchoice(ir_model: Model):
    """
    Flatten the subgraph into root graph and jump all layerchoice
    """
    def _flatten_without_layerchoice(graph: Graph):
        """
        flatten this graph
        """
        model = graph.model
        node_to_remove = []

        for node in graph.hidden_nodes:
            if is_layerchoice_node(node):
                for in_edge in node.incoming_edges:
                    graph.del_edge(in_edge)
                for out_edge in node.outgoing_edges:
                    graph.del_edge(out_edge)
                del model.graphs[node.name]
                node.remove()
                return

            node_graph = model.graphs.get(node.name)
            if node_graph is not None:
                _flatten_without_layerchoice(node_graph)

                # flatten node graph into this graph
                id_to_new_node = {}
                for node_graph_node in node_graph.hidden_nodes:
                    new_node = Node(graph, node_graph_node.id, node_graph_node.name, node_graph_node.operation, _internal=True)
                    new_node.update_label(node_graph_node.label)
                    new_node._register()
                    id_to_new_node[new_node.id] = new_node

                # reconnect node edges
                for in_edge in node.incoming_edges:
                    graph.del_edge(in_edge)
                    for input_node_edge in node_graph.input_node.outgoing_edges:
                        if input_node_edge.head_slot == in_edge.tail_slot:
                            graph.add_edge(
                                head=(in_edge.head, in_edge.head_slot),
                                tail=(id_to_new_node[input_node_edge.tail.id], input_node_edge.tail_slot))

                for out_edge in node.outgoing_edges:
                    graph.del_edge(out_edge)
                    for output_node_edge in node_graph.output_node.incoming_edges:
                        if output_node_edge.head_slot == out_edge.tail_slot:
                            graph.add_edge(
                                head=(id_to_new_node[output_node_edge.head.id], output_node_edge.head_slot),
                                tail=(out_edge.tail, out_edge.tail_slot))


                for edge in node_graph.edges:
                    if edge.head == node_graph.input_node or edge.tail == node_graph.output_node:
                        continue
                    new_head = id_to_new_node[edge.head.id]
                    new_tail = id_to_new_node[edge.tail.id]
                    Edge((new_head, edge.head_slot), (new_tail, edge.tail_slot), _internal=True)._register()

                node_to_remove.append(node)
                del model.graphs[node.name]

        for node in node_to_remove:
            node.remove()

    new_ir_model = ir_model.fork()
    _flatten_without_layerchoice(new_ir_model.root_graph)

    # remove subgraphs
    new_ir_model.graphs = {new_ir_model._root_graph_name: new_ir_model.root_graph}
    return new_ir_model