We need to satisfy quite a few interesting requirements
- Deployment: invoke the compiled function from python/javascript/c++ language.
- Debug: define a function in python and call that from a compiled function.
- Link: write driver code to call device specific code(CUDA) and call it from compiled host function.
- Prototype: define an IR pass from python and call that from C++ backend.
- Expose: compiler stack developed in c++ to front-end (i.e, python)
- Experiment: ship a compiled function to an embedded device directly run there.
We want to be able to define a function from any language and call from another.
We also want the runtime core to be minimal to deploy to embedded devices.
## PackedFunc
[PackedFunc](https://github.com/dmlc/tvm/blob/master/include/tvm/runtime/packed_func.h) is a simple but elegant solution
we find to solve the challenges listed. The following code block provides an example in C++
```c++
#include <tvm/runtime/packed_func.h>
voidMyAdd(TVMArgsargs,TVMRetValue*rv){
// automatically convert arguments to desired type.
inta=args[0];
intb=args[1];
// automatically assign value return to rv
*rv=a+b;
}
voidCallPacked(){
PackedFuncmyadd=PackedFunc(MyAdd);
// get back 3
intc=myadd(1,2);
}
```
In the above codeblock, we defined a PackedFunc MyAdd. It takes two arguments
: ```args``` represents input arguments and ```rv``` represents return value.
The function is type-erased, which means the function signature does not restrict which input type to pass in or type to return.
Under the hood, when we call a PackedFunc, it packs the input arguments to TVMArgs on stack,
and get the result back via TVMRetValue.
Thanks to template tricks in C++, we can call a PackedFunc just like a normal function. Because of its type-erased nature, we can call a PackedFunc from dynamic languages like python, without additional glue code for each new type function created.
The following example registers PackedFunc in C++ and calls from python.
```c++
// register a global packed function in c++
TVM_REGISTER_GLOBAL("myadd")
.set_body(MyAdd);
```
```python
importtvm
myadd=tvm.get_global_func("myadd")
# prints 3
print(myadd(1,2))
```
Most of the magic of PackedFunc lies in ```TVMArgs``` and ```TVMRetValue``` structure.
We restrict a list of possible types which can be passed, here are the common ones
- int, float and string
- PackedFunc itself
- Module for compiled modules
- DLTensor* for tensor object exchange
- TVM Node to represent any object in IR
The restriction makes the implementation simple without the need of serialization.
Despite being minimum, the PackedFunc is sufficient for the use-case of deep learning deployment as
most functions only take DLTensor or numbers.
Since one PackedFunc can take another PackedFunc as argument,
we can pass functions from python(as PackedFunc) to C++.
```c++
TVM_REGISTER_GLOBAL("callhello")
.set_body([](TVMArgsargs,TVMRetValue*rv){
PackedFuncf=args[0];
f("hello world");
});
```
```python
importtvm
defcallback(msg):
print(msg)
# convert to PackedFunc
f=tvm.convert(callback)
callhello=tvm.get_global_func("callhello")
# prints hello world
callhello(f)
```
TVM provides a [minimum C API](https://github.com/dmlc/tvm/blob/master/include/tvm/runtime/c_runtime_api.h),
that allows us to embedded the PackedFunc into any languages. Besides python, so far we supported
[java](https://github.com/dmlc/tvm/tree/master/jvm) and [javascript](https://github.com/dmlc/tvm/tree/master/web).
This philosophy of embedded API is very like Lua, except that we don't have a new language and uses C++.
One fun fact about PackedFunc is that we use it for both compiler and deployment stack.
- All TVM's compiler pass functions are exposed to frontend as PackedFunc, see [here](https://github.com/dmlc/tvm/tree/master/src/api)
- The compiled modules also returns compiled function as PackedFunc
To keep the runtime minimum, we isolated the IR Node support from the deployment runtime. The resulting runtime takes around 200K - 600K depending on how many runtime driver modules(e.g., CUDA) get included.
The overhead of calling into PackedFunc vs. a normal function is small, as it is only saving a few values on the stack.
So it is OK as long as we don't wrap small functions.
In summary, the PackedFunc is the universal glue in TVM where we use it extensively to support our compiler and deployment.
## Module
Since TVM support multiple types of devices, we need to support different type of drivers.
We have to use driver API to load the kernel, set up the argument in packed format and perform kernel launch.
We also need to patch up the driver API so that the exposed functions is threadsafe.
So we often need to implement these driver glues in C++ and expose them to the user.
We can certainly not do it for each type of functions, so again PackedFunc is our answer.
TVM defines the compiled object as [Module](https://github.com/dmlc/tvm/blob/master/include/tvm/runtime/module.h).
The user can get the compiled function from Module as PackedFunc.
The generated compiled code can dynamically get function from Module in runtime. It caches the function handle in the first call and reuses in subsequent calls. We use this to link device code and callback into any PackedFunc(e.g., python) from generated code.
The ModuleNode is an abstract class that can be implemented by each type of device.
So far we support modules for CUDA, Metal, OpenCL and loading dynamic shared libraries. This abstraction makes introduction
of new device easy, and we do not need to redo the host code generation for each type of device.
## Remote Deployment
The PackedFunc and Module system also makes it easy to ship the function into remote devices directly.
Under the hood, we have a RPCModule that serializes the arguments and do the data movement and launches the computation on the remote.
The RPC server itself is minimum and can be bundled into the runtime. We can start a minimum TVM
RPC server on iPhone/android/raspberry pi or even your browser. The cross compilation on server and shipping of the module for testing can be done in the same script. Checkout
[Cross compilation and RPC tutorial](http://docs.tvmlang.org/tutorials/deployment/cross_compilation_and_rpc.html#sphx-glr-tutorials-deployment-cross-compilation-and-rpc-py) for more details.
This instant feedback gives us a lot of advantages. For example, to test the correctness of generated code on iPhone, we no longer have to write test-cases in swift/objective-c from scratch -- We can use RPC to execute on iPhone copy the result back and do verification on my host via numpy. We can also do the profiling using the same script.
## TVM Node and Compiler Stack
As we mentioned earlier, we build compiler stack API on top of the PackedFunc runtime system.
We faced a constant changing the compiler API for the need of research. We need a new language object or IR node from now and then when we want to test out new primitives.
However, we don't want to change our API from time to time. Besides that, we also want to
- be able to serialize any language object and IRs
- be able to explore, print, and manipulate the IR objects in front-end language to do quick prototyping.
We introduced a base class, called [Node](https://github.com/dmlc/HalideIR/blob/master/src/tvm/node.h#L52) to solve this problem.
All the language object in compiler stack is a subclass of Node. Each node contains a string type_key that uniquely identifies
the type of object. We choose string instead of int as type key so new Node class can be added in decentralized fashion without
adding the code back to the central repo. To ease the speed of dispatching, we allocate an integer type_index at runtime for each type_key.
Since usually one Node object could be referenced in multiple places in the language. We use a shared_ptr to keep
track of reference. We use NodeRef class to represents a reference to the Node.
We can roughly view NodeRef class as shared_ptr to the Node container.
We can also define subclass NodeRef to hold each subtypes of Node. Each Node class needs to define the VisitAttr function.