Skip to content

Commit

Permalink
[BYOC][Contrib] Arm Compute Library integration
Browse files Browse the repository at this point in the history
Arm Compute Library (ACL) integration using the BYOC infrastructure. This will enable offloading select operators from a relay
graph to ACL so we can achieve faster inference times on Arm CPU's due to hand crafted optimized routines. The PR adds initial
support for offloading FP32 conv2d, maxpool2d and reshape to ACL. ACL codegen is used to generate a JSON representation of an
operator or 'ACL layer', the ACL runtime then uses this representation to construct a layer, cache it and create a packed
function to for the graph runtime to call into.

RFC here: https://discuss.tvm.ai/t/rfc-byoc-arm-compute-library-integration/7082

Change-Id: If756dcea787ea346b1508e9a191b7eed7bd02b7f
  • Loading branch information
lhutton1 committed Jul 10, 2020
1 parent 8a0249c commit 454fa3b
Show file tree
Hide file tree
Showing 24 changed files with 2,700 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ tvm_option(USE_CPP_RPC "Build CPP RPC" OFF)
tvm_option(USE_TFLITE "Build with tflite support" OFF)
tvm_option(USE_TENSORFLOW_PATH "TensorFlow root path when use TFLite" none)
tvm_option(USE_COREML "Build with coreml support" OFF)
tvm_option(USE_ACL "Build with Arm Compute Library" OFF)
tvm_option(USE_ACL_GRAPH_RUNTIME "Build with Arm Compute Library graph runtime" OFF)

if(USE_CPP_RPC AND UNIX)
message(FATAL_ERROR "USE_CPP_RPC is only supported with WIN32. Use the Makefile for non-Windows.")
Expand Down Expand Up @@ -327,6 +329,7 @@ include(cmake/modules/contrib/HybridDump.cmake)
include(cmake/modules/contrib/TFLite.cmake)
include(cmake/modules/contrib/TF_TVMDSOOP.cmake)
include(cmake/modules/contrib/CoreML.cmake)
include(cmake/modules/contrib/ACL.cmake)

include(CheckCXXCompilerFlag)
if(NOT MSVC)
Expand Down
12 changes: 12 additions & 0 deletions cmake/config.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,18 @@ set(USE_SORT ON)
# Whether use MKL-DNN (DNNL) codegen
set(USE_DNNL_CODEGEN OFF)

# Whether to use ACL (Arm Compute Library) codegen
# We provide 2 separate flags since we cannot build the ACL runtime on x86.
# This is useful for cases where you want to cross-compile a relay graph
# on x86 then run on AArch.
#
# USE_ACL - Support for compiling a relay graph offloading supported
# operators to ACL. OFF/ON
# USE_ACL_GRAPH_RUNTIME - Run ACL annotated functions via the ACL
# runtime. OFF/ON/"path/to/ACL"
set(USE_ACL OFF)
set(USE_ACL_GRAPH_RUNTIME OFF)

# Build ANTLR parser for Relay text format
# Possible values:
# - ON: enable ANTLR by searching default locations (cmake find_program for antlr4 and /usr/local for jar)
Expand Down
68 changes: 68 additions & 0 deletions cmake/modules/contrib/ACL.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# 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.

# We separate the codegen and runtime build since ACL can only be built
# for AArch. In the world where we take the cross compilation approach,
# which is common with arm devices, we need to be able to cross-compile
# a relay graph on x86 for AArch and then run the graph on AArch.
if(USE_ACL)
file(GLOB ACL_RELAY_CONTRIB_SRC src/relay/backend/contrib/acl/*.cc)
file(GLOB ACL_RUNTIME_MODULE src/runtime/contrib/acl/acl_runtime.cc)
list(APPEND COMPILER_SRCS ${ACL_RELAY_CONTRIB_SRC})
list(APPEND COMPILER_SRCS ${ACL_RUNTIME_MODULE})
message(STATUS "Build with ACL support...")
endif()

if(USE_ACL_GRAPH_RUNTIME)
set(ACL_PATH ${CMAKE_CURRENT_SOURCE_DIR}/acl)
# Detect custom ACL path.
if (NOT USE_ACL_GRAPH_RUNTIME STREQUAL "ON")
set(ACL_PATH ${USE_ACL_GRAPH_RUNTIME})
endif()

file(GLOB ACL_CONTRIB_SRC src/runtime/contrib/acl/*)
file(GLOB ACL_API src/relay/backend/contrib/acl/acl_api.cc)

set(ACL_INCLUDE_DIRS ${ACL_PATH}/include ${ACL_PATH})
include_directories(${ACL_INCLUDE_DIRS})

find_library(EXTERN_ACL_COMPUTE_LIB
NAMES arm_compute libarm_compute
HINTS "${ACL_PATH}" "${ACL_PATH}/lib" "${ACL_PATH}/build"
)
find_library(EXTERN_ACL_COMPUTE_CORE_LIB
NAMES arm_compute_core libarm_compute_core
HINTS "${ACL_PATH}" "${ACL_PATH}/lib" "${ACL_PATH}/build"
)
find_library(EXTERN_ACL_COMPUTE_GRAPH_LIB
NAMES arm_compute_graph libarm_compute_graph
HINTS "${ACL_PATH}" "${ACL_PATH}/lib" "${ACL_PATH}/build"
)

list(APPEND TVM_RUNTIME_LINKER_LIBS ${EXTERN_ACL_COMPUTE_LIB})
list(APPEND TVM_RUNTIME_LINKER_LIBS ${EXTERN_ACL_COMPUTE_CORE_LIB})
list(APPEND TVM_RUNTIME_LINKER_LIBS ${EXTERN_ACL_COMPUTE_GRAPH_LIB})
list(APPEND RUNTIME_SRCS ${ACL_CONTRIB_SRC})
list(APPEND RUNTIME_SRCS ${ACL_API})
message(STATUS "Build with ACL graph runtime support: "
${EXTERN_ACL_COMPUTE_LIB} ", \n"
${EXTERN_ACL_COMPUTE_CORE_LIB} ", \n"
${EXTERN_ACL_COMPUTE_GRAPH_LIB})

# Set flag to detect ACL graph runtime support.
add_definitions(-DTVM_GRAPH_RUNTIME_ACL)
endif()
1 change: 1 addition & 0 deletions python/tvm/relay/op/contrib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
"""Contrib modules."""
from .register import get_pattern_table, register_pattern_table

from .acl import *
from .dnnl import *
from .coreml import *
125 changes: 125 additions & 0 deletions python/tvm/relay/op/contrib/acl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# 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.
# pylint: disable=invalid-name, unused-argument
"""ACL library supported operators."""
import tvm
from tvm.relay import transform
from tvm.relay.build_module import bind_params_by_name

from ...dataflow_pattern import wildcard, is_op, is_constant
from .register import register_pattern_table


def is_acl_runtime_present():
"""Check if the ACL graph runtime is present.
Returns
-------
ret: bool
True if present, False if not.
"""
return tvm.get_global_func("relay.op.is_acl_runtime_enabled", True)


def partition_for_acl(mod, params=None):
"""Partition the graph greedily offloading supported
operators to ACL.
Parameters
----------
mod : Module
The module to run passes on.
params : dict[str, NDArray]
Constant input parameters.
Returns
-------
ret : annotated and partitioned module.
"""
if params:
mod['main'] = bind_params_by_name(mod['main'], params)

seq = tvm.transform.Sequential([transform.MergeComposite(pattern_table()),
transform.AnnotateTarget('acl'),
transform.PartitionGraph()])

return seq(mod)


@register_pattern_table("acl")
def pattern_table():
"""Get the ACL pattern table."""

def conv_pattern():
"""Create a convolution pattern.
Returns
-------
pattern : dataflow_pattern.AltPattern
Denotes the convolution pattern.
"""
pattern = is_op('nn.pad')(wildcard()) | wildcard()
pattern = is_op('nn.conv2d')(pattern, is_constant())
pattern = pattern.optional(lambda x: is_op('nn.bias_add')(x, is_constant()))
pattern = pattern.optional(is_op('nn.relu'))
return pattern

def check_conv(extract):
"""Check conv pattern is supported by ACL."""
call = extract
while call.op.name != "nn.conv2d":
call = call.args[0]
return conv2d(call.attrs, call.args)

return [('acl.conv2d', conv_pattern(), check_conv)]


def _register_external_op_helper(op_name, supported=True):
@tvm.ir.register_op_attr(op_name, "target.acl")
def _func_wrapper(attrs, args):
return supported

return _func_wrapper


_register_external_op_helper("reshape")


@tvm.ir.register_op_attr("nn.conv2d", "target.acl")
def conv2d(attrs, args):
"""Check if the external ACL codegen for conv2d should be used."""

# ACL only supports group size of 1
if attrs.groups != 1:
return False

# ACL only supports NHWC layout
if attrs.data_layout != "NHWC":
return False

return True


@tvm.ir.register_op_attr("nn.max_pool2d", "target.acl")
def max_pool2d(attrs, args):
"""Check if the external ACL codegen for maxpool2d should be used."""

# ACL only supports NHWC layout
if attrs.layout != "NHWC":
return False

return True
111 changes: 111 additions & 0 deletions src/relay/backend/contrib/acl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<!---
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.
-->

# Relay Arm&reg; Compute Library Integration
Arm Compute Library (ACL) is an open source project that provides accelerated kernels for Arm CPU's
and GPU's. Currently the integration offloads operators to ACL to use hand-crafted assembler
routines in the library. By offloading select operators from a relay graph to ACL we can achieve
a performance boost on such devices.

## Building with ACL support
The current implementation has two separate build options in cmake. The reason for this split is
because ACL cannot be used on an x86 machine. However, we still want to be able compile an ACL
runtime module on an x86 machine.

* USE_ACL=ON/OFF - Enabling this flag will add support for compiling an ACL runtime module.
* USE_GRAPH_RUNTIME_ACL=ON/OFF/path-to-acl - Enabling this flag will allow the graph runtime to
compute the ACL offloaded functions.

These flags can be used in different scenarios depending on your setup. For example, if you want
to compile ACL on an x86 machine and then run the module on a remote Arm device via RPC, you will
need to use USE_ACL=ON on the x86 machine and USE_GRAPH_RUNTIME_ACL=ON on the remote AArch64
device.
## Usage
_Note:_ this may not stay up-to-date with changes to the API.
1. Create a relay graph. This may be a single operator or a whole graph. The intention is that any
relay graph can be input. The ACL integration will only pick supported operators to be offloaded
whilst the rest will be computed via TVM. (For this example we will use a single
max_pool2d operator).
```
import tvm
from tvm import relay

data_type = "float32"
data_shape = (1, 14, 14, 512)
strides = (2, 2)
padding = (0, 0, 0, 0)
pool_size = (2, 2)
layout = "NHWC"
output_shape = (1, 7, 7, 512)

data = relay.var('data', shape=data_shape, dtype=data_type)
out = relay.nn.max_pool2d(data, pool_size=pool_size, strides=strides,
layout=layout, padding=padding)
module = tvm.IRModule.from_expr(out)
```
2. Annotate and partition the graph for ACL.
```
module = relay.transform.AnnotateTarget("acl")(module)
module = relay.transform.PartitionGraph()(module)
```
3. Build the Relay graph.
```
target = "llvm -target=aarch64-linux-gnu -mattr=+neon"
with relay.build_config(opt_level=3, disabled_pass=["AlterOpLayout"]):
json, lib, params = relay.build(module, target=target)
```
4. Export the module.
```
lib_path = '~/lib_acl.so'
cross_compile = 'aarch64-linux-gnu-c++'
lib.export_library(lib_path, cc=cross_compile)
```
5. Run Inference. This must be on an Arm device. If compiling on x86 device and running on aarch64
consider using the RPC mechanism.
```
tvm.runtime.load_module('lib_acl.so')
gen_module = tvm.contrib.graph_runtime.create(json, lib, ctx)
d_data = np.random.uniform(0, 1, data_shape).astype(data_type)
map_inputs = {'data': d_data}
gen_module.map_inputs(**map_inputs)
gen_module.run()
```
## More examples
The example above only shows a basic example of how ACL can be used for offloading a single
Maxpool2D. If you would like to see more examples for each implemented operator and for
networks refer to the tests: `tests/python/contrib/test_acl`. Here you can modify
`infrastructure.py` to use the remote device you have setup.
## Adding a new operator
Adding a new operator requires changes to a series of places. This section will give a hint on
what needs to be changed and where, it will not however dive into the complexities for an
individual operator. This is left to the developer.
There are a series of files we need to make changes to:
* `python/relay/op/contrib/acl.py` In this file we define the operators we wish to offload using the
`op.register` decorator. This will mean the annotation pass recognizes this operator as ACL
offloadable.
* `src/relay/backend/contrib/acl/codegen_acl.h` Implement `Make[OpName]` method. This is where we
declare how the operator should be represented by JSON. This will be used to create the ACL module.
* `src/runtime/contrib/acl/acl_kernel.h` Implement `Create[OpName]Layer` method. This is where we
define how the JSON representation can be used to create an ACL function. We simply define how to
translate from the JSON representation to ACL API.
* `tests/python/contrib/test_acl` Add unit tests for the given operator.
Loading

0 comments on commit 454fa3b

Please sign in to comment.