Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,3 +43,6 @@
[submodule "examples/demo-apps/android/jni/third-party/fbjni"]
path = examples/demo-apps/android/jni/third-party/fbjni
url = https://github.com/facebookincubator/fbjni.git
[submodule "backends/arm/third-party/ethos-u-core-driver"]
path = backends/arm/third-party/ethos-u-core-driver
url = https://git.mlplatform.org/ml/ethos-u/ethos-u-core-driver.git
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line numberDiff line numberDiff line change
Expand Up@@ -334,6 +334,13 @@ if(EXECUTORCH_BUILD_QNN)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/qualcomm)
endif()

# Build Arm Baremetal backend
option(EXECUTORCH_BUILD_ARM_BAREMETAL
Comment thread
robell marked this conversation as resolved.
"Build the Arm Baremetal flow for Cortex-M and Ethos-U" OFF)
if(EXECUTORCH_BUILD_ARM_BAREMETAL)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/backends/arm)
endif()

# Add selective build subdirectory
if(BUILD_SELECTIVE_BUILD_TEST)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/examples/selective_build)
Expand Down
36 changes: 36 additions & 0 deletions backends/arm/CMakeLists.txt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
cmake_minimum_required(VERSION 3.19)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Source root directory for executorch.
if(NOT EXECUTORCH_ROOT)
set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
endif()

include(${EXECUTORCH_ROOT}/build/Utils.cmake)

set(_common_include_directories ${EXECUTORCH_ROOT}/..)

include(cmake/Dependencies.cmake)

set(_arm_baremetal_sources backends/arm/runtime/ArmBackendEthosU.cpp)
list(TRANSFORM _arm_baremetal_sources PREPEND "${EXECUTORCH_ROOT}/")

add_library(
executorch_delegate_ethos_u
Comment thread
digantdesai marked this conversation as resolved.
STATIC ${_arm_baremetal_sources}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${_common_include_directories}
)
target_include_directories(
executorch_delegate_ethos_u
PUBLIC
${DRIVER_ETHOSU_INCLUDE_DIR}
)
113 changes: 100 additions & 13 deletions backends/arm/arm_backend.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
import logging
import operator
import os
import struct
import subprocess
import tempfile
from typing import final, List

Expand DownExpand Up@@ -136,13 +138,89 @@ def dbg_tosa_dump(tosa_fb, path):
fb = tosa_fb.serialize()
js = tosa_fb.writeJson(filename)

f = open(path + filename, "wb")
f.write(fb)
f.close()
with open(path + filename, "wb") as f:
f.write(fb)

f = open(path + "desc.json", "w")
f.write(js)
f.close()
with open(path + "desc.json", "w") as f:
f.write(js)


# Output to Vela with current file-based compilation
# WARNING: if this changes, the runtime reader also needs to change
def vela_compile(tosa_fb):
with tempfile.TemporaryDirectory() as tmpdir:
tosaname = "out.tosa"
flatbuffer = tosa_fb.serialize()
with open(os.path.join(tmpdir, tosaname), "wb") as f:
f.write(flatbuffer)

# invoke vela
vela_command = (
f"cd {tmpdir}; vela --accelerator-config ethos-u55-128 {tosaname}"
)
subprocess.run([vela_command], shell=True, check=True)

np_path = os.path.join(tmpdir, "output", "out_sg0_vela.npz")
Comment thread
digantdesai marked this conversation as resolved.
blocks = b""
with np.load(np_path, allow_pickle=False) as data:
# Emit the NPZ regions as:
# - 16 byte block name null terminated string (padded to 16 if name shorter)
# - 4 bytes of int32 block length and 12 bytes of 0's
# - block data (padded to 16 byte alignment at end)
# Repeat for all blocks
for key in data.keys():
Comment thread
robell marked this conversation as resolved.
Comment thread
digantdesai marked this conversation as resolved.
block_name = bytes(key, "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))

block_data = b""
if key in ("input_shape", "output_shape"):
inputs = data[key]
# Encode a struct of int len; and one or more int x,y,z,w shape;
input_struct = struct.pack("<i", len(inputs))
for inp in inputs:
assert len(inp) <= 4
inp_pad = inp.tolist() + [0] * (4 - len(inp))
input_struct = input_struct + struct.pack("<iiii", *inp_pad)
block_data = input_struct
elif key in ("input_offset", "output_offset"):
inputs = data[key]
if key == "output_offset" and len(inputs) > 1:
raise RuntimeError(
"Currently only support one output in Vela ArmBackend"
)
offset_struct = struct.pack("<i", len(inputs))
for inp in inputs:
offset_struct = offset_struct + struct.pack("<i", inp)
block_data = offset_struct
else:
block_data = data[key].tobytes()
# We need the acual unpadded block lengths for hw setup
block_length = len(block_data).to_bytes(16, "little")
# pad block data to multiple of 16 bytes
block_data = block_data + b"\x00" * (15 - (len(block_data) - 1) % 16)

block = block_name + block_length + block_data
blocks = blocks + block

# Add a block for scratch, inputs and outputs
# scratch shape is a 1 element array giving us size in bytes
block_name = bytes("scratch_data", "utf8")[:15]
block_name = block_name + b"\x00" * (16 - len(block_name))
block_length = data["scratch_shape"][0].item()
block_length = block_length + (15 - (block_length - 1) % 16)
block_data = b"\x00" * block_length
block_length = block_length.to_bytes(16, "little")
block = block_name + block_length + block_data
blocks = blocks + block
# TODO are these already in scratch shape? look to be
# input_shape * input_elem_size
# output_shape * output_elem_size
# input_offset and output_offset specify the location these arrays are written from base of scratch

# return 16 byte VELA bin header + blocks + footer
header = bytes("vela_bin_stream", "utf-8") + b"\x00"
footer = bytes("vela_end_stream", "utf-8") + b"\x00"
return header + blocks + footer


def dbg_fail(node, tosa_fb, path):
Expand DownExpand Up@@ -237,14 +315,13 @@ def preprocess( # noqa: C901
# if a debug/test build capture output files from TOSA stage
path = None
debug_output = False
output_format = "vela"
for spec in compile_spec:
if spec.key == "debug_tosa_path":
path = spec.value.decode()
debug_output = True

# in non debug builds we still pass files to vela
if path is None:
path = tempfile.mkdtemp(prefix="arm_tosa_")
if spec.key == "output_format":
output_format = spec.value.decode()

# Converted output for this subgraph, serializer needs path early as it emits
# const data directly. Path created and data written only in debug builds.
Expand DownExpand Up@@ -890,6 +967,16 @@ def preprocess( # noqa: C901
if debug_output is True:
dbg_tosa_dump(tosa_fb, path)

# Serialize and return the tosa flatbuffer
fb = tosa_fb.serialize()
return PreprocessResult(processed_bytes=bytes(fb))
# Serialize and return the program. While we have always produced TOSA
# output as an intermediate, some flows compile to device binaries in
# preprocess and some consume TOSA fb directly.
if output_format == "vela":
# Emit vela_bin_stream format
binary = vela_compile(tosa_fb)
elif output_format == "tosa":
Comment thread
digantdesai marked this conversation as resolved.
# Emit TOSA flatbuffer
binary = bytes(tosa_fb.serialize())
else:
raise RuntimeError(f"Unknown format {output_format}")

return PreprocessResult(processed_bytes=binary)
10 changes: 10 additions & 0 deletions backends/arm/cmake/Dependencies.cmake
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

set(THIRD_PARTY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third-party")

# Ethos-U driver
set(DRIVER_ETHOSU_INCLUDE_DIR "${THIRD_PARTY_ROOT}/ethos-u-core-driver/include")
include_directories( ${DRIVER_ETHOSU_INCLUDE_DIR} )
53 changes: 53 additions & 0 deletions backends/arm/cmake/build.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

#
# Setup toolchain
#
BASEDIR=`realpath $(dirname "$0")`
echo "building using build.sh in $BASEDIR"

ARCH=$(uname -i)
GCCPATH=${BASEDIR}/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi/bin/

echo $GCCPATH
if test -d "${GCCPATH}"; then
echo Using exising compiler ${GCCPATH}
else
pushd ${BASEDIR}/
./toolchain.sh
popd
fi
export PATH=${PATH}:${GCCPATH}

echo building with `arm-none-eabi-gcc -v 2>&1 | grep "^gcc"`


#
# Prepare and run clean build
#
rm -rf buck-out/ build/lib/ cmake-out/
rm -rf cmake-corstone
mkdir cmake-corstone
cd cmake-corstone

#cmake -DBUCK2=buck2 ..

#cmake --toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake ..
cmake -DFLATC_EXECUTABLE=flatc \
-DEXECUTORCH_BUILD_XNNPACK=OFF \
-DEXECUTORCH_BUILD_HOST_TARGETS=OFF \
-DEXECUTORCH_BUILD_ARM_BAREMETAL=ON \
-DCMAKE_SYSTEM_PROCESSOR=cortex-m55+nodsp+nofp \
-DETHOSU_TARGET_NPU_CONFIG=ethos-u55-128 \
--toolchain backends/arm/cmake/arm-none-eabi-gcc.cmake \
-DCMAKE_BUILD_TYPE=Release \
-DEXECUTORCH_ENABLE_LOGGING_RELEASE_MODE=ON \
..

cd ..
cmake --build cmake-corstone -j9 --target ethos_u ethosu_core_driver executorch portable_ops_lib portable_kernels
12 changes: 12 additions & 0 deletions backends/arm/cmake/toolchain.sh
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
#!/bin/bash
# Copyright 2023 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
set -e

# Cross compiler for Arm baremetal (e.g. Corestone-300 FVP or silcon)
ARCH=$(uname -i)
curl -o gcc.tar.xz https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-${ARCH}-arm-none-eabi.tar.xz
tar xf gcc.tar.xz
export PATH=${PATH}:`(cd arm-gnu-toolchain-12.3.rel1-aarch64-arm-none-eabi/bin/; pwd)`
Loading