You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by GitBox <gi...@apache.org> on 2021/05/19 13:04:09 UTC

[GitHub] [tvm] melsonlai opened a new pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

melsonlai opened a new pull request #8076:
URL: https://github.com/apache/tvm/pull/8076


   This commit implements the basic structure of Android NNAPI codegen with the BYOC mechanism:
   
   * Basic graph partition using pattern-based rules
   * RPC-based graph partition
   * relay.ext.android_nnapi BYOC codegen
   
   [\[RFC\]\[BYOC\] Android NNAPI Integration](https://discuss.tvm.apache.org/t/rfc-byoc-android-nnapi-integration/9072)
   
   Thanks for contributing to TVM!   Please refer to guideline https://tvm.apache.org/docs/contribute/ for useful information and tips. After the pull request is submitted, please request code reviews from [Reviewers](https://github.com/apache/incubator-tvm/blob/master/CONTRIBUTORS.md#reviewers) by @ them in the pull request thread.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] comaniac commented on pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
comaniac commented on pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#issuecomment-1008447278


   Thanks for reminding. I'm closing this PR for now as @melsonlai is no longer working on this RFC. The guy that takes over his work will file a new one later.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] melsonlai commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
melsonlai commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r660303669



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/_export_object/helper.py
##########
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Namespace for helper objects/methods that's not part of the JSON
+content. This includes the symbol table, checking methods, ...
+"""
+from .operand import Operand as _Operand
+
+
+class Helper:

Review comment:
       I would make it "JSONAnalyser" then. :)




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] melsonlai commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
melsonlai commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r655259193



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/__init__.py
##########
@@ -0,0 +1,60 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Converts Relay IR subgraph to Android NNAPI source code
+"""
+import tvm
+from .converter import Converter
+
+
+def convert_relayir_to_nnapi(func):

Review comment:
       Hi, I plan to name it "codegen" if that's OK. (I don't want to collide with the Python built-in function "compile")
   As an extra explanation that matters, the external compiler is actually a C++ stub in `src/relay/backend/contrib/android_nnapi/codegen.cc`, and it's that thing that gets registered as `relay.ext.android_nnapi`. 
   The existence of the C++ stub is a historical issue, however, it's not a complex file after all, so would you agree if I completely remove the C++ stub and make all of `relay.ext.android_nnapi` pythonic?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] masahi commented on pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
masahi commented on pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#issuecomment-1008443187


   what's the status of this PR?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] comaniac commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
comaniac commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r659946074



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/_export_object/helper.py
##########
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Namespace for helper objects/methods that's not part of the JSON
+content. This includes the symbol table, checking methods, ...
+"""
+from .operand import Operand as _Operand
+
+
+class Helper:

Review comment:
       analysis.py:XXAnalyzer seems much better to me.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] comaniac commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
comaniac commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r659944789



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/__init__.py
##########
@@ -0,0 +1,60 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Converts Relay IR subgraph to Android NNAPI source code
+"""
+import tvm
+from .converter import Converter
+
+
+def convert_relayir_to_nnapi(func):

Review comment:
       We actually prefer a reverse way that makes most of the implementations in C++ instead of Python for better performance. However, given that would be a huge effort, it should be fine for this specific backend to be all in Python IMHO.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] comaniac commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
comaniac commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r659945572



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/export_object.py
##########
@@ -0,0 +1,304 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""ExportObject, a dict-like structure providing infrastructure for
+Android NNAPI codegen
+"""
+import struct
+import copy
+from .error import assert_anc_compatibility
+from ._export_object import Helper as _Helper
+
+
+class ExportObject:
+    """A dict-like structure providing infrastructure for Android NNAPI codegen
+
+    Parameters
+    ----------------------
+    options: dict
+        The converter option dict
+
+    """
+
+    _SCALAR_RELAY_NNAPI_TYPE_MAP = {
+        "bool": "BOOL",
+        "float16": "FLOAT16",
+        "float32": "FLOAT32",
+        "int32": "INT32",
+        "uint32": "UINT32",
+    }
+
+    _TENSOR_RELAY_NNAPI_TYPE_MAP = {
+        "bool": "TENSOR_BOOL",
+        "float16": "TENSOR_FLOAT16",
+        "float32": "TENSOR_FLOAT32",
+        "int32": "TENSOR_INT32",
+        "uint32": "TENSOR_UINT32",
+    }
+
+    def __init__(self, options):
+        self.helper = _Helper(self)
+        self._json = {
+            "constants": [],
+            "inputs": [],
+            "memories": [],
+            "operands": [],
+            "operations": [],
+            "outputs": [],
+            "types": [],
+        }
+        self._options = options
+
+    def __getitem__(self, key):
+        return self._json[key]
+
+    def __setitem__(self, key, value):
+        self._json[key] = value
+
+    def asjson(self):
+        """Return the content of ExportObject as a primitive Python dict
+
+        Returns
+        -------
+        json: dict
+            The content of ExportObject as a primitive Python dict
+
+        """
+        return copy.deepcopy(self._json)
+
+    def get_type_idx(self, tipe):
+        """Register and lookup type index in export_obj["types"]
+
+        Parameters
+        ----------
+        tipe: ((int, ...), str)
+            type (shape, dtype) to look up
+
+        Returns
+        -------
+        index: int
+            type index in export object
+        """
+        tipe = (tuple(map(int, tipe[0])), str(tipe[1]))  # canonicalize
+        shape, dtype = tipe
+        assert_anc_compatibility(
+            dtype in ["bool", "float16", "float32", "int32", "uint32"],
+            "Unsupported data type { dtype }",
+        )
+
+        if self.helper.type_to_idx_map.get(tipe, None) is None:  # create new type
+            shape, dtype = tipe
+
+            if dtype == "bool":
+                assert_anc_compatibility(
+                    self._options["target"]["api_level"] >= 29,
+                    f"Boolean is not supported for Android API{ self._options['target']['api_level'] }",  # pylint: disable=line-too-long
+                )
+
+            new_type = {}
+            if len(shape) == 0:
+                new_type["type"] = self._SCALAR_RELAY_NNAPI_TYPE_MAP[dtype]
+            else:
+                new_type["shape"] = list(shape)
+                new_type["type"] = self._TENSOR_RELAY_NNAPI_TYPE_MAP[dtype]
+
+            self["types"].append(new_type)
+            self.helper.type_to_idx_map[tipe] = len(self["types"]) - 1
+        return self.helper.type_to_idx_map[tipe]
+
+    @staticmethod
+    def _canonicalize_scalar_constant(dtype, val):
+        # skip canonicalizing strings as they may carry specific meanings,
+        # e.g. macro-defined values
+        if not isinstance(val, str):
+            if dtype == "float16":
+                if isinstance(val, float):
+                    val = hex(
+                        struct.unpack("H", struct.pack("e", val))[0]
+                    )  # for float16 we use uint16_t in C, hence the conversion
+            elif dtype == "float32":
+                val = float(val)
+            elif dtype == "int32":
+                val = int(val)
+            elif dtype == "uint32":
+                val = int(val)
+            elif dtype == "bool":
+                val = bool(val)
+            else:
+                assert False, "Unreachable"
+        return val
+
+    def add_scalar_constant(self, val, dtype):
+        """Add scalar constant to export object
+
+        Parameters
+        ----------
+        val: numerical or str
+            value of the constant. Can be defined constant in the NNAPI framework.
+
+        dtype: str
+            data type of the constant
+
+        Returns
+        -------
+        index: int
+            index of the constant in export object constants array
+        """
+        # canonicalize
+        dtype = str(dtype)
+        assert_anc_compatibility(
+            dtype in ["float16", "float32", "int32", "uint32", "bool"],
+            f"Unsupported data type { dtype }",
+        )
+        val = self._canonicalize_scalar_constant(dtype, val)
+
+        new_const = {
+            "type": "scalar",
+            "dtype": dtype,
+            "value": val,
+        }
+        if new_const in self["constants"]:
+            return self["constants"].index(new_const)
+
+        self["constants"].append(new_const)
+        return len(self["constants"]) - 1
+
+    def add_array_constant(self, vals, dtype):
+        """Add array constant to export object
+
+        Parameters
+        ----------
+        vals: array of values in dtype
+            values of array
+
+        dtype: string
+            data type of array
+
+        Returns
+        -------
+        index: int
+            index of added constant in export_obj["constants"]
+        """
+        # canonicalize
+        dtype = str(dtype)
+        assert_anc_compatibility(
+            dtype in ["float16", "float32", "int32", "uint32", "bool"],
+            f"Unsupported data type { dtype }",
+        )
+        assert len(vals) > 0, "Array constant should not be empty"
+        vals = list(map(lambda v: self._canonicalize_scalar_constant(dtype, v), vals))
+
+        new_const = {
+            "type": "array",
+            "dtype": dtype,
+            "value": vals,
+        }
+        if new_const in self["constants"]:

Review comment:
       I see. It should be fine then.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] comaniac closed pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
comaniac closed pull request #8076:
URL: https://github.com/apache/tvm/pull/8076


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] melsonlai commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
melsonlai commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r660303669



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/_export_object/helper.py
##########
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Namespace for helper objects/methods that's not part of the JSON
+content. This includes the symbol table, checking methods, ...
+"""
+from .operand import Operand as _Operand
+
+
+class Helper:

Review comment:
       I would make it "JSONAnalyser" then. :)




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] melsonlai commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
melsonlai commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r655259193



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/__init__.py
##########
@@ -0,0 +1,60 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Converts Relay IR subgraph to Android NNAPI source code
+"""
+import tvm
+from .converter import Converter
+
+
+def convert_relayir_to_nnapi(func):

Review comment:
       Hi, I plan to name it "codegen" if that's OK. (I don't want to collide with the Python built-in function "compile")
   As an extra explanation that matters, the external compiler is actually a C++ stub in `src/relay/backend/contrib/android_nnapi/codegen.cc`, and it's that thing that gets registered as `relay.ext.android_nnapi`. 
   The existence of the C++ stub is a historical issue, however, it's not a complex file after all, so would you agree if I completely remove the C++ stub and make all of `relay.ext.android_nnapi` pythonic?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] melsonlai commented on pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
melsonlai commented on pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#issuecomment-844259424


   cc @comaniac @zhiics 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] melsonlai commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
melsonlai commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r655974487



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/export_object.py
##########
@@ -0,0 +1,304 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""ExportObject, a dict-like structure providing infrastructure for
+Android NNAPI codegen
+"""
+import struct
+import copy
+from .error import assert_anc_compatibility
+from ._export_object import Helper as _Helper
+
+
+class ExportObject:
+    """A dict-like structure providing infrastructure for Android NNAPI codegen
+
+    Parameters
+    ----------------------
+    options: dict
+        The converter option dict
+
+    """
+
+    _SCALAR_RELAY_NNAPI_TYPE_MAP = {
+        "bool": "BOOL",
+        "float16": "FLOAT16",
+        "float32": "FLOAT32",
+        "int32": "INT32",
+        "uint32": "UINT32",
+    }
+
+    _TENSOR_RELAY_NNAPI_TYPE_MAP = {
+        "bool": "TENSOR_BOOL",
+        "float16": "TENSOR_FLOAT16",
+        "float32": "TENSOR_FLOAT32",
+        "int32": "TENSOR_INT32",
+        "uint32": "TENSOR_UINT32",
+    }
+
+    def __init__(self, options):
+        self.helper = _Helper(self)
+        self._json = {
+            "constants": [],
+            "inputs": [],
+            "memories": [],
+            "operands": [],
+            "operations": [],
+            "outputs": [],
+            "types": [],
+        }
+        self._options = options
+
+    def __getitem__(self, key):
+        return self._json[key]
+
+    def __setitem__(self, key, value):
+        self._json[key] = value
+
+    def asjson(self):
+        """Return the content of ExportObject as a primitive Python dict
+
+        Returns
+        -------
+        json: dict
+            The content of ExportObject as a primitive Python dict
+
+        """
+        return copy.deepcopy(self._json)
+
+    def get_type_idx(self, tipe):
+        """Register and lookup type index in export_obj["types"]
+
+        Parameters
+        ----------
+        tipe: ((int, ...), str)
+            type (shape, dtype) to look up
+
+        Returns
+        -------
+        index: int
+            type index in export object
+        """
+        tipe = (tuple(map(int, tipe[0])), str(tipe[1]))  # canonicalize
+        shape, dtype = tipe
+        assert_anc_compatibility(
+            dtype in ["bool", "float16", "float32", "int32", "uint32"],
+            "Unsupported data type { dtype }",
+        )
+
+        if self.helper.type_to_idx_map.get(tipe, None) is None:  # create new type
+            shape, dtype = tipe
+
+            if dtype == "bool":
+                assert_anc_compatibility(
+                    self._options["target"]["api_level"] >= 29,
+                    f"Boolean is not supported for Android API{ self._options['target']['api_level'] }",  # pylint: disable=line-too-long
+                )
+
+            new_type = {}
+            if len(shape) == 0:
+                new_type["type"] = self._SCALAR_RELAY_NNAPI_TYPE_MAP[dtype]
+            else:
+                new_type["shape"] = list(shape)
+                new_type["type"] = self._TENSOR_RELAY_NNAPI_TYPE_MAP[dtype]
+
+            self["types"].append(new_type)
+            self.helper.type_to_idx_map[tipe] = len(self["types"]) - 1
+        return self.helper.type_to_idx_map[tipe]
+
+    @staticmethod
+    def _canonicalize_scalar_constant(dtype, val):
+        # skip canonicalizing strings as they may carry specific meanings,
+        # e.g. macro-defined values
+        if not isinstance(val, str):
+            if dtype == "float16":
+                if isinstance(val, float):
+                    val = hex(
+                        struct.unpack("H", struct.pack("e", val))[0]
+                    )  # for float16 we use uint16_t in C, hence the conversion
+            elif dtype == "float32":
+                val = float(val)
+            elif dtype == "int32":
+                val = int(val)
+            elif dtype == "uint32":
+                val = int(val)
+            elif dtype == "bool":
+                val = bool(val)
+            else:
+                assert False, "Unreachable"
+        return val
+
+    def add_scalar_constant(self, val, dtype):
+        """Add scalar constant to export object
+
+        Parameters
+        ----------
+        val: numerical or str
+            value of the constant. Can be defined constant in the NNAPI framework.
+
+        dtype: str
+            data type of the constant
+
+        Returns
+        -------
+        index: int
+            index of the constant in export object constants array
+        """
+        # canonicalize
+        dtype = str(dtype)
+        assert_anc_compatibility(
+            dtype in ["float16", "float32", "int32", "uint32", "bool"],
+            f"Unsupported data type { dtype }",
+        )
+        val = self._canonicalize_scalar_constant(dtype, val)
+
+        new_const = {
+            "type": "scalar",
+            "dtype": dtype,
+            "value": val,
+        }
+        if new_const in self["constants"]:
+            return self["constants"].index(new_const)
+
+        self["constants"].append(new_const)
+        return len(self["constants"]) - 1
+
+    def add_array_constant(self, vals, dtype):
+        """Add array constant to export object
+
+        Parameters
+        ----------
+        vals: array of values in dtype
+            values of array
+
+        dtype: string
+            data type of array
+
+        Returns
+        -------
+        index: int
+            index of added constant in export_obj["constants"]
+        """
+        # canonicalize
+        dtype = str(dtype)
+        assert_anc_compatibility(
+            dtype in ["float16", "float32", "int32", "uint32", "bool"],
+            f"Unsupported data type { dtype }",
+        )
+        assert len(vals) > 0, "Array constant should not be empty"
+        vals = list(map(lambda v: self._canonicalize_scalar_constant(dtype, v), vals))
+
+        new_const = {
+            "type": "array",
+            "dtype": dtype,
+            "value": vals,
+        }
+        if new_const in self["constants"]:

Review comment:
       `self["constants"]` is a list, so I think it's fine? (`new_const` is not used as key)

##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/_export_object/helper.py
##########
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Namespace for helper objects/methods that's not part of the JSON
+content. This includes the symbol table, checking methods, ...
+"""
+from .operand import Operand as _Operand
+
+
+class Helper:

Review comment:
       Perhaps I can name it "analysis"?
   This namespace (for now) includes read-and-compute methods that help checking for some properties during codegen. 




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [tvm] comaniac commented on a change in pull request #8076: [BYOC][NNAPI]: Implement basic structure of Android NNAPI BYOC

Posted by GitBox <gi...@apache.org>.
comaniac commented on a change in pull request #8076:
URL: https://github.com/apache/tvm/pull/8076#discussion_r659944789



##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/__init__.py
##########
@@ -0,0 +1,60 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Converts Relay IR subgraph to Android NNAPI source code
+"""
+import tvm
+from .converter import Converter
+
+
+def convert_relayir_to_nnapi(func):

Review comment:
       We actually prefer a reverse way that makes most of the implementations in C++ instead of Python for better performance. However, given that would be a huge effort, it should be fine for this specific backend to be all in Python IMHO.

##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/export_object.py
##########
@@ -0,0 +1,304 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""ExportObject, a dict-like structure providing infrastructure for
+Android NNAPI codegen
+"""
+import struct
+import copy
+from .error import assert_anc_compatibility
+from ._export_object import Helper as _Helper
+
+
+class ExportObject:
+    """A dict-like structure providing infrastructure for Android NNAPI codegen
+
+    Parameters
+    ----------------------
+    options: dict
+        The converter option dict
+
+    """
+
+    _SCALAR_RELAY_NNAPI_TYPE_MAP = {
+        "bool": "BOOL",
+        "float16": "FLOAT16",
+        "float32": "FLOAT32",
+        "int32": "INT32",
+        "uint32": "UINT32",
+    }
+
+    _TENSOR_RELAY_NNAPI_TYPE_MAP = {
+        "bool": "TENSOR_BOOL",
+        "float16": "TENSOR_FLOAT16",
+        "float32": "TENSOR_FLOAT32",
+        "int32": "TENSOR_INT32",
+        "uint32": "TENSOR_UINT32",
+    }
+
+    def __init__(self, options):
+        self.helper = _Helper(self)
+        self._json = {
+            "constants": [],
+            "inputs": [],
+            "memories": [],
+            "operands": [],
+            "operations": [],
+            "outputs": [],
+            "types": [],
+        }
+        self._options = options
+
+    def __getitem__(self, key):
+        return self._json[key]
+
+    def __setitem__(self, key, value):
+        self._json[key] = value
+
+    def asjson(self):
+        """Return the content of ExportObject as a primitive Python dict
+
+        Returns
+        -------
+        json: dict
+            The content of ExportObject as a primitive Python dict
+
+        """
+        return copy.deepcopy(self._json)
+
+    def get_type_idx(self, tipe):
+        """Register and lookup type index in export_obj["types"]
+
+        Parameters
+        ----------
+        tipe: ((int, ...), str)
+            type (shape, dtype) to look up
+
+        Returns
+        -------
+        index: int
+            type index in export object
+        """
+        tipe = (tuple(map(int, tipe[0])), str(tipe[1]))  # canonicalize
+        shape, dtype = tipe
+        assert_anc_compatibility(
+            dtype in ["bool", "float16", "float32", "int32", "uint32"],
+            "Unsupported data type { dtype }",
+        )
+
+        if self.helper.type_to_idx_map.get(tipe, None) is None:  # create new type
+            shape, dtype = tipe
+
+            if dtype == "bool":
+                assert_anc_compatibility(
+                    self._options["target"]["api_level"] >= 29,
+                    f"Boolean is not supported for Android API{ self._options['target']['api_level'] }",  # pylint: disable=line-too-long
+                )
+
+            new_type = {}
+            if len(shape) == 0:
+                new_type["type"] = self._SCALAR_RELAY_NNAPI_TYPE_MAP[dtype]
+            else:
+                new_type["shape"] = list(shape)
+                new_type["type"] = self._TENSOR_RELAY_NNAPI_TYPE_MAP[dtype]
+
+            self["types"].append(new_type)
+            self.helper.type_to_idx_map[tipe] = len(self["types"]) - 1
+        return self.helper.type_to_idx_map[tipe]
+
+    @staticmethod
+    def _canonicalize_scalar_constant(dtype, val):
+        # skip canonicalizing strings as they may carry specific meanings,
+        # e.g. macro-defined values
+        if not isinstance(val, str):
+            if dtype == "float16":
+                if isinstance(val, float):
+                    val = hex(
+                        struct.unpack("H", struct.pack("e", val))[0]
+                    )  # for float16 we use uint16_t in C, hence the conversion
+            elif dtype == "float32":
+                val = float(val)
+            elif dtype == "int32":
+                val = int(val)
+            elif dtype == "uint32":
+                val = int(val)
+            elif dtype == "bool":
+                val = bool(val)
+            else:
+                assert False, "Unreachable"
+        return val
+
+    def add_scalar_constant(self, val, dtype):
+        """Add scalar constant to export object
+
+        Parameters
+        ----------
+        val: numerical or str
+            value of the constant. Can be defined constant in the NNAPI framework.
+
+        dtype: str
+            data type of the constant
+
+        Returns
+        -------
+        index: int
+            index of the constant in export object constants array
+        """
+        # canonicalize
+        dtype = str(dtype)
+        assert_anc_compatibility(
+            dtype in ["float16", "float32", "int32", "uint32", "bool"],
+            f"Unsupported data type { dtype }",
+        )
+        val = self._canonicalize_scalar_constant(dtype, val)
+
+        new_const = {
+            "type": "scalar",
+            "dtype": dtype,
+            "value": val,
+        }
+        if new_const in self["constants"]:
+            return self["constants"].index(new_const)
+
+        self["constants"].append(new_const)
+        return len(self["constants"]) - 1
+
+    def add_array_constant(self, vals, dtype):
+        """Add array constant to export object
+
+        Parameters
+        ----------
+        vals: array of values in dtype
+            values of array
+
+        dtype: string
+            data type of array
+
+        Returns
+        -------
+        index: int
+            index of added constant in export_obj["constants"]
+        """
+        # canonicalize
+        dtype = str(dtype)
+        assert_anc_compatibility(
+            dtype in ["float16", "float32", "int32", "uint32", "bool"],
+            f"Unsupported data type { dtype }",
+        )
+        assert len(vals) > 0, "Array constant should not be empty"
+        vals = list(map(lambda v: self._canonicalize_scalar_constant(dtype, v), vals))
+
+        new_const = {
+            "type": "array",
+            "dtype": dtype,
+            "value": vals,
+        }
+        if new_const in self["constants"]:

Review comment:
       I see. It should be fine then.

##########
File path: python/tvm/contrib/target/android_nnapi/relayir_to_nnapi_converter/_export_object/helper.py
##########
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Namespace for helper objects/methods that's not part of the JSON
+content. This includes the symbol table, checking methods, ...
+"""
+from .operand import Operand as _Operand
+
+
+class Helper:

Review comment:
       analysis.py:XXAnalyzer seems much better to me.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org