├── .gitignore ├── graph_editor └── addone_example.py ├── python └── tf_op │ ├── __init__.py │ └── module.py ├── src ├── index_seq.h ├── build.sh ├── tvm_dso_ops.cc └── tvm_dso_op_kernels.cc ├── examples ├── addone │ ├── export_tvm_ops.py │ └── tensorflow_with_tvm.py └── vector_add │ ├── export_tvm_ops.py │ └── test.py ├── CMakeLists.txt ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | build/ 35 | logs/ 36 | -------------------------------------------------------------------------------- /graph_editor/addone_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import tensorflow as tf 4 | from tensorflow.contrib import graph_editor as ge 5 | from tvm.contrib import tf_op 6 | 7 | graph = tf.Graph() 8 | 9 | with graph.as_default(): 10 | input_op = tf.constant([1.0, 2.0, -1.0]) 11 | tf_addone = tf.add(input_op, 1.0) 12 | output_op = tf_addone * 100 13 | 14 | tvm_addone = tf_op.Module("tvm_addone_dll.so")["addone"](input_op) 15 | new_output_op = ge.graph_replace(output_op, {tf_addone: tvm_addone}) 16 | 17 | with tf.Session(graph=graph) as sess: 18 | print(sess.run(output_op)) 19 | print(sess.run(new_output_op)) 20 | -------------------------------------------------------------------------------- /python/tf_op/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | 18 | from . import module 19 | 20 | Module = module.Module 21 | -------------------------------------------------------------------------------- /src/index_seq.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Refer to std::index_sequence (since c++14) 3 | * Utilities to invoke variadic function with template 4 | */ 5 | #ifndef __TFTVM_INDEX_SEQ__ 6 | #define __TFTVM_INDEX_SEQ__ 7 | 8 | template 9 | struct IndexSeq {}; 10 | 11 | template 12 | struct IndexSeqHelper : public IndexSeqHelper {}; 13 | 14 | template 15 | struct IndexSeqHelper<0U, Tail ...> { 16 | using type = IndexSeq; 17 | }; 18 | 19 | template 20 | using make_index_sequence = typename IndexSeqHelper::type; 21 | 22 | 23 | template 24 | decltype(auto) apply_variadic_impl(F f, T(&t)[N], IndexSeq) { 25 | return f(t[Idx]...); 26 | } 27 | 28 | template 29 | decltype(auto) apply_variadic(F f, T(&t)[N]) { 30 | return apply_variadic_impl(f, t, make_index_sequence{}); 31 | } 32 | 33 | template 34 | decltype(auto) apply_variadic_by_ptrs_impl(F f, T(&t)[N], IndexSeq) { 35 | return f(&t[Idx]...); 36 | } 37 | 38 | template 39 | decltype(auto) apply_variadic_by_ptrs(F f, T(&t)[N]) { 40 | return apply_variadic_by_ptrs_impl(f, t, make_index_sequence{}); 41 | } 42 | 43 | #endif 44 | 45 | -------------------------------------------------------------------------------- /src/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | 20 | set -x 21 | set -e 22 | 23 | TF_CFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_compile_flags()))') ) 24 | TF_LFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_link_flags()))') ) 25 | 26 | op_kernel_file=tvm_dso_op_kernels.cc 27 | op_register_file=tvm_dso_ops.cc 28 | output_so_file=tvm_dso_op.so 29 | 30 | g++ -std=c++11 -shared $op_kernel_file $op_register_file -o $output_so_file -fPIC ${TF_CFLAGS[@]} ${TF_LFLAGS[@]} -O2 -I${TVM_HOME}/include -I${TVM_HOME}/3rdparty/dmlc-core/include -I${TVM_HOME}/3rdparty/dlpack/include -ldl -lpthread -I/usr/local/cuda/include 31 | -------------------------------------------------------------------------------- /examples/addone/export_tvm_ops.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | 20 | import tvm 21 | import os 22 | 23 | def main(): 24 | n = tvm.var("n") 25 | A = tvm.placeholder((n,), name='A') 26 | B = tvm.compute(A.shape, lambda *i: A(*i) + 1, name='B') 27 | s = tvm.create_schedule(B.op) 28 | fadd_dylib = tvm.build(s, [A, B], "llvm", name="addone") 29 | fadd_dylib.export_library("tvm_addone_dll.so") 30 | 31 | bx, tx = s[B].split(B.op.axis[0], factor=64) 32 | s[B].bind(bx, tvm.thread_axis("blockIdx.x")) 33 | s[B].bind(tx, tvm.thread_axis("threadIdx.x")) 34 | fadd_dylib = tvm.build(s, [A, B], "cuda", name="addone") 35 | fadd_dylib.export_library("tvm_addone_cuda_dll.so") 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /examples/addone/tensorflow_with_tvm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | 20 | import tensorflow as tf 21 | from tvm.contrib import tf_op 22 | 23 | def main(): 24 | mod = tf_op.Module("tvm_addone_dll.so") 25 | addone = mod.func("addone", output_shape=[2]) 26 | 27 | with tf.Session() as sess: 28 | with tf.device("/cpu:0"): 29 | placeholder = tf.placeholder("float32", shape=[2]) 30 | print(sess.run(addone(placeholder), feed_dict={placeholder: [1.0, 2.0]})) 31 | 32 | with tf.device("/gpu:0"): 33 | placeholder = tf.placeholder("float32") 34 | addone_gpu = tf_op.Module("tvm_addone_cuda_dll.so")["addone"] 35 | print(sess.run(addone_gpu(placeholder), feed_dict={placeholder: [1.0, 2.0]})) 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /examples/vector_add/export_tvm_ops.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | 20 | import tvm 21 | import os 22 | 23 | def main(): 24 | n = tvm.var("n") 25 | A = tvm.placeholder((n,), name='A') 26 | B = tvm.placeholder((n,), name='B') 27 | C = tvm.compute(A.shape, lambda i: A[i] + B[i], name='C') 28 | s = tvm.create_schedule(C.op) 29 | fadd_dylib = tvm.build(s, [A, B, C], "llvm", name="vector_add") 30 | fadd_dylib.export_library("tvm_add_dll.so") 31 | 32 | bx, tx = s[C].split(C.op.axis[0], factor=64) 33 | s[C].bind(bx, tvm.thread_axis("blockIdx.x")) 34 | s[C].bind(tx, tvm.thread_axis("threadIdx.x")) 35 | fadd_dylib = tvm.build(s, [A, B, C], "cuda", name="vector_add") 36 | fadd_dylib.export_library("tvm_add_cuda_dll.so") 37 | 38 | 39 | if __name__ == "__main__": 40 | main() 41 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.2) 2 | project(tftvm) 3 | set(CMAKE_VERBOSE_MAKEFILE ON) 4 | 5 | if ("${TVM_HOME}" STREQUAL "") 6 | message(FATAL_ERROR "TVM_HOME is not defined") 7 | else() 8 | message("Use TVM_HOME=\"${TVM_HOME}\"") 9 | endif() 10 | 11 | 12 | include_directories(${TVM_HOME}/include) 13 | include_directories(${TVM_HOME}/3rdparty/dlpack/include) 14 | include_directories(${TVM_HOME}/3rdparty/dmlc-core/include) 15 | 16 | 17 | execute_process(COMMAND python -c "import tensorflow as tf; print(' '.join(tf.sysconfig.get_compile_flags()))" 18 | OUTPUT_VARIABLE TF_COMPILE_FLAGS_STR 19 | RESULT_VARIABLE TF_STATUS) 20 | if (NOT ${TF_STATUS} EQUAL 0) 21 | message(FATAL_ERROR "Fail to get TensorFlow compile flags") 22 | endif() 23 | 24 | execute_process(COMMAND python -c "import tensorflow as tf; print(' '.join(tf.sysconfig.get_link_flags()))" 25 | OUTPUT_VARIABLE TF_LINK_FLAGS_STR 26 | RESULT_VARIABLE TF_STATUS) 27 | if (NOT ${TF_STATUS} EQUAL 0) 28 | message(FATAL_ERROR "Fail to get TensorFlow link flags") 29 | endif() 30 | 31 | string(REGEX REPLACE "\n" " " TF_FLAGS "${TF_COMPILE_FLAGS} ${TF_LINK_FLAGS}") 32 | message("Use TensorFlow flags=\"${TF_FLAGS}\"") 33 | separate_arguments(TF_COMPILE_FLAGS UNIX_COMMAND ${TF_COMPILE_FLAGS_STR}) 34 | separate_arguments(TF_LINK_FLAGS UNIX_COMMAND ${TF_LINK_FLAGS_STR}) 35 | 36 | 37 | set(OP_LIBRARY_NAME tvm_dso_op) 38 | file(GLOB_RECURSE TFTVM_SRCS src/*.cc) 39 | add_library(${OP_LIBRARY_NAME} SHARED ${TFTVM_SRCS}) 40 | set_target_properties(${OP_LIBRARY_NAME} PROPERTIES PREFIX "") 41 | 42 | set(TFTVM_COMPILE_FLAGS -O2 -ldl -g) 43 | set(TFTVM_LINK_FLAGS -ltvm_runtime -L${TVM_HOME}/build) 44 | target_compile_options(${OP_LIBRARY_NAME} PUBLIC ${TFTVM_COMPILE_FLAGS} ${TF_COMPILE_FLAGS}) 45 | target_link_options(${OP_LIBRARY_NAME} PUBLIC ${TFTVM_LINK_FLAGS} ${TF_LINK_FLAGS}) 46 | 47 | -------------------------------------------------------------------------------- /examples/vector_add/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | 20 | import tensorflow as tf 21 | import sys 22 | 23 | from tvm.contrib import tf_op 24 | # import tf_op 25 | 26 | 27 | def main(): 28 | module = tf_op.Module("tvm_add_dll.so") 29 | 30 | left = tf.placeholder("float32", shape=[4]) 31 | right = tf.placeholder("float32", shape=[4]) 32 | 33 | feed_dict = { 34 | left: [1.0, 2.0, 3.0, 4.0], 35 | right: [5.0, 6.0, 7.0, 8.0] 36 | } 37 | 38 | # specify output shape with various styles, output type default to float 39 | # (1) via static dimensions 40 | add1 = module.func("vector_add", output_shape=[4], output_dtype="float") 41 | # (2) via shape tensor 42 | add2 = module.func("vector_add", output_shape=tf.shape(left), output_dtype="float") 43 | # (3) via dimension tensor list 44 | add3 = module.func("vector_add", output_shape=[tf.shape(left)[0]], output_dtype="float") 45 | 46 | with tf.Session() as sess: 47 | 48 | with tf.device("/cpu:0"): 49 | print(sess.run(add1(left, right), feed_dict)) 50 | print(sess.run(add2(left, right), feed_dict)) 51 | print(sess.run(add3(left, right), feed_dict)) 52 | 53 | with tf.device("/gpu:0"): 54 | add_gpu = tf_op.Module("tvm_add_cuda_dll.so").func("vector_add") 55 | print(sess.run(add_gpu(left, right), feed_dict)) 56 | 57 | 58 | if __name__ == "__main__": 59 | main() 60 | 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TF-TVM 2 | 3 | Deprecated notice: This project has been merged into [tvm](https://github.com/apache/incubator-tvm) and please compile with `USE_TF_TVMDSOOP=ON`. 4 | 5 | ## Introduction 6 | 7 | This project enables TensorFlow users to run TVM-optimized operators without effort. 8 | 9 | TVM is one of the most popular compile stack for graph and operator optmization. We can embed TVM in TensorFlow graph to leverage the usability of TensorFlow and extensibility of TVM. The [RFC](https://discuss.tvm.ai/t/rfc-add-tensorflow-custom-op-to-embed-tvm-runtime-in-tensorflow-graph-and-session/4601) is under discussion and this project may migrate to [tvm](https://github.com/apache/incubator-tvm) in the future. 10 | 11 | ## Installation 12 | 13 | Make sure the `TensorFlow` and `TVM` has been installed and setup environment variable of `TVM_HOME`. Notice that the following steps can be skipped once these packages has been migrated to `TVM`. 14 | 15 | We can build the `TVMDSOOp` from scratch or download for your OS arch. 16 | 17 | ``` 18 | git clone https://github.com/tobegit3hub/tftvm 19 | cd ./tftvm 20 | sh build.sh 21 | ``` 22 | 23 | Then links the files to existing `TVM` path and set `LD_LIBRARY_PATH`. 24 | ``` 25 | ln -s $(pwd)/tftvm/python/tf_op/ ${TVM_HOME}/python/tvm/contrib/ 26 | ln -s $(pwd)/tftvm/cpp/tvm_dso_op.so ${TVM_HOME}/build/ 27 | 28 | export LD_LIBRARY_PATH=${TVM_HOME}/build/:${LD_LIBRARY_PATH} 29 | ``` 30 | 31 | ## Usage 32 | 33 | We can use Python API to load TVM dynamic libraries in TensorFlow graph and session. 34 | 35 | ``` 36 | import tensorflow as tf 37 | from tvm.contrib import tf_op 38 | 39 | mod = tf_op.Module("tvm_addone_dll.so") 40 | addone = mod.func("addone", output_shape=[4]) 41 | 42 | with tf.Session() as sess: 43 | a = tf.constant([10.1, 20.0, 11.2, -30.3]) 44 | b = addone(a) 45 | print(sess.run(b)) 46 | ``` 47 | 48 | ## Examples 49 | 50 | [addone](./examples/addone/) is the walk-through example to export TVM libraries and load with TensorFlow. 51 | 52 | [vector_add](./examples/vector_add/) is another walk-through example to specify output shape and datatype. 53 | 54 | [graph_editor](./graph_editor/addone_example.py) provides the example to edit TensorFlow graph with TVM operator. 55 | 56 | ## Contribution 57 | 58 | Feel free to discuss in [TVM RFC](https://discuss.tvm.ai/t/rfc-add-tensorflow-custom-op-to-embed-tvm-runtime-in-tensorflow-graph-and-session/4601) and any feedback is welcome. 59 | -------------------------------------------------------------------------------- /src/tvm_dso_ops.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | #include "tensorflow/core/framework/op.h" 21 | 22 | using namespace tensorflow; 23 | 24 | #define REGISTER_TFTVM_OP(n) REGISTER_OP("TvmDsoOp" #n) \ 25 | .Output("output: output_dtype") \ 26 | .Attr("lib_path: string") \ 27 | .Attr("func_name: string") \ 28 | .Attr("output_dtype: {int32, int64, float} = DT_FLOAT") \ 29 | .Attr("static_output_shape: list(int) >= 0 = []") \ 30 | .Attr("has_static_output_shape: bool") \ 31 | 32 | 33 | REGISTER_TFTVM_OP(1) 34 | .Input("input: T").Attr("T: type") \ 35 | .Input("dynamic_output_shape: int64"); 36 | 37 | REGISTER_TFTVM_OP(2) 38 | .Input("input1: T1").Attr("T1: type") 39 | .Input("input2: T2").Attr("T2: type") 40 | .Input("dynamic_output_shape: int64"); 41 | 42 | REGISTER_TFTVM_OP(3) 43 | .Input("input1: T1").Attr("T1: type") 44 | .Input("input2: T2").Attr("T2: type") 45 | .Input("input3: T3").Attr("T3: type") 46 | .Input("dynamic_output_shape: int64"); 47 | 48 | REGISTER_TFTVM_OP(4) 49 | .Input("input1: T1").Attr("T1: type") 50 | .Input("input2: T2").Attr("T2: type") 51 | .Input("input3: T3").Attr("T3: type") 52 | .Input("input4: T4").Attr("T4: type") 53 | .Input("dynamic_output_shape: int64"); 54 | 55 | REGISTER_TFTVM_OP(5) 56 | .Input("input1: T1").Attr("T1: type") 57 | .Input("input2: T2").Attr("T2: type") 58 | .Input("input3: T3").Attr("T3: type") 59 | .Input("input4: T4").Attr("T4: type") 60 | .Input("input5: T5").Attr("T5: type") 61 | .Input("dynamic_output_shape: int64"); 62 | 63 | REGISTER_TFTVM_OP(6) 64 | .Input("input1: T1").Attr("T1: type") 65 | .Input("input2: T2").Attr("T2: type") 66 | .Input("input3: T3").Attr("T3: type") 67 | .Input("input4: T4").Attr("T4: type") 68 | .Input("input5: T5").Attr("T5: type") 69 | .Input("input6: T6").Attr("T6: type") 70 | .Input("dynamic_output_shape: int64"); 71 | 72 | REGISTER_TFTVM_OP(7) 73 | .Input("input1: T1").Attr("T1: type") 74 | .Input("input2: T2").Attr("T2: type") 75 | .Input("input3: T3").Attr("T3: type") 76 | .Input("input4: T4").Attr("T4: type") 77 | .Input("input5: T5").Attr("T5: type") 78 | .Input("input6: T6").Attr("T6: type") 79 | .Input("input7: T7").Attr("T7: type") 80 | .Input("dynamic_output_shape: int64"); 81 | 82 | REGISTER_TFTVM_OP(8) 83 | .Input("input1: T1").Attr("T1: type") 84 | .Input("input2: T2").Attr("T2: type") 85 | .Input("input3: T3").Attr("T3: type") 86 | .Input("input4: T4").Attr("T4: type") 87 | .Input("input5: T5").Attr("T5: type") 88 | .Input("input6: T6").Attr("T6: type") 89 | .Input("input7: T7").Attr("T7: type") 90 | .Input("input8: T8").Attr("T8: type") 91 | .Input("dynamic_output_shape: int64"); 92 | -------------------------------------------------------------------------------- /python/tf_op/module.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | import tensorflow as tf 18 | from tensorflow.python.framework import load_library 19 | 20 | 21 | class Module(): 22 | 23 | def __init__(self, lib_path): 24 | self.lib_path = lib_path 25 | 26 | def func(self, name, output_dtype=None, output_shape=None): 27 | return Func(self.lib_path, name, output_dtype, output_shape) 28 | 29 | def __getitem__(self, func_name): 30 | return self.func(func_name) 31 | 32 | 33 | class Func(): 34 | 35 | def __init__(self, lib_path, func_name, output_dtype, output_shape): 36 | self.lib_path = lib_path 37 | self.func_name = func_name 38 | self.output_dtype = output_dtype 39 | 40 | # const(0) indicate invalid dynamic shape 41 | self.dynamic_output_shape = tf.constant(0, tf.int64) 42 | self.static_output_shape = None 43 | self.has_static_output_shape = False # extra flag is required 44 | 45 | if self._is_static_shape(output_shape): 46 | self.static_output_shape = output_shape 47 | self.has_static_output_shape = True 48 | elif output_shape is not None: 49 | self.dynamic_output_shape = self._pack_shape_tensor(output_shape) 50 | 51 | # TODO: support non-xpu device 52 | #self.device = device 53 | # delay initialization to called first time, where num input arguments is known 54 | self.tvm_dso_op = None 55 | self.module = load_library.load_op_library('tvm_dso_op.so') 56 | 57 | def apply(self, *params): 58 | if self.tvm_dso_op is None: 59 | num_inputs = len(params) 60 | self.tvm_dso_op = getattr(self.module, "tvm_dso_op%s" % num_inputs) 61 | 62 | return self.tvm_dso_op(*params, 63 | dynamic_output_shape=self.dynamic_output_shape, 64 | static_output_shape=self.static_output_shape, 65 | has_static_output_shape=self.has_static_output_shape, 66 | lib_path=self.lib_path, 67 | func_name=self.func_name, 68 | output_dtype=self.output_dtype) 69 | 70 | def __call__(self, *params): 71 | return self.apply(*params) 72 | 73 | def _is_static_shape(self, shape): 74 | if shape is None or not isinstance(shape, list): 75 | return False 76 | for d in shape: 77 | if not isinstance(d, int): 78 | return False 79 | if d < 0: 80 | raise Exception("Negative dimension is illegal: %d" % d) 81 | return True 82 | 83 | def _pack_shape_tensor(self, shape): 84 | if isinstance(shape, tf.Tensor): 85 | if shape.dtype == tf.int32: 86 | shape = tf.cast(shape, tf.int64) 87 | return shape 88 | elif isinstance(shape, list): 89 | shape_dims = [] 90 | for d in shape: 91 | if isinstance(d, int): 92 | shape_dims.append(tf.constant(d, tf.int64)) 93 | elif isinstance(d, tf.Tensor) and len(d.shape) == 0: 94 | if d.dtype == tf.int32: 95 | d = tf.cast(d, tf.int64) 96 | shape_dims.append(d) 97 | else: 98 | raise TypeError("Input shape dimension is neither scala tensor nor int") 99 | return tf.stack(shape_dims) 100 | else: 101 | raise TypeError("Input shape is neither tensor nor list") 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /src/tvm_dso_op_kernels.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "tensorflow/core/framework/op_kernel.h" 28 | 29 | #include "index_seq.h" 30 | 31 | using namespace tensorflow; 32 | 33 | typedef Eigen::ThreadPoolDevice CPUDevice; 34 | typedef Eigen::GpuDevice GPUDevice; 35 | typedef gtl::InlinedVector ShapeContainer; 36 | 37 | 38 | template 39 | class TVMDSOOpTrait; 40 | 41 | 42 | class TensorAsBuf { 43 | public: 44 | Tensor inline_tensor; 45 | Tensor* tensor; 46 | 47 | size_t size; 48 | size_t offset; 49 | 50 | int device_type; 51 | 52 | char* origin_buf; 53 | char* buf; 54 | 55 | void CopyToOrigin() { 56 | if (buf == origin_buf) { 57 | return; 58 | } 59 | if (device_type == kDLCPU) { 60 | memcpy(origin_buf, buf + offset, size); 61 | } else { 62 | cudaMemcpy(origin_buf, buf + offset, size, cudaMemcpyDeviceToDevice); 63 | } 64 | } 65 | 66 | void CopyFromOrigin() { 67 | if (buf == origin_buf) { 68 | return; 69 | } 70 | if (device_type == kDLCPU) { 71 | memcpy(buf + offset, origin_buf, size); 72 | } else { 73 | cudaMemcpy(buf + offset, origin_buf, size, cudaMemcpyDeviceToDevice); 74 | } 75 | } 76 | }; 77 | 78 | 79 | int GetDLPackDtype(const Tensor& tf_tensor, DLDataType* res) { 80 | auto dtype = tf_tensor.dtype(); 81 | if (dtype == DT_FLOAT) { 82 | res->code = kDLFloat; 83 | res->bits = 32; 84 | res->lanes = 1; 85 | } else if (dtype == DT_INT64) { 86 | res->code = kDLInt; 87 | res->bits = 64; 88 | res->lanes = 1; 89 | } else if (dtype == DT_INT32) { 90 | res->code = kDLInt; 91 | res->bits = 32; 92 | res->lanes = 1; 93 | } else { 94 | return -1; 95 | } 96 | return 0; 97 | } 98 | 99 | 100 | void EnsureAlignment(OpKernelContext* ctx, const Tensor& tensor, TensorAsBuf* out) { 101 | char* buf = (char*) tensor.tensor_data().data(); 102 | out->origin_buf = buf; 103 | out->size = tensor.TotalBytes(); 104 | 105 | int alignment = 64; 106 | char* aligned = (char*)(((uint64_t)buf + alignment - 1) & (~ (alignment - 1))); 107 | if (buf == aligned) { 108 | out->tensor = const_cast(&tensor); 109 | out->buf = buf; 110 | out->offset = 0; 111 | } else { 112 | TensorShape buf_shape; 113 | int64 dims[1] = { (int64)(tensor.TotalBytes() + alignment) }; 114 | TensorShapeUtils::MakeShape(dims, 1, &buf_shape); 115 | 116 | out->tensor = &out->inline_tensor; 117 | ctx->allocate_temp(tensor.dtype(), buf_shape, out->tensor); 118 | 119 | buf = (char*)(out->tensor->tensor_data().data()); 120 | char* buf_aligned = (char*)(((uint64_t)buf + alignment) & (~ (alignment - 1))); 121 | out->buf = buf; 122 | out->offset = buf_aligned - buf; 123 | } 124 | } 125 | 126 | 127 | int MakeDLTensor(const TensorAsBuf& src, const DLContext& ctx, int64_t* tf_shape, DLTensor* out) { 128 | DLDataType dlpack_type; 129 | const Tensor& tensor = *src.tensor; 130 | 131 | int status = GetDLPackDtype(tensor, &dlpack_type); 132 | if (status != 0) { 133 | return status; 134 | } 135 | out->ctx = ctx; 136 | out->ndim = tensor.shape().dims(); 137 | out->shape = tf_shape; 138 | out->strides = NULL; 139 | out->byte_offset = 0; 140 | out->dtype = dlpack_type; 141 | out->data = src.buf + src.offset; 142 | return 0; 143 | } 144 | 145 | 146 | template <> 147 | class TVMDSOOpTrait { 148 | public: 149 | static const int device_type = kDLCPU; 150 | 151 | static int device_id(OpKernelContext* context) { 152 | return 0; 153 | } 154 | 155 | }; 156 | 157 | 158 | template <> 159 | class TVMDSOOpTrait { 160 | public: 161 | static const int device_type = kDLGPU; 162 | 163 | static int device_id(OpKernelContext* context) { 164 | auto device_base = context->device(); 165 | auto gpu_device_info = device_base->tensorflow_gpu_device_info(); 166 | return gpu_device_info->gpu_id; 167 | } 168 | }; 169 | 170 | 171 | template 172 | class TVMDSOOp : public OpKernel { 173 | 174 | private: 175 | tvm::runtime::PackedFunc tvm_func; 176 | string lib_path; 177 | string func_name; 178 | 179 | DataType output_dtype; 180 | 181 | bool has_static_output_shape; 182 | std::vector static_output_shape; 183 | 184 | void initAttributes(OpKernelConstruction* context) { 185 | context->GetAttr("lib_path", &lib_path); 186 | context->GetAttr("func_name", &func_name); 187 | context->GetAttr("output_dtype", &output_dtype); 188 | 189 | context->GetAttr("has_static_output_shape", &has_static_output_shape); 190 | context->GetAttr("static_output_shape", &static_output_shape); 191 | } 192 | 193 | public: 194 | explicit TVMDSOOp(OpKernelConstruction* context) : OpKernel(context) { 195 | 196 | // Get attr 197 | initAttributes(context); 198 | 199 | // Load TVM function from dynamic library 200 | tvm::runtime::Module mod_dylib = tvm::runtime::Module::LoadFromFile(lib_path); 201 | LOG(INFO) << "Verify dynamic loading from " << lib_path << " device_type=" << TVMDSOOpTrait::device_type; 202 | tvm_func = mod_dylib.GetFunction(func_name); 203 | CHECK(tvm_func != nullptr); 204 | } 205 | 206 | void Compute(OpKernelContext* context) override { 207 | 208 | DLTensor args[NUM_INPUTS + 1]; 209 | TensorAsBuf buf_info[NUM_INPUTS]; 210 | ShapeContainer shapes[NUM_INPUTS]; 211 | 212 | int status; 213 | int device_id = TVMDSOOpTrait::device_id(context); 214 | int device_type = TVMDSOOpTrait::device_type; 215 | 216 | DLContext dl_ctx = { DLDeviceType(device_type), device_id }; 217 | 218 | // Get output shape 219 | TensorShape output_shape; 220 | auto& output_shape_tensor = context->input(NUM_INPUTS); 221 | if (has_static_output_shape) { 222 | // use static output shape 223 | const int64* dims = static_output_shape.data(); 224 | TensorShapeUtils::MakeShape(dims, static_output_shape.size(), &output_shape); 225 | } else if (output_shape_tensor.dims() == 1) { 226 | // use shape tensor values as output shape 227 | const int64* dims = output_shape_tensor.flat().data(); 228 | TensorShapeUtils::MakeShape(dims, 1, &output_shape); 229 | } else { 230 | // use input tensor shape by default 231 | output_shape = context->input(0).shape(); 232 | } 233 | 234 | for (int i = 0; i < NUM_INPUTS; ++i) { 235 | // Grab the input tensor 236 | auto& input_tensor = context->input(i); 237 | 238 | // Create shape container, should keep ref during execution 239 | shapes[i] = input_tensor.shape().dim_sizes(); 240 | auto shape_ptr = (int64_t*) shapes[i].data(); 241 | 242 | TensorAsBuf& input = buf_info[i]; 243 | input.device_type = device_type; 244 | 245 | EnsureAlignment(context, input_tensor, &input); 246 | input.CopyFromOrigin(); 247 | 248 | status = MakeDLTensor(input, dl_ctx, shape_ptr, &args[i]); 249 | OP_REQUIRES(context, status == 0, Status(error::INTERNAL, "Fail to create dlpack tensor for input")); 250 | } 251 | 252 | // Allocate output tensor 253 | Tensor* output_tensor; 254 | OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_tensor)); 255 | auto output_shape_dim_buf = output_tensor->shape().dim_sizes(); // should keep alive on stack 256 | auto output_shape_ptr = (int64_t*) output_shape_dim_buf.data(); 257 | 258 | TensorAsBuf output; 259 | output.device_type = device_type; 260 | EnsureAlignment(context, *output_tensor, &output); 261 | 262 | status = MakeDLTensor(output, dl_ctx, output_shape_ptr, &args[NUM_INPUTS]); 263 | OP_REQUIRES(context, status == 0, Status(error::INTERNAL, "Fail to create dlpack tensor for output")); 264 | 265 | apply_variadic_by_ptrs(tvm_func, args); 266 | 267 | output.CopyToOrigin(); 268 | } 269 | }; 270 | 271 | 272 | 273 | #define REGISTER_TFTVM_KERNEL(n) \ 274 | REGISTER_KERNEL_BUILDER(Name("TvmDsoOp" #n).Device(DEVICE_CPU), TVMDSOOp); \ 275 | REGISTER_KERNEL_BUILDER(Name("TvmDsoOp" #n).Device(DEVICE_GPU), TVMDSOOp); \ 276 | 277 | REGISTER_TFTVM_KERNEL(1) 278 | REGISTER_TFTVM_KERNEL(2) 279 | REGISTER_TFTVM_KERNEL(3) 280 | REGISTER_TFTVM_KERNEL(4) 281 | REGISTER_TFTVM_KERNEL(5) 282 | REGISTER_TFTVM_KERNEL(6) 283 | REGISTER_TFTVM_KERNEL(7) 284 | REGISTER_TFTVM_KERNEL(8) 285 | 286 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------