Skip to content

Commit

Permalink
[QNN][Legalize] Specialize for Platforms without any fast Int8 arithm…
Browse files Browse the repository at this point in the history
…etic units.
  • Loading branch information
anijain2305 committed Nov 11, 2019
1 parent 10b77ef commit 7025a08
Show file tree
Hide file tree
Showing 2 changed files with 317 additions and 32 deletions.
196 changes: 170 additions & 26 deletions python/tvm/relay/qnn/op/legalizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,43 @@
from tvm import relay
from .. import op as reg

#################################################
# Register the functions for different operators.
#################################################

# Registering QNN Conv2D legalization function.
@reg.register_qnn_legalize("qnn.conv2d")
def legalize_qnn_conv2d(attrs, inputs, types):
"""Legalizes QNN conv2d op.
return qnn_conv2d_legalize(attrs, inputs, types)

# Registering QNN dense legalization function.
@reg.register_qnn_legalize("qnn.dense")
def legalize_qnn_dense(attrs, inputs, types):
return qnn_dense_legalize(attrs, inputs, types)

# Default to None. If overridden by target, this will not be run.
# Generic QNN Conv2D legalization function.
@tvm.target.generic_func
def qnn_conv2d_legalize(attrs, inputs, types):
"""Default legalization is None."""
return None

# Generic QNN Conv2D legalization function.
@tvm.target.generic_func
def qnn_dense_legalize(attrs, inputs, types):
"""Default legalization is None."""
return None

###################
# Helper functions.
###################

# Helper function for lowering in the abscence of fast Int8 arithmetic units.
def helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay_op):
""" Converts QNN operators into a sequence of Relay operators that are friendly to HW that do
not have fast Int8 arithmetic. For example, for ARM, LLVM utilizes the assembly instructions
much more efficiently if the convolution or dense operator input datatypes are int16 instead of
int8. More details are present at https://github.com/apache/incubator-tvm/pull/4277.
Parameters
----------
Expand All @@ -41,19 +74,27 @@ def legalize_qnn_conv2d(attrs, inputs, types):
result : tvm.relay.Expr
The legalized expr
"""
return qnn_conv2d_legalize(attrs, inputs, types)

# Generic QNN Conv2D legalization function.
@tvm.target.generic_func
def qnn_conv2d_legalize(attrs, inputs, types):
"""Default legalization is None."""
return None
# Collect the input exprs.
data, kernel = inputs

# Intel x86 QNN Conv2D legalization function.
@qnn_conv2d_legalize.register('cpu')
def _qnn_conv2d_legalize(attrs, inputs, types):
"""Legalizes QNN conv2d op. VNNI supports u8 x i8 fast conv/MM. If the dtypes are already good,
we dont transform. Else, we shift the tensor values and zero points to change the dtype.
input_zp = attrs['input_zero_point']
kernel_zp = attrs['kernel_zero_point']

shift_data = relay.subtract(relay.cast(data, dtype='int16'),
relay.const(input_zp, 'int16'))
shift_kernel = relay.subtract(relay.cast(kernel, dtype='int16'),
relay.const(kernel_zp, 'int16'))
new_attrs = {k : attrs[k] for k in attrs.keys()}
del new_attrs['kernel_zero_point']
del new_attrs['input_zero_point']
return relay_op(shift_data, shift_kernel, **new_attrs)

# Helper function to change dtypes to uint8 x int8. Intel VNNI instructions prefer this setting.
def helper_change_dtypes_to_uint8_int8(attrs, inputs, types, relay_op):
"""Legalizes QNN conv2d/dense op for Intel HW. VNNI supports u8 x i8 fast conv/MM. If the dtypes
are already good, we dont transform. Else, we shift the tensor values and zero points to change
the dtype.
Converting from int8 to uint8 can be done in following manner.
Expand Down Expand Up @@ -95,26 +136,13 @@ def _shift(data, out_dtype):
data_modified = relay.cast(data_modified, out_dtype)
return data_modified

def _is_int8_hw_support(target):
"""
Checks to ensure that we can use Intel DLBoost instructions - Check if the target is skylake
and above.
"""
supported_arches = {'-mcpu=skylake-avx512', '-mcpu=cascadelake'}
return supported_arches.intersection(set(target.options))

# Collect the dtypes.
data_dtype = types[0].dtype
kernel_dtype = types[1].dtype

# Collect the input exprs.
data, kernel = inputs

# The VNNI transformations are applicable only Skylake and above.g
target = tvm.target.current_target(allow_none=False)
if not _is_int8_hw_support(target):
return None

# VNNI supports u8 x i8 fast conv/MM. Don't do anything if it is already satisfied.
if data_dtype == 'uint8' and kernel_dtype == 'int8':
return None
Expand All @@ -137,4 +165,120 @@ def _is_int8_hw_support(target):
new_attrs = {k : attrs[k] for k in attrs.keys()}
new_attrs['input_zero_point'] = input_zp
new_attrs['kernel_zero_point'] = kernel_zp
return relay.qnn.op.conv2d(data, kernel, **new_attrs)
return relay_op(data, kernel, **new_attrs)

# Helper function to change dtypes to be same. ARM dotprod instructions prefer this setting.
def helper_change_dtypes_to_be_same(attrs, inputs, types, relay_op):
""" Sometimes MxNet + MLDNN can lead to uint8 x int8 datatypes for the conv inputs. However,
many devices like ARM prefer the datatypes to be same for the HW units. This helper transforms
conv2d/dense such that both the dtypes are same.
Parameters
----------
attrs : tvm.attrs.Attrs
Attributes of current convolution
inputs : list of tvm.relay.Expr
The args of the Relay expr to be legalized
types : list of types
List of input and output types
Returns
-------
result : tvm.relay.Expr
The legalized expr
"""

def _shift(data, out_dtype):
"""Shifts (add/subtracts) the qnn tensor with +/-128)"""
if out_dtype == 'uint8':
shift = 128
elif out_dtype == 'int8':
shift = -128
else:
raise ValueError("Unsupport out dtype.")
data_modified = relay.cast(data, 'int32')
data_modified = relay.add(data_modified, relay.const(shift, 'int32'))
data_modified = relay.cast(data_modified, out_dtype)
return data_modified

# Collect the dtypes.
data_dtype = types[0].dtype
kernel_dtype = types[1].dtype

# Collect the input exprs.
data, kernel = inputs

# VNNI supports u8 x i8 fast conv/MM. Don't do anything if it is already satisfied.
if data_dtype == kernel_dtype:
return None

assert 'int8' in data_dtype and 'int8' in kernel_dtype, \
"Qnn Conv2D only accepts uint8 or int8 inputs"

# Shift input if necessary.
input_zp = attrs['input_zero_point']
data = _shift(data, kernel_dtype)
if data_dtype == 'int8':
input_zp = input_zp + 128
elif data_dtype == 'uint8':
input_zp = input_zp - 128
else:
raise RuntimeError("Qnn Conv2D only accepts uint8 or int8 inputs")

# Call qnn.conv2d with modified inputs and zero points.
new_attrs = {k : attrs[k] for k in attrs.keys()}
new_attrs['input_zero_point'] = input_zp
return relay_op(data, kernel, **new_attrs)

def is_fast_int8_hw_present():
"""
Checks to ensure that we can use Intel DLBoost instructions - Check if the target is skylake
and above.
"""
target = tvm.target.current_target(allow_none=False)
intel_supported_arches = {'-mcpu=skylake-avx512', '-mcpu=cascadelake'}
is_present_intel = intel_supported_arches.intersection(set(target.options))

arm_supported_attr = '+v8.2a,+dotprod'
is_present_arm = False
for opt in target.options:
if arm_supported_attr in opt:
is_present_arm = True

return is_present_intel or is_present_arm

########################
# ARM CPU legalizations.
########################

@qnn_conv2d_legalize.register('arm_cpu')
def _qnn_conv2d_legalize_arm_cpu(attrs, inputs, types):
# ARM likes the dtypes to be same.
if is_fast_int8_hw_present():
return helper_change_dtypes_to_be_same(attrs, inputs, types, relay.qnn.op.conv2d)
return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.conv2d)

@qnn_dense_legalize.register('arm_cpu')
def _qnn_dense_legalize_arm_cpu(attrs, inputs, types):
# ARM likes the dtypes to be same.
if is_fast_int8_hw_present():
return helper_change_dtypes_to_be_same(attrs, inputs, types, relay.qnn.op.dense)
return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.dense)

##########################
# Intel CPU legalizations.
##########################

@qnn_conv2d_legalize.register('cpu')
def _qnn_conv2d_legalize_intel_cpu(attrs, inputs, types):
# The VNNI transformations prefer uint8 x int8 datatypes.
if is_fast_int8_hw_present():
return helper_change_dtypes_to_uint8_int8(attrs, inputs, types, relay.qnn.op.conv2d)
return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.conv2d)

@qnn_dense_legalize.register('cpu')
def _qnn_dense_legalize_intel_cpy(attrs, inputs, types):
# The VNNI transformations prefer uint8 x int8 datatypes.
if is_fast_int8_hw_present():
return helper_change_dtypes_to_uint8_int8(attrs, inputs, types, relay.qnn.op.dense)
return helper_no_fast_int8_hw_legalization(attrs, inputs, types, relay.nn.dense)
Loading

0 comments on commit 7025a08

Please sign in to comment.