Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / MulQuantizeFuse.py
1 """
2  Copyright (c) 2019 Intel Corporation
3
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 """
16
17 import logging as log
18 from typing import Dict
19
20 import numpy as np
21
22 from mo.graph.graph import Graph, Node
23 from mo.middle.passes.conv import get_tensor_in_port, get_value_in_port
24 from mo.middle.replacement import MiddleReplacementPattern
25
26
27 class MulQuantizeFuse(MiddleReplacementPattern):
28     """ Fuses Mul --> Quantize sequence if possible
29     """
30     enabled = False
31
32     def run_after(self):
33         return []
34
35     def run_before(self):
36         return []
37
38     def pattern(self):
39         return dict(
40             nodes=[
41                 ('preop', dict(op='Mul')),
42                 ('preoped', dict()),
43                 ('quantize', dict(op='Quantize')),
44             ],
45             edges=[
46                 ('preop', 'preoped'),
47                 ('preoped', 'quantize', {'in': 0}),
48             ]
49         )
50
51     def replace_pattern(self, graph: Graph, match: Dict[str, Node]):
52         quantize = match['quantize']
53         preop = match['preop']
54
55         # Check for total number of Mul consumers -- if something else consume its output it cannot be fused
56         if len(preop.out_node().out_nodes()) > 1:
57             log.debug('MulQuantizeFuse: cannot fuse because Mul have multiple consumers')
58             return
59
60         # If the fusion is applicable, direct modifications to quantize 1-st and 2-nd inputs
61         # are performed. So the data nodes at those inputs shouldn't have more than 1 consumer
62         # maximum 2 consumers to the same quantize op (consumed by 1st and 2nd ports).
63         # TODO: relax this limitation and duplicate data nodes accordingly to modify the input range freely
64
65         # Provisional limitation that related to binary quantization
66         # TODO: Relax it beyond binarization case
67         # Provisional limitation that related to binary quantization
68         # TODO: Relax it beyond binarization case
69         if len(quantize.in_node(1).out_nodes()) != 1 or \
70                 len(quantize.in_node(2).out_nodes()) != 1 or \
71                 len(quantize.in_node(3).out_nodes()) != 1 or len(quantize.in_node(4).out_nodes()) != 1 or \
72                 quantize.levels != 2:
73             log.debug('MulQuantizeFuse: cannot fuse because Quantize op has '
74                       'unexpected number of consumers for ports 1, 2, 3 or 4')
75             return
76
77         tensor_port, value_port = get_tensor_in_port(preop), get_value_in_port(preop)
78
79
80         # Need to flip output_low and output_high for those elements that have multiplier < 0
81         # TODO: need some special processing for values that exactly equal to threshold
82         if np.all(value_port.data.get_value() <= 0):
83             log.debug('MulQuantizeFuse: cannot fuse because Mul op has non-positive multipliers.')
84
85         quantize.in_port(1).data.set_value(quantize.in_port(1).data.get_value() / value_port.data.get_value())
86         quantize.in_port(2).data.set_value(quantize.in_port(2).data.get_value() / value_port.data.get_value())
87
88         # Remove Mul as it no longer needed
89         quantize.in_port(0).disconnect()
90         tensor_port.get_connection().set_destination(quantize.in_port(0))