test_pass_qnn_legalize.py 11.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
"""Test legalize pass"""
import numpy as np
import tvm

from tvm import relay
from tvm.contrib import graph_runtime
from tvm.relay import transform, analysis
24
from tvm.relay.testing.temp_op_attr import TempOpAttr
25

26 27 28 29 30 31 32 33
def alpha_equal(x, y):
    """
    Wrapper around alpha equality which ensures that
    the hash function respects equality.
    """
    x = x['main']
    y = y['main']
    return analysis.alpha_equal(x, y) and analysis.structural_hash(x) == analysis.structural_hash(y)
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

def run_opt_pass(expr, passes):
    passes = passes if isinstance(passes, list) else [passes]
    mod = relay.Module.from_expr(expr)
    seq = transform.Sequential(passes)
    with transform.PassContext(opt_level=3):
        mod = seq(mod)
    entry = mod["main"]
    return entry if isinstance(expr, relay.Function) else entry.body

def test_qnn_legalize():
    """Test directly replacing an operator with a new one"""
    def before():
        x = relay.var("x", shape=(1, 64, 56, 56), dtype='int8')
        y = relay.qnn.op.requantize(x,
49 50 51 52
                                    input_scale=relay.const(1, 'float32'),
                                    input_zero_point=relay.const(0, 'int32'),
                                    output_scale=relay.const(1, 'float32'),
                                    output_zero_point=relay.const(0, 'int32'),
53 54 55 56 57 58 59 60
                                    out_dtype='int8')
        y = relay.Function([x], y)
        return y

    def legalize_qnn_requantize(attrs, inputs, types):
        data = inputs[0]
        data = relay.add(relay.const(0, 'int8'), data)
        y = relay.qnn.op.requantize(data,
61 62 63 64
                                    input_scale=relay.const(1, 'float32'),
                                    input_zero_point=relay.const(0, 'int32'),
                                    output_scale=relay.const(1, 'float32'),
                                    output_zero_point=relay.const(0, 'int32'),
65 66 67 68 69 70 71
                                    out_dtype='int8')
        return y

    def expected():
        x = relay.var("x", shape=(1, 64, 56, 56), dtype='int8')
        y = relay.add(relay.const(0, 'int8'), x)
        z = relay.qnn.op.requantize(y,
72 73 74 75
                                    input_scale=relay.const(1, 'float32'),
                                    input_zero_point=relay.const(0, 'int32'),
                                    output_scale=relay.const(1, 'float32'),
                                    output_zero_point=relay.const(0, 'int32'),
76 77 78 79 80 81
                                    out_dtype='int8')
        z = relay.Function([x], z)
        return z

    a = before()

82
    with TempOpAttr("qnn.requantize", "FTVMQnnLegalize", legalize_qnn_requantize):
83

84 85 86 87 88 89 90 91 92
        # Check that Relay Legalize does not change the graph.
        a = run_opt_pass(a, relay.transform.Legalize())
        b = run_opt_pass(before(), transform.InferType())
        assert analysis.alpha_equal(a, b), "Actual = \n" + str(a)

        # Check that QNN Legalize modifies the graph.
        a = run_opt_pass(a, relay.qnn.transform.Legalize())
        b = run_opt_pass(expected(), transform.InferType())
        assert analysis.alpha_equal(a, b), "Actual = \n" + str(a)
93

94

95
def test_qnn_legalize_qnn_conv2d():
96 97 98
    def _get_mod(data_dtype, kernel_dtype):
        data_shape = (1, 64, 256, 256)
        kernel_shape = (128, 64, 3, 3)
99 100 101 102 103 104
        data = relay.var("data", shape=data_shape,
                dtype=data_dtype)
        kernel = relay.var("kernel", shape=kernel_shape,
                dtype=kernel_dtype)
        func = relay.qnn.op.conv2d(
                data, kernel,
105 106 107 108
                input_zero_point=relay.const(1, 'int32'),
                kernel_zero_point=relay.const(1, 'int32'),
                input_scale=relay.const(1.0, 'float32'),
                kernel_scale=relay.const(1.0, 'float32'),
109 110 111 112 113 114 115 116 117
                kernel_size=(3, 3),
                strides=(1, 1),
                dilation=(1, 1),
                out_dtype='int32',
                data_layout='NCHW',
                kernel_layout='OIHW')

        mod = relay.Function(relay.analysis.free_vars(func), func)
        mod = relay.Module.from_expr(mod)
118 119 120 121 122
        return mod

    # Check uint8 x uint8 and int8 x int8 transformation
    for dtype in ('uint8', 'int8'):
        mod = _get_mod(dtype, dtype)
123

124 125 126 127
        #############################################################
        # Check transformations for platforms with fast Int8 support.
        #############################################################
        # Check that Intel VNNI gets picked up.
128
        with tvm.target.create('llvm -mcpu=skylake-avx512'):
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
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert 'cast' in legalized_mod.astext() and "qnn.conv2d" in legalized_mod.astext()

        # Since same dtype, there should not be any transformation
        with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu -mattr=+v8.2a,+dotprod'):
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert alpha_equal(mod, legalized_mod)

        ################################################################
        # Check transformations for platforms without fast Int8 support.
        ################################################################
        # Older Intel versions.
        with tvm.target.create('llvm'):
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()

        # Older ARM vesions.
        with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu'):
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()

    # Check uint8 x int8 transformation
    mod = _get_mod('uint8', 'int8')
    #############################################################
    # Check transformations for platforms with fast Int8 support.
    #############################################################
    # Check no transformation for Intel VNNI.
    with tvm.target.create('llvm -mcpu=skylake-avx512'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert alpha_equal(mod, legalized_mod)

    # ARM - so check that transformation has happened.
    with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu -mattr=+v8.2a,+dotprod'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert 'cast' in legalized_mod.astext() and "qnn.conv2d" in legalized_mod.astext()

    ################################################################
    # Check transformations for platforms without fast Int8 support.
    ################################################################
    # Older Intel versions.
    with tvm.target.create('llvm'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()

    # Older ARM vesions.
    with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()


def test_qnn_legalize_qnn_dense():
    def _get_mod(data_dtype, kernel_dtype):
        data_shape = (10, 3)
        kernel_shape = (20, 3)
        data = relay.var("data", shape=data_shape,
                dtype=data_dtype)
        kernel = relay.var("kernel", shape=kernel_shape,
                dtype=kernel_dtype)
        func = relay.qnn.op.dense(
                data, kernel,
189 190 191 192
                input_zero_point=relay.const(1, 'int32'),
                kernel_zero_point=relay.const(1, 'int32'),
                input_scale=relay.const(1, 'float32'),
                kernel_scale=relay.const(1, 'float32'),
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
                out_dtype='int32')

        mod = relay.Function(relay.analysis.free_vars(func), func)
        mod = relay.Module.from_expr(mod)
        return mod

    # Check uint8 x uint8 and int8 x int8 transformation
    for dtype in ('uint8', 'int8'):
        mod = _get_mod(dtype, dtype)

        #############################################################
        # Check transformations for platforms with fast Int8 support.
        #############################################################
        # Check that Intel VNNI gets picked up.
        with tvm.target.create('llvm -mcpu=skylake-avx512'):
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert 'cast' in legalized_mod.astext() and "qnn.dense" in legalized_mod.astext()

        # Since same dtype, there should not be any transformation
        with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu -mattr=+v8.2a,+dotprod'):
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert alpha_equal(mod, legalized_mod)

        ################################################################
        # Check transformations for platforms without fast Int8 support.
        ################################################################
        # Older Intel versions.
        with tvm.target.create('llvm'):
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()

        # Older ARM vesions.
        with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu'):
            legalized_mod = relay.qnn.transform.Legalize()(mod)
            assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()

    # Check uint8 x int8 transformation
    mod = _get_mod('uint8', 'int8')
    #############################################################
    # Check transformations for platforms with fast Int8 support.
    #############################################################
    # Check no transformation for Intel VNNI.
    with tvm.target.create('llvm -mcpu=skylake-avx512'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert alpha_equal(mod, legalized_mod)

    # ARM - so check that transformation has happened.
    with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu -mattr=+v8.2a,+dotprod'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert 'cast' in legalized_mod.astext() and "qnn.dense" in legalized_mod.astext()

    ################################################################
    # Check transformations for platforms without fast Int8 support.
    ################################################################
    # Older Intel versions.
    with tvm.target.create('llvm'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()

    # Older ARM vesions.
    with tvm.target.create('llvm -device=arm_cpu -target=aarch64-linux-gnu'):
        legalized_mod = relay.qnn.transform.Legalize()(mod)
        assert 'cast' in legalized_mod.astext() and "qnn" not in legalized_mod.astext()
256 257


258 259
if __name__ == "__main__":
    test_qnn_legalize()
260
    test_qnn_legalize_qnn_conv2d()
261
    test_qnn_legalize_qnn_dense()