def _match(self, G: GraphView, set_identity: bool = True, **kwargs): modified_graph = False candidates = [node for node in G.nodes() if len(G.indexed_out_edges(node.name)) == 1 and len(G.out_edges(node.name)) > 1] while candidates: node = candidates.pop(0) strings = self.explore(G, [node]) if not strings: continue modified_graph = True primary = strings.pop(0) for pnode in primary: if pnode in candidates: candidates.remove(pnode) out_edges = [] for other in strings: out_edges.extend(G.out_edges(other[-1].name)) for other_node in other: if other_node in candidates: candidates.remove(other_node) G.remove(other_node) nid = NodeId(other_node) if G.quantization and nid in G.quantization: del G.quantization[nid] LOG.info( f'removed duplicates from {primary[0].name} {",".join(node.name for node in other)}') pend = primary[-1] for edge in out_edges: G.add_edge( NNEdge(from_node=pend, to_node=edge.to_node, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return modified_graph
def match(self, G: GraphView, set_identity: bool = True): if not G.quantization: return for nid in [nid for nid, qrec in G.quantization.sorted_iterator(G) if qrec is None or not (qrec.in_qs and qrec.out_qs)]: if nid.fnode_name: LOG.warning("can't add quantization to fused node %s", nid.fnode_name) continue if nid.node_name not in G: # previous fusions may have removed nodes from the graph continue node = nid.get_node(G) predecessors = [NodeId(pred) for pred in G.predecessors(node.name)] successors = [NodeId(succ) for succs in G.successors(node.name) for succ in succs] go_back = not successors or (predecessors and all(pred in G.quantization for pred in predecessors)) go_forward = not predecessors or (successors and all(succ in G.quantization for succ in successors)) if not (go_back or go_forward): LOG.warning("node %s is not connected to anything and has no quantization", node.name) continue if go_forward: out_qrecs = set(G.quantization[nid] for nid in successors) if not all(isinstance(out_qrec, MultQuantizationRecord) for out_qrec in out_qrecs): continue out_qtypes = reduce_qtypes([(edge.from_idx, G.quantization[NodeId(edge.to_node)].in_qs[edge.to_idx]) for edge in G.out_edges(node.name)]) else: out_qtypes = None if go_back: in_qrecs = set(G.quantization[nid] for nid in predecessors) if not all(isinstance(in_qrec, MultQuantizationRecord) for in_qrec in in_qrecs): continue in_qtypes = reduce_qtypes([(edge.to_idx, G.quantization[NodeId(edge.from_node)].out_qs[edge.from_idx]) for edge in G.in_edges(node.name)]) else: in_qtypes = None if not in_qtypes: if not predecessors: LOG.info("setting quantization on input node %s", node.name) qrec = MultQuantizationRecord(in_qs=deepcopy(out_qtypes), out_qs=deepcopy(out_qtypes)) else: raise NotImplementedError("propagating qrecs not implemented") elif not out_qtypes: if not successors: LOG.info("setting quantization on output node %s", node.name) qrec = MultQuantizationRecord(in_qs=deepcopy(in_qtypes), out_qs=deepcopy(in_qtypes)) else: raise NotImplementedError("propagating qrecs not implemented") else: LOG.info("setting quantization on node %s", node.name) qrec = MultQuantizationRecord(in_qs=deepcopy(in_qtypes), out_qs=deepcopy(out_qtypes)) G.quantization[nid] = qrec if set_identity: self.set_identity(G) return False
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): const_ops = [node for node in G.nodes() if isinstance(node, MatrixMulParameters) and any([isinstance(edge.from_node, ConstantInputParameters) and check_equals(G, edge.from_node, 1.0/6.0) for edge in G.in_edges(node.name)])] oprecs = [oprec for oprec in (look_back(G, op) for op in const_ops) if oprec is not None] has_modified_graph = False for oprec in oprecs: mul_edge = G.out_edges(oprec['mul'][0].name) if len(mul_edge) == 1: mul_edge = mul_edge[0] if isinstance(mul_edge.to_node, ReluActivationParameters): oprec['relu3'] = (mul_edge.to_node, G.quantization[NodeId(mul_edge.to_node)]) has_modified_graph = True process_rec(G, oprec) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): has_modified_graph = False for node in G.nodes(node_classes=tuple(VALID_FUSIONS.keys())): node_list = self.get_node_list(G, node, FusionMatch(self._default_ktype)) if node_list is None or len(node_list.order) < 2: continue LOG.info("fusing nodes %s", ",".join( (node.name for node in node_list.order))) has_modified_graph = True subgraph = GraphView() last_node = None for snode in node_list.order: if last_node is not None: subgraph.add_edge( NNEdge(from_node=last_node, to_node=snode)) last_node = snode # assumption here is that the first node could have multiple inputs but definitely has only # one output input_mapping = [[ (node_list.node, idx) ] for idx in range(G.num_in_edges(node_list.node.name))] output_mapping = [(last_node, 0)] pnode = node_list.fusions_class(node_list.node.name + '_fusion', fusion_type=node_list.fusion_type, subgraph=subgraph, input_mapping=input_mapping, output_mapping=output_mapping) if G.quantization: # TODO - stats qrecs = G.quantization.get_all(pnode.contained_nodes()) if qrecs: prec = QRec.copy_ktype(qrecs[0], in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) for fnode in pnode.contained_nodes(): G.quantization.move_to_fusion(fnode, pnode) G.quantization[NodeId(pnode)] = prec in_edges = G.in_edges(node_list.node.name) out_edges = G.out_edges(last_node.name) for snode in node_list.order: G.remove(snode) for edge in in_edges: G.add_edge( NNEdge(edge.from_node, pnode, from_idx=edge.from_idx, to_idx=edge.to_idx)) for edge in out_edges: G.add_edge( NNEdge(pnode, edge.to_node, from_idx=edge.from_idx, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def find_forward(G: GraphView, edge, find_node_classes, skip_node_classes=None, find_skip=None): if find_skip is None: find_skip = [find_node_classes, skip_node_classes] for idx, elem in enumerate(find_skip): if elem is not None and not isinstance(elem, tuple): if isinstance(elem, list): find_skip[idx] = tuple(elem) else: find_skip[idx] = tuple([elem]) if isinstance(edge.to_node, find_skip[0]): return [[edge]] if skip_node_classes and isinstance(edge.to_node, find_skip[0]): res = [] for out_edge in G.out_edges(edge.to_node.name): edge_lists = find_forward(G, out_edge, find_node_classes, find_skip=find_skip) if not edge_lists: continue res.extend([[edge] + edge_list for edge_list in edge_lists]) return res return []
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): fragment = GraphMatcher( match_function=lambda state, frag: (frag, state['match'])) fragment.add_node(MatScaleNodeMatch()) has_modified_graph = False for frag, match in fragment.match_graph(G): match_edges = [ G.indexed_in_edges(node.name)[idx] for node, idx in match['inputs'] ] matched_node = list(frag.nodes())[0] out_edges = G.out_edges(matched_node.name) has_modified_graph = True G.remove(matched_node) fnode = MatScaleFusionParameters( "{}_fusion".format(matched_node.name), fusion_type=match['type'], subgraph=frag, input_mapping=[[(matched_node, 0)], [(matched_node, 1)]]) G.add_node(fnode) for idx, edge in enumerate(match_edges): edge.to_node = fnode edge.to_idx = idx G.add_edge(edge) for edge in out_edges: edge.from_node = fnode G.add_edge(edge) if set_identity: self.set_identity(G) return has_modified_graph
def match(self, G: GraphView, set_identity: bool = True): if not G.quantization: return softmaxes = [ node for node in G.nodes() if isinstance(node, SoftMaxParameters) ] qrecs = [G.quantization[NodeId(node)] for node in softmaxes] if not all(isinstance(qrec, MultQuantizationRecord) for qrec in qrecs): return for softmax, qrec in zip(softmaxes, qrecs): in_q = qrec.in_qs[0] in_q.scale_to_pow2() for edge in G.in_edges(softmax.name): propagate_qtype_up(G, in_q, edge) for edge in G.out_edges(softmax.name): assert isinstance( edge.to_node, (OutputParameters, QuantizeParameters )), "Softmax is supported only at the end of the graph" out_qrec = G.quantization[NodeId(edge.to_node)] out_qrec.in_qs[0] = qrec.out_qs[0] out_qrec.out_qs[0] = qrec.out_qs[0] if set_identity: self.set_identity(G) return False
def match(self, G: GraphView, set_identity: bool = True): # get a list of all the nodes that are transposable but not transposes # Need to do this first to avoid mutating it when doing the modifications tnodes = list(filter(lambda n: isinstance(n, Transposable) and\ not isinstance(n, TransposeParameters), G.nodes())) for node in tnodes: if node.transpose_in: for idx, edge in enumerate(G.in_edges(node.name)): in_params = TransposeParameters("%s_TIN_%s" % (node.name, idx), transpose=node.transpose_in) if node.in_dims_hint: in_hint = node.in_dims_hint[edge.to_idx] out_hint = apply_reverse_transpose_to_hint(in_hint, node.transpose_in) in_params.in_dims_hint = [in_hint.copy()] in_params.out_dims_hint = [out_hint.copy()] node.in_dims_hint[edge.to_idx] = out_hint G.insert_node(in_params, edge.from_node.name, edge.to_node.name, from_idx=edge.from_idx, to_idx=edge.to_idx) node.transpose_in = None if node.transpose_out: for idx, edge in enumerate(G.out_edges(node.name)): out_params = TransposeParameters("%s_TOUT_%s" % (node.name, idx), transpose=node.transpose_out) if node.out_dims_hint: out_hint = node.out_dims_hint[edge.from_idx] in_hint = apply_reverse_transpose_to_hint(out_hint, node.transpose_out) out_params.in_dims_hint = [in_hint.copy()] out_params.out_dims_hint = [out_hint.copy()] node.out_dims_hint[edge.from_idx] = in_hint G.insert_node(out_params, edge.from_node.name, edge.to_node.name, from_idx=edge.from_idx, to_idx=edge.to_idx) node.transpose_out = None if set_identity: self.set_identity(G)
def _match(self, G: GraphView, set_identity: bool = True, **kwargs) -> bool: has_modified_graph = False for node in [ node for node in G.nodes() if self.node_does_nothing(G, node) ]: has_modified_graph = True in_edge = G.in_edges(node.name)[0] G.remove_edge(in_edge) for out_edge in G.out_edges(node.name): G.remove_edge(out_edge) G.add_edge( NNEdge(in_edge.from_node, out_edge.to_node, from_idx=in_edge.from_idx, to_idx=out_edge.to_idx)) LOG.info(f'removing {node.name} that does nothing') G.remove(node) if set_identity: self.set_identity(G) return has_modified_graph
def match(self, G: GraphView, set_identity: bool = True): has_modified = False for node in G.nodes(node_classes=ConstantInputParameters): out_edges = G.out_edges(node.name) if len(out_edges) <= 1: continue has_modified = True LOG.info( 'node %s has more than one out edge and will be duplicated', node.name) idx = 1 for out_edge in out_edges[1::]: new_constant = ConstantInputParameters(f'{node.name}_{idx}', dims=Dim.unnamed( node.dims.shape), value=node.value.copy()) G.remove_edge(out_edge) G.add_edge( NNEdge(from_node=new_constant, to_node=out_edge.to_node, to_idx=out_edge.to_idx)) idx += 1 if set_identity: self.set_identity(G) return has_modified
def match(self, G: GraphView, set_identity: bool = True): # Only works for reverses connected to one RNN node reverse_nodes = set([ node for node in G.nodes() if (isinstance(node, ReverseParameters) and len(G.out_edges(node.name)) == 1 and isinstance( G.out_edges(node.name)[0].to_node, RNNBaseParameters)) ]) has_modified_graph = False for reverse_node in reverse_nodes: in_edges = G.in_edges(reverse_node.name) rnn_edge = G.out_edges(reverse_node.name)[0] if rnn_edge.to_idx != 0: LOG.warning("reverse on rnn input %s", rnn_edge.to_idx) continue assert not rnn_edge.to_node.revert, "RNN node is already reversed!" rnn_edge.to_node.revert = True LOG.info("fusing reverses into node %s", rnn_edge.to_node.name) has_modified_graph = True G.remove(reverse_node) for edge in in_edges: G.add_edge( NNEdge(edge.from_node, rnn_edge.to_node, from_idx=edge.from_idx, to_idx=rnn_edge.to_idx)) for edge in G.out_edges(rnn_edge.to_node.name): if not isinstance(edge.to_node, ReverseParameters): continue if edge.from_idx != 0: LOG.warning("reverse on rnn output %s", edge.from_idx) continue rev_edges = G.out_edges(edge.to_node.name) G.remove(edge.to_node) for rev_edge in rev_edges: G.add_edge( NNEdge(edge.from_node, rev_edge.to_node, from_idx=edge.from_idx, to_idx=rev_edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): rnn_nodes = [ self.find_unpack(G, node) for node in G.nodes() if isinstance(node, RNNBaseParameters) and node.n_output_cells > 1 ] rnn_nodes_by_slice = self.validate_slices(G, rnn_nodes) rnn_nodes_by_slice = self.validate_multi_branch(G, rnn_nodes_by_slice) if not rnn_nodes_by_slice: return False for unpack_node, rnn_unpacks in rnn_nodes_by_slice.items(): modified_nodes = set() for rnn_unpack in rnn_unpacks: self.process_path(G, rnn_unpack, modified_nodes) # since process path will have removed all unnecessary nodes the edges will be correct here out_edges = G.out_edges(unpack_node.name) in_edges = G.in_edges(unpack_node.name) assert len(in_edges ) == 1, "expecting unpack node to have only one in edge" in_edge = in_edges[0] changes_shape = unpack_node.changes_shape if isinstance( unpack_node, StridedSliceParameters) else False LOG.info("Eliminating last cell unpack: %s", unpack_node.name) G.remove(unpack_node) # Here the strided slice can change the output shape of the RNN # so insert a reshape to do the shape change if changes_shape: reshape = ReshapeParameters( unpack_node.name + '_reshape', old_shape=Dim.unnamed(unpack_node.post_slice_shape), shape=Dim.unnamed(unpack_node.out_shape)) G.add_edge( NNEdge(from_node=in_edge.from_node, to_node=reshape, from_idx=in_edge.from_idx)) for out_edge in out_edges: G.add_edge( NNEdge(from_node=reshape, to_node=out_edge.to_node, to_idx=out_edge.to_idx)) if G.quantization: G.quantization[NodeId(reshape)] = G.quantization[NodeId( unpack)] else: for out_edge in out_edges: G.add_edge( NNEdge(from_node=in_edge.from_node, to_node=out_edge.to_node, from_idx=in_edge.from_idx, to_idx=out_edge.to_idx)) if G.quantization: del G.quantization[NodeId(unpack_node)] if set_identity: self.set_identity(G) return True
def match(self, G: GraphView, set_identity: bool = True): has_modified_graph = False for conv_node in [params for params in G.nodes() if isinstance(params, Conv2DParameters)]: node_list = self.get_node_list(G, conv_node) if node_list is None or len(node_list.order) < 2: continue if node_list.fusion_type == 'conv_active_pool': if node_list.pool.pool_type == "average": node_list.order = node_list.order[:2:] node_list.pool = None elif node_list.fusion_type == 'conv_pool_active': if node_list.pool.pool_type == "average" and node_list.active.activation != "relu": continue LOG.info("fusing nodes %s", ",".join((node.name for node in node_list.order))) has_modified_graph = True subgraph = GraphView() last_node = None for node in node_list.order: if last_node is not None: subgraph.add_edge(NNEdge(from_node=last_node, to_node=node)) last_node = node input_mapping = [[(node_list.conv, idx)] for idx in range(3)] output_mapping = [(last_node, 0)] pnode = ConvFusionParameters( node_list.conv.name + '_fusion', fusion_type=node_list.fusion_type, subgraph=subgraph, in_dims_hint=node_list.conv.in_dims_hint, out_dims_hint=node_list.conv.out_dims_hint, input_mapping=input_mapping, output_mapping=output_mapping) if G.quantization: qrecs = G.quantization.get_all(pnode.contained_nodes()) if qrecs: prec = None if isinstance(qrecs[0], (SymmetricQuantizationRecord, SymmetricScalableFilterQuantizationRecord)): prec = SymmetricQuantizationRecord( in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) elif isinstance(qrecs[0], (MultQuantizationRecord, MultScalableFilterQuantizationRecord)): prec = MultQuantizationRecord(in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) elif isinstance(qrecs[0], (Float32QuantizationRecord, Float32ScalableFilterQuantizationRecord)): prec = Float32QuantizationRecord( in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) for node in pnode.contained_nodes(): G.quantization.move_to_fusion(node, pnode) G.quantization[NodeId(pnode)] = prec in_edges = G.in_edges(node_list.conv.name) out_edges = G.out_edges(last_node.name) for node in node_list.order: G.remove(node) for edge in in_edges: G.add_edge(NNEdge(edge.from_node, pnode, from_idx=edge.from_idx, to_idx=edge.to_idx)) for edge in out_edges: G.add_edge(NNEdge(pnode, edge.to_node, from_idx=edge.from_idx, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): something_changed = False for relu_node in [node for node in G.nodes(node_classes=ReluActivationParameters) if node.upper_bound == 6]: out_edges = G.out_edges(relu_node) if len(out_edges) != 1 or not isinstance(out_edges[0].to_node, MatrixMulParameters): continue mul_node = out_edges[0].to_node in_edges = G.in_edges(mul_node) if len(in_edges) != 2: continue other_edge = (set(in_edges) - {out_edges[0]}).pop() constant_node = other_edge.from_node if len(G.out_edges(constant_node)) != 1: continue if (not isinstance(constant_node, ConstantInputParameters) or not check_equals(G, constant_node, 1.0/6.0)): continue something_changed = True activation = HSigmoidActivationParameters( G.unique_name(f'{mul_node.name}_hsigmoid'), offset=0) in_edges = G.in_edges(relu_node) out_edges = G.out_edges(mul_node) nodes_to_replace = [relu_node, mul_node, constant_node] LOG.info(f'fusing {", ".join(node.name for node in nodes_to_replace)} into HSIGMOID {activation.name}') G.remove_all(nodes_to_replace) for in_edge in in_edges: G.add_edge(NNEdge.clone(in_edge, to_node=activation, to_idx=0)) for out_edge in out_edges: G.add_edge(NNEdge.clone( out_edge, from_node=activation, from_idx=0)) if G.quantization: reluqrec = G.quantization[NodeId(relu_node)] mulqrec = G.quantization[NodeId(mul_node)] del G.quantization[NodeId(constant_node)] pqrec = QRec.copy_ktype( reluqrec, in_qs=reluqrec.in_qs, out_qs=mulqrec.out_qs) G.quantization[NodeId(activation)] = pqrec return something_changed
def match(self, G: GraphView, set_identity: bool = True): visited_edges = {} nodes_to_remove = [] has_modified_graph = False for node in G.inputs(): # check if constantinput. if is then check if positive and check max value if isinstance(node, ConstantInputParameters): if node.value is not None: if G.has_quantized_parameters: qrec = G.quantization[NodeId(node)] qtype = qrec.out_qs[0] if hasattr(qtype, 'wrapped'): qtype = qtype.wrapped val = qtype.dequantize(node.value) else: val = node.value if val.min() >= 0: status = (True, val.max()) else: status = (False, False) else: status = (False, False) for edge in G.out_edges(node.name): visited_edges[edge] = status nodes_to_remove += find_redundant_relus( G, edge.to_node, visited_edges) for node in nodes_to_remove: has_modified_graph = True # Only relus so only one in edge in_edge = G.in_edges(node.name)[0] for edge in G.out_edges(node.name): G.add_edge( NNEdge(from_node=in_edge.from_node, from_idx=in_edge.from_idx, to_node=edge.to_node, to_idx=edge.to_idx)) G.remove(node) if set_identity: self.set_identity(G) return has_modified_graph
def match(self, G: GraphView, set_identity: bool = True): # get a list of all the nodes that are transposable but not transposes # Need to do this first to avoid mutating it when doing the modifications tnodes = list(filter(lambda n: isinstance(n, Transposable) and not isinstance(n, TransposeParameters), G.nodes())) has_modified_graph = False for node in tnodes: if node.transpose_in: for idx, edge in enumerate(G.in_edges(node.name)): if edge.to_idx >= len(node.transpose_in): continue trans = node.transpose_in[edge.to_idx] if trans is None: continue has_modified_graph = True in_params = TransposeParameters("%s_TIN_%s" % (node.name, idx), transpose=trans) if node.in_dims_hint and node.in_dims_hint[edge.to_idx]: in_hint = node.in_dims_hint[edge.to_idx] out_hint = apply_reverse_transpose_to_hint(in_hint, trans) in_params.in_dims_hint = [in_hint.copy()] in_params.out_dims_hint = [out_hint.copy()] node.in_dims_hint[edge.to_idx] = out_hint if G.quantization: G.quantization.copy_to_node(node, in_params) G.insert_node(in_params, edge.from_node.name, edge.to_node.name, from_idx=edge.from_idx, to_idx=edge.to_idx, edge_class=NNEdge) node.transpose_in = None if node.transpose_out: for idx, edge in enumerate(G.out_edges(node.name)): if edge.from_idx >= len(node.transpose_out): continue trans = node.transpose_out[edge.from_idx] if trans is None: continue has_modified_graph = True out_params = TransposeParameters("%s_TOUT_%s" % (node.name, idx), transpose=trans) if node.out_dims_hint: out_hint = node.out_dims_hint[edge.from_idx] in_hint = apply_reverse_transpose_to_hint(out_hint, trans) out_params.in_dims_hint = [in_hint.copy()] out_params.out_dims_hint = [out_hint.copy()] node.out_dims_hint[edge.from_idx] = in_hint if G.quantization: G.quantization.copy_to_node(node, out_params) G.insert_node(out_params, edge.from_node.name, edge.to_node.name, from_idx=edge.from_idx, to_idx=edge.to_idx, edge_class=NNEdge) node.transpose_out = None if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): has_modified_graph = False group_identity = kwargs.get('group_identity') if group_identity == 'pow2_match_group': valid_activations = VALID_ACTIVATIONS_POW2 else: valid_activations = VALID_ACTIVATIONS_SQ8 for fc_node in [params for params in G.nodes() if isinstance(params, FcParameters)]: node_list = self.get_node_list(G, fc_node, valid_activations) if node_list is None or len(node_list.order) < 2: continue LOG.info("fusing nodes %s", ",".join( (node.name for node in node_list.order))) has_modified_graph = True subgraph = GraphView() last_node = None for node in node_list.order: if last_node is not None: subgraph.add_edge( NNEdge(from_node=last_node, to_node=node)) last_node = node input_mapping = [[(node_list.linear, idx)] for idx in range(3)] output_mapping = [(last_node, 0)] pnode = LinearFusionParameters( node_list.linear.name + '_fusion', fusion_type=node_list.fusion_type, subgraph=subgraph, input_mapping=input_mapping, output_mapping=output_mapping) if G.quantization: # TODO - stats qrecs = G.quantization.get_all(pnode.contained_nodes()) if qrecs: prec = QRec.copy_ktype( qrecs[0], in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) for node in pnode.contained_nodes(): G.quantization.move_to_fusion(node, pnode) G.quantization[NodeId(pnode)] = prec in_edges = G.in_edges(node_list.linear.name) out_edges = G.out_edges(last_node.name) for node in node_list.order: G.remove(node) for edge in in_edges: G.add_edge(NNEdge(edge.from_node, pnode, from_idx=edge.from_idx, to_idx=edge.to_idx)) for edge in out_edges: G.add_edge(NNEdge(pnode, edge.to_node, from_idx=edge.from_idx, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): has_modified_graph = False for node in G.nodes(node_classes=SplitParameters): same_op_edges = self.moveable_same_operation_edges(G, node) if not same_op_edges: continue has_modified_graph = True in_edges = G.in_edges(node.name) assert len(in_edges) == 1 # sort by name to ensure that operation is repeatable same_op_edges.sort(key=lambda x: x.to_node.name) keep_node = same_op_edges[0].to_node LOG.info('split node %s has duplicate operations on its out edges', node.name) LOG.info('moving %s before split node %s', keep_node.name, node.name) for edge in G.out_edges(node.name): node_out_edges = G.out_edges(edge.to_node.name) G.remove(edge.to_node) if edge.to_node != keep_node: LOG.info('deleting duplicate node %s', edge.to_node.name) if G.quantization: nid = NodeId(edge.to_node) if nid in G.quantization: del G.quantization[nid] for out_edge in node_out_edges: G.add_edge( NNEdge(from_node=node, from_idx=edge.from_idx, to_node=out_edge.to_node, to_idx=out_edge.to_idx)) G.insert_node_at_edge(keep_node, in_edges[0], edge_class=NNEdge) if G.quantization: quantizer = NewQuantizer.from_quantized_graph(G) quantizer.quantize() if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): visited_edges = {} nodes_to_remove = [] has_modified_graph = False for node in G.inputs(): # check if constantinput. if is then check if positive and check max value if isinstance(node, ConstantInputParameters): if node.value is not None: val = node.dqvalue if np.min(val) >= 0: status = (True, np.max(val)) else: status = (False, False) else: status = (False, False) else: status = (False, False) for edge in G.out_edges(node.name): visited_edges[edge] = status nodes_to_remove += find_redundant_relus( G, edge.to_node, visited_edges) for node in nodes_to_remove: has_modified_graph = True # Only relus so only one in edge LOG.info("removing redundant relu %s", node.name) in_edge = G.in_edges(node.name)[0] out_edges = G.out_edges(node.name) G.remove(node) for edge in out_edges: G.add_edge(NNEdge(from_node=in_edge.from_node, from_idx=in_edge.from_idx, to_node=edge.to_node, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs) -> bool: has_modified_graph = False for split_node in set( [node for node in G.nodes() if isinstance(node, SplitParameters)]): in_edges = G.in_edges(split_node.name) if len(in_edges) > 1: continue in_edge = in_edges[0] if not isinstance(in_edge.from_node, ConcatParameters): continue concat_node = in_edge.from_node if len(G.out_edges(concat_node.name)) > 1: continue if concat_node.transpose_out or split_node.transpose_in: continue if concat_node.axis != split_node.axis: continue axis = concat_node.axis split_out_sizes = [ out_shape[axis] for out_shape in split_node.out_shapes ] if len(split_out_sizes) != len(concat_node.in_dims): continue if not all(split_out_sizes[idx] == in_dim.shape[axis] for idx, in_dim in enumerate(concat_node.in_dims)): continue has_modified_graph = True LOG.info("removing unnecessary concat/split pair %s/%s", concat_node.name, split_node.name) concat_in_edges = G.indexed_in_edges(concat_node.name) split_out_edges = G.indexed_out_edges(split_node.name) G.remove(split_node) G.remove(concat_node) for idx, in_edge in enumerate(concat_in_edges): for out_edge in split_out_edges[idx]: G.add_edge( NNEdge(from_node=in_edge.from_node, from_idx=in_edge.from_idx, to_node=out_edge.to_node, to_idx=out_edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs) -> bool: replaced = True has_modified_graph = False while replaced: replaced = False for subgraph in self.match_function(G): # TODO - Save in and out edges here since the replace function may modify the # subgraph in_edges = [ in_edge for input_node in subgraph.inputs() for in_edge in G.in_edges(input_node.name) ] out_edges = [ out_edge for output_node in subgraph.outputs() for out_edge in G.out_edges(output_node.name) ] try: replacement, edge_in_mapping, edge_out_mapping = self.replace_function( G, subgraph) if replacement is None: G.remove_fragment(subgraph) has_modified_graph = True elif isinstance(replacement, Node): # use saved in and out edges G.replace_fragment(subgraph, replacement, frag_in_edges=in_edges, frag_out_edges=out_edges, edge_in_mapping=edge_in_mapping, edge_out_mapping=edge_out_mapping) has_modified_graph = True else: raise TypeError( "unexcepted return value from replace_function") replaced = True break except DontReplaceError: pass if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): fac = MatScalePairMatchFactory() has_modified_graph = False for frag, match in fac.get_matcher().match_graph(G): match_edges = [ G.indexed_in_edges(node.name)[idx] for node, idx in match ] first_node = frag.inputs()[0] last_node = frag.outputs()[0] out_edges = G.out_edges(last_node.name) for node in frag.nodes(): G.remove(node) input_mapping = MatScaleFusionParameters.get_mapping_from_edges( match_edges) fnode = MatScaleFusionParameters( "{}_{}_fusion".format(first_node.name, last_node.name), fusion_type="vec_scalar", subgraph=frag, input_mapping=MatScaleFusionParameters.convert_input_mapping( input_mapping)) has_modified_graph = True G.add_node(fnode) fnode.in_dims_hint = [None] * 3 for idx, edge in enumerate(match_edges): new_edge = edge.clone( to_node=fnode, to_idx=list(input_mapping[edge.to_node].keys())[0]) if new_edge.from_node.out_dims_hint: fnode.in_dims_hint[idx] = new_edge.from_node.out_dims_hint[ edge.from_idx] G.add_edge(new_edge) for edge in out_edges: new_edge = edge.clone(from_node=fnode) G.add_edge(new_edge) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): modified_graph = True while modified_graph: modified_graph = False for reshape in G.nodes(node_classes=(ReshapeParameters, )): if not reshape.has_transpose and reshape.shape.shape == reshape.old_shape.shape: modified_graph = True LOG.info('removing reshape that does nothing %s', reshape.name) G.remove_and_reconnect(reshape, edge_class=NNEdge) nid = NodeId(reshape) if G.quantization and nid in G.quantization: del G.quantization[nid] res = None for reshape in G.nodes(node_classes=(ReshapeParameters, )): res = self.validate_reshape(G, reshape) if res: LOG.info('unnecessary reshape found after %s', reshape.name) modified_graph = True (reshape, candidates, out_shape) = res for candidate in candidates: LOG.info( 'removing unnecessary reshape or transpose %s', candidate.name) edges = G.out_edges(candidate.name) G.remove(candidate) nid = NodeId(candidate) if G.quantization and nid in G.quantization: del G.quantization[nid] for edge in edges: G.add_edge( NNEdge(from_node=reshape, to_node=edge.to_node, to_idx=edge.to_idx)) reshape.shape = Dim.unnamed(out_shape) break if set_identity: self.set_identity(G) return modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): nodes = list(G.nodes(node_classes=GlobalPoolingParameters)) modified_graph = False while nodes: node = nodes.pop() node_group = self.reductions(G, node) if len(node_group) <= 1: continue modified_graph = True reduction_axes, new_shape, has_keepdims, _ = reduce( reduce_reduction, node_group, None) new_node = node_group[0] new_node.axis = sorted(list(reduction_axes)) new_node.keep_dims = has_keepdims out_edges = G.out_edges(node_group[-1].name) if G.quantization: last_qrec = G.quantization[NodeId(node_group[-1])] G.quantization[NodeId(new_node)].out_qs = last_qrec.out_qs for node in node_group[1::]: G.remove(node.name) nid = NodeId(node) if G.quantization and nid in G.quantization: del G.quantization[nid] if has_keepdims and len(new_shape) != len( new_node.in_dims[0].shape): rparams = ReshapeParameters( G.unique_name(f'{new_node.name}_reshape'), shape=Dim.unnamed(new_shape)) if G.quantization: G.quantization.copy_qrec(last_qrec, 'out', 0, rparams) G.add_edge(NNEdge(new_node, rparams)) new_node = rparams for edge in out_edges: G.add_edge(NNEdge(new_node, edge.to_node, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): has_modified_graph = False nodes_to_remove = [] for node in G.nodes(node_classes=CopyParameters): out_edges = G.out_edges(node) if len(out_edges) > 1: continue if (search_down( G, out_edges[0], (OutputParameters, InputParameters, ConstantInputParameters, SplitParameters, ConcatParameters), can_pass=(ReshapeParameters, NoOPParameters), can_pass_fn=lambda G, node: isinstance( node, TransposeParameters) and node.does_nothing, follow_multi=True) and search_up( G, G.in_edges(node)[0], (InputParameters, OutputParameters, ConstantInputParameters, SplitParameters, ConcatParameters), can_pass=(ReshapeParameters, NoOPParameters), can_pass_fn=lambda G, node: isinstance( node, TransposeParameters) and node.does_nothing, follow_multi=True)): continue nodes_to_remove.append(node) for node in nodes_to_remove: LOG.info("remove redundant copy %s", node.name) has_modified_graph = True G.remove_and_reconnect(node, edge_class=NNEdge) if G.quantization: nid = NodeId(node) if nid in G.quantization: del G.quantization[nid] if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): modified_graph = False candidates = set(G.nodes(node_classes=(ReshapeParameters, ))) while candidates: node = candidates.pop() out_edges = G.out_edges(node.name) if len(out_edges) != 1 or not isinstance( out_edges[0].to_node, FcParameters) or out_edges[0].to_node.batch_size > 1: continue LOG.info('removing unnecessary reshape before linear %s', node.name) G.remove_and_reconnect(node, edge_class=NNEdge) modified_graph = True nid = NodeId(node) if G.quantization and G.quantization.get(nid): del G.quantization[nid] modified_graph = True if set_identity: self.set_identity(G) return modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): has_modified_graph = False group_identity = kwargs.get('group_identity') if group_identity == 'pow2_match_group': valid_activations = VALID_ACTIVATIONS_POW2 valid_activations_wo_pool = VALID_ACTIVATIONS_POW2_WO_POOL else: valid_activations = VALID_ACTIVATIONS_SQ8 valid_activations_wo_pool = VALID_ACTIVATIONS_SQ8_WO_POOL for pool_node in G.nodes(node_classes=(PoolingParameters, GlobalPoolingParameters)): node_list = self.get_node_list(G, pool_node, valid_activations, valid_activations_wo_pool) if node_list is None or len(node_list.order) < 2: continue LOG.info("fusing nodes %s", ",".join( (node.name for node in node_list.order))) has_modified_graph = True subgraph = GraphView() last_node = None for node in node_list.order: if last_node is not None: subgraph.add_edge(NNEdge(from_node=last_node, to_node=node)) last_node = node input_mapping = [[(node_list.pool, 0)]] output_mapping = [(last_node, 0)] pnode = ActivationFusion(node_list.pool.name + '_fusion', fusion_type=node_list.fusion_type, subgraph=subgraph, input_mapping=input_mapping, output_mapping=output_mapping) if G.quantization: # TODO - stats qrecs = G.quantization.get_all(pnode.contained_nodes()) if qrecs: prec = QRec.copy_ktype(qrecs[0], in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) for node in pnode.contained_nodes(): G.quantization.move_to_fusion(node, pnode) if isinstance(node, GlobalPoolingParameters): # Global pooling fused with activations need to have only the activation scale G.quantization[NodeId(pnode, node)].out_qs[0] = deepcopy( G.quantization[NodeId( pnode, node)].in_qs[0]) G.quantization[NodeId( pnode, node)].out_qs[0].dtype = np.int32 G.quantization[NodeId(pnode)] = prec in_edges = G.in_edges(node_list.pool.name) out_edges = G.out_edges(last_node.name) for node in node_list.order: G.remove(node) for edge in in_edges: G.add_edge( NNEdge(edge.from_node, pnode, from_idx=edge.from_idx, to_idx=edge.to_idx)) for edge in out_edges: G.add_edge( NNEdge(pnode, edge.to_node, from_idx=edge.from_idx, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def match(self, G: GraphView, set_identity: bool = True): has_modified_graph = False for pad_node in [ params for params in G.nodes() if isinstance(params, PadParameters) ]: node_list = self.get_node_list(G, pad_node) if node_list is None or len(node_list.order) < 2: continue LOG.info("fusing nodes %s", ",".join( (node.name for node in node_list.order))) has_modified_graph = True subgraph = GraphView() padded_input_idx = G.out_edges(node_list.pad.name)[0].to_idx subgraph.add_edge( NNEdge(from_node=node_list.pad, to_node=node_list.add, to_idx=padded_input_idx)) last_node = node_list.add node_list.add.force_quantized_index = 0 if node_list.active: subgraph.add_edge( NNEdge(from_node=node_list.add, to_node=node_list.active)) last_node = node_list.active if padded_input_idx == 0: input_mapping = [[(node_list.pad, 0)], [(node_list.add, 1)]] else: input_mapping = [[(node_list.add, 0)], [(node_list.pad, 1)]] output_mapping = [(last_node, 0)] pnode = PaddedAddFusionParameters( "PADDED_" + node_list.add.name, fusion_type=node_list.fusion_type, subgraph=subgraph, input_mapping=input_mapping, output_mapping=output_mapping) if G.quantization: qrecs = G.quantization.get_all(pnode.contained_nodes()) if qrecs: prec = None if isinstance(qrecs[0], (SymmetricQuantizationRecord, SymmetricScalableFilterQuantizationRecord)): prec = SymmetricQuantizationRecord( in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) elif isinstance(qrecs[0], (MultQuantizationRecord, MultScalableFilterQuantizationRecord)): prec = MultQuantizationRecord(in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) elif isinstance(qrecs[0], (Float32QuantizationRecord, Float32ScalableFilterQuantizationRecord)): prec = Float32QuantizationRecord( in_qs=qrecs[0].in_qs, out_qs=qrecs[-1].out_qs) for node in pnode.contained_nodes(): G.quantization.move_to_fusion(node, pnode) G.quantization[NodeId(pnode)] = prec if padded_input_idx == 0: in_edges = G.in_edges(node_list.pad.name) + G.indexed_in_edges( node_list.add.name)[1::] else: in_edges = G.indexed_in_edges( node_list.add.name)[0:1:] + G.in_edges(node_list.pad.name) out_edges = G.out_edges(last_node.name) for node in node_list.order: G.remove(node) for edge in in_edges: G.add_edge( NNEdge(edge.from_node, pnode, from_idx=edge.from_idx, to_idx=edge.to_idx)) for edge in out_edges: G.add_edge( NNEdge(pnode, edge.to_node, from_idx=edge.from_idx, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): has_modified_graph = False filter_nodes = [ node for node in G.nodes() if isinstance(node, FilterParameters) ] for filter_node in filter_nodes: while True: out_edges = G.out_edges(filter_node.name) # can't fuse if there is a branch if len(out_edges) > 1: break out_edge = out_edges[0] op_node = out_edge.to_node # must be a valid matrix op if not isinstance(op_node, tuple(OPS.keys())): break # other edge to the op must be a constant other_idx = 1 if out_edge.to_idx == 0 else 0 other_in_edge = G.indexed_in_edges(op_node.name)[other_idx] if not isinstance(other_in_edge.from_node, ConstantInputParameters): break const_node = other_in_edge.from_node remove_constant = len(G.out_edges(const_node.name)) flat_value = const_node.dqvalue.flatten() out_c = filter_node.filter.out_c op, weights_and_biases = OPS[op_node.__class__] # it would be possible to support mult bias addition by out channel but only supporting a # scalar at present if len(flat_value) != 1 and (weights_and_biases or len(flat_value) != out_c): LOG.warning('could not absorb %s into %s', const_node.name, filter_node.name) break # If there is quantization then essentially the output of the filter # takes the quantization of the output of the operation. # The biases will not change since their quantization depends on the weights # and input fnid = NodeId(filter_node) opnid = NodeId(op_node) if G.quantization and (fnid in G.quantization or opnid in G.quantization): if not (fnid in G.quantization and opnid in G.quantization): LOG.warning( 'could not absorb %s into %s - graph is partially quantized', const_node.name, filter_node.name) break fqrec = G.quantization[fnid] opqrec = G.quantization[opnid] fqrec.out_qs[0] = opqrec.out_qs[0] has_modified_graph = True LOG.info("fusing bias in %s into %s", const_node.name, filter_node.name) self.fuse_bias(G, filter_node, other_idx, op, flat_value, 2) if weights_and_biases: # TODO - need to adjust weights quantization here LOG.info("fusing multiplicative bias in %s into %s", const_node.name, filter_node.name) self.fuse_bias(G, filter_node, other_idx, op, flat_value, 1) out_edges = G.out_edges(op_node.name) G.remove(op_node) if remove_constant: G.remove(const_node) for edge in out_edges: G.add_edge( NNEdge(from_node=filter_node, to_node=edge.to_node, to_idx=edge.to_idx)) if set_identity: self.set_identity(G) return has_modified_graph
def _match(self, G: GraphView, set_identity: bool = True, **kwargs): has_modified_graph = False has_transposed = False for params in G.nodes(node_classes=MatMulOpParameters): while True: out_edges = G.out_edges(params.name) # can't fuse if there is a branch if len(out_edges) > 1: break out_edge = out_edges[0] op_node = out_edge.to_node # must be a valid matrix op if not isinstance(op_node, (MatrixAddParameters, MatrixMulParameters)): break # other edge to the op must be a constant other_idx = 1 if out_edge.to_idx == 0 else 0 other_in_edge = G.indexed_in_edges(op_node.name)[other_idx] if not isinstance(other_in_edge.from_node, ConstantInputParameters): break const_node = other_in_edge.from_node remove_constant = len(G.out_edges(const_node.name)) flat_value = const_node.dqvalue.flatten() out_shape = params.out_dims[0].shape if len(out_shape) != 2: raise ValueError( f'strange outputs shape of {out_shape} for matmul {params.name}' ) if len(flat_value) != out_shape[0] and len( flat_value) != out_shape[1]: LOG.info( "can't fuse %s into %s - value shape is not correct for bias", const_node.name, params.name) break has_bias = len(params.in_dims) == 3 if isinstance(op_node, MatrixAddParameters): if has_bias: if len(flat_value.shape) != len(params.in_dims[2]): LOG.info( "can't fuse %s into %s - bias shape is not the same", const_node.name, params.name) break bias_node = G.indexed_in_edges( params.name)[2].from_node LOG.info( "folding additive bias from %s into existing bias on %s", op_node.name, params.name) bias_node.value = bias_node.dq_value + flat_value else: if len(flat_value) == out_shape[1]: # matmul needs to be transposed to fuse this reverse_matmul(G, params) has_transposed = True bias_node = ConstantInputParameters( G.unique_name(f'{params.name}_bias'), value=flat_value, dims=Dim.unnamed(flat_value.shape)) G.add_edge( NNEdge(from_node=bias_node, to_node=params, to_idx=2)) # extend the inward transpose if params.transpose_in: params.transpose_in = params.transpose_in + [None] LOG.info( "folding additive bias from %s into new bias on %s", op_node.name, params.name) else: params_in = G.indexed_in_edges(params.name) consts = [ isinstance(edge.from_node, ConstantInputParameters) for edge in params_in ] if not any(consts): break mult_const_node = params_in[1].from_node if consts[ 1] else params_in[0].from_node mult_const_node.value = mult_const_node.dqvalue * const_node.dqvalue if has_bias: bias_node = params_in[2].from_node bias_node.value = bias_node.dqvalue * const_node.dqvalue LOG.info( "folding multaplicative bias from %s into new bias on %s", op_node.name, params.name) out_edges = G.out_edges(op_node.name) G.remove(op_node) if remove_constant: G.remove(const_node) for edge in out_edges: G.add_edge( NNEdge(from_node=params, to_node=edge.to_node, to_idx=edge.to_idx)) G.add_dimensions() if G.quantization: quantizer = UnifiedQuantizer.from_quantized_graph(G) quantizer.quantize(G, start_nodes=[params]) RemoveUnnecessaryQuantizeOperators().match(G) if has_transposed: G.adjust_order() if set_identity: self.set_identity(G) return has_modified_graph