file_path
stringlengths 7
180
| content
stringlengths 0
811k
| repo
stringclasses 11
values |
---|---|---|
python/tvm/topi/x86/tensor_intrin.py | # 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.
"""Core kernel of dot product of 4 Int8 operations"""
# pylint: disable=invalid-name
import tvm
from tvm import te
import tvm.target.codegen
from .utils import target_has_sse42, target_has_vnni, get_simd_32bit_lanes
def dot_16x1x16_uint8_int8_int32():
"""Dispatch the most optimized intrin depending on the target"""
mcpu = tvm.target.Target.current().mcpu
assert target_has_sse42(mcpu), "An old Intel machine that does not have fast Int8 support."
if target_has_vnni(mcpu):
# VNNI capable platform
return dot_16x1x16_uint8_int8_int32_cascadelake()
# vpmaddubsw/vpmaddwd fallback
return dot_16x1x16_uint8_int8_int32_skylake()
def dot_16x1x16_uint8_int8_int32_skylake():
"""
Int8 dot product by every 4 elements using AVX512 Skylake instructions.
This function takes two arrays of uint8 and int8 datatype -- data[4] and
kernel[16][4] -- and computes a dot product of data[4] with every
4 elements of kernels, resulting in output[16] of int32 datatype.
The pseudo code is as follows.
.. code-block:: c
void dot_16x1x16_uint8_int8_int32(uint8 data[4], int8 kernel[16][4],
int32 output[16]){
for (int i = 0; i < 16; i++){
output[i] = 0;
for (int k = 0; k < 4; k++){
output[i] += data[k] * kernel[i][k]
}
}
}
Physically, the kernel array sits in an AVX512 vector register and
the data[4] is broadcasted to another AVX512 vector register. This
function returns a TensorIntrin that can be used to tensorize
a schedule.
Returns
-------
intrin : TensorIntrin
The Skylake int8 TensorIntrin that can be used in tensorizing schedule
"""
int32_lanes = get_simd_32bit_lanes()
num_int8_elements = 4 # 4 int8 elements in int32
data = te.placeholder((num_int8_elements,), dtype="uint8", name="data")
kernel = te.placeholder((int32_lanes, num_int8_elements), dtype="int8", name="kernel")
k = te.reduce_axis((0, num_int8_elements), name="k")
C = te.compute(
(int32_lanes,),
lambda i: te.sum(data[k].astype("int32") * kernel[i, k].astype("int32"), axis=k),
name="C",
)
a_buffer = tvm.tir.decl_buffer(
data.shape, dtype="uint8", name="a_buffer", offset_factor=1, strides=[1]
)
b_buffer = tvm.tir.decl_buffer(
kernel.shape, dtype="int8", name="b_buffer", offset_factor=1, strides=[te.var("ldw"), 1]
)
def _intrin_func(ins, outs):
def _instr(index):
# int_lx32 - output datatype after pmaddubs - 16 bits to number of lanes
# int_8xl - input datatype to pmaddubs - 8 bits to number of lanes
# int_32xl - output datatype after pmaddw - 32 bits per number of lanes
if int32_lanes == 4:
int_lx32 = "int16x8"
int_8xl = "int8x16"
int_32xl = "int32x4"
pmaddubs = "llvm.x86.ssse3.pmadd.ub.sw.128"
pmaddw = "llvm.x86.sse2.pmadd.wd"
elif int32_lanes == 8:
int_lx32 = "int16x16"
int_8xl = "int8x32"
int_32xl = "int32x8"
pmaddubs = "llvm.x86.avx2.pmadd.ub.sw"
pmaddw = "llvm.x86.avx2.pmadd.wd"
elif int32_lanes == 16:
int_lx32 = "int16x32"
int_8xl = "int8x64"
int_32xl = "int32x16"
pmaddubs = "llvm.x86.avx512.pmaddubs.w.512"
pmaddw = "llvm.x86.avx512.pmaddw.d.512"
ib = tvm.tir.ir_builder.create()
if index == 1:
ib.emit(outs[0].vstore(0, tvm.tir.const(0, int_32xl)))
return ib.get()
a_int8 = ins[0].vload([0], "uint8x4")
re_int32 = tvm.tir.call_intrin("int32", "tir.reinterpret", a_int8)
vec_ai32 = re_int32.astype(int_32xl)
vec_a = tvm.tir.call_intrin(int_8xl, "tir.reinterpret", vec_ai32)
vec_b = ins[1].vload([0, 0], int_8xl)
vec_one = tvm.tir.const(1, int_lx32)
pair_reduction = tvm.tir.call_llvm_pure_intrin(
int_lx32,
pmaddubs,
tvm.tir.const(0, "uint32"),
vec_a,
vec_b,
)
quad_reduction = tvm.tir.call_llvm_pure_intrin(
int_32xl,
pmaddw,
tvm.tir.const(0, "uint32"),
pair_reduction,
vec_one,
)
if index == 0:
ib.emit(outs[0].vstore(0, quad_reduction))
else:
ib.emit(outs[0].vstore(0, quad_reduction + outs[0].vload([0], int_32xl)))
return ib.get()
# body, reset, update
return _instr(0), _instr(1), _instr(2)
buffer_params = {"offset_factor": 1}
return te.decl_tensor_intrin(
C.op,
_intrin_func,
binds={data: a_buffer, kernel: b_buffer},
default_buffer_params=buffer_params,
)
def dot_16x1x16_uint8_int8_int16():
"""
Int8 dot product by every 2 elements using AVX512 Skylake instructions.
This function takes two arrays of uint8 and int8 datatype -- data[2] and
kernel[4][32][2] -- and computes a dot product of data[2] with every
2 elements of kernels, resulting in output[4][32] of int16 datatype.
The pseudo code is as follows.
.. code-block:: c
void dot_16x1x16_uint8_int8_int16(uint8 data[2], int8 kernel[32*4][2],
int16 output[32*4]){
for (int i = 0; i< 4; i++){
for (int j = 0; j < 32; j++){
output[i][i] = 0;
for (int k = 0; k < 2; k++){
output[i][j][k] += data[k] * kernel[i][j][k]
}
}
}
}
Physically, the kernel array sits in four AVX512 vector registers and
the data[2] is broadcasted to another AVX512 vector register. This
function returns a TensorIntrin that can be used to tensorize
a schedule.
Returns
-------
intrin : TensorIntrin
The Skylake int8 TensorIntrin that can be used in tensorizing schedule
"""
int16_lanes = 4 * 32 # 4*32 int32 lanes in 4 AVX512 vector registers
num_int8_elements = 2 # 2 int8 elements in int16
data = te.placeholder((num_int8_elements,), dtype="uint8", name="data")
kernel = te.placeholder((int16_lanes, num_int8_elements), dtype="int8", name="kernel")
k = te.reduce_axis((0, num_int8_elements), name="k")
C = te.compute(
(int16_lanes,),
lambda i: te.sum(data[k].astype("int16") * kernel[i, k].astype("int16"), axis=k),
name="C",
)
a_buffer = tvm.tir.decl_buffer(
data.shape, dtype="uint8", name="a_buffer", offset_factor=1, strides=[1]
)
b_buffer = tvm.tir.decl_buffer(kernel.shape, dtype="int8", name="b_buffer", offset_factor=1)
# strides=[te.var('ldw'), 1, 1])
def _intrin_func(ins, outs):
def _instr(index):
ib = tvm.tir.ir_builder.create()
if index == 1:
for i in range(4):
ib.emit(outs[0].vstore([i * 32], tvm.tir.const(0, "int16x32")))
return ib.get()
a_int8 = ins[0].vload([0], "uint8x2")
re_int16 = tvm.tir.call_intrin("int16", "tir.reinterpret", a_int8)
vec_ai16 = re_int16.astype("int16x32")
vec_a = tvm.tir.call_intrin("int8x64", "tir.reinterpret", vec_ai16)
for i in range(4):
vec_b = ins[1].vload([i * 32, 0], "int8x64")
pair_reduction = tvm.tir.call_llvm_pure_intrin(
"int16x32",
"llvm.x86.avx512.pmaddubs.w.512",
tvm.tir.const(0, "uint32"),
vec_a,
vec_b,
)
if index == 0:
ib.emit(outs[0].vstore([i * 32], pair_reduction))
else:
ib.emit(
outs[0].vstore(
[i * 32], pair_reduction + outs[0].vload([i * 32], "int16x32")
)
)
return ib.get()
# body, reset, update
return _instr(0), _instr(1), _instr(2)
buffer_params = {"offset_factor": 1}
return te.decl_tensor_intrin(
C.op,
_intrin_func,
binds={data: a_buffer, kernel: b_buffer},
default_buffer_params=buffer_params,
)
def dot_16x1x16_uint8_int8_int32_cascadelake():
"""
Int8 dot product by every 4 elements using AVX512VNNI Cascade Lake instructions.
This function takes two arrays of uint8 and int8 datatype -- data[4] and
kernel[16][4] -- and computes a dot product of data[4] with every
4 elements of kernels, resulting in output[16] of int32 datatype.
The pseudo code is as follows.
.. code-block:: c
void dot_16x1x16_uint8_int8_int32_cascadelake(uint8 data[4], int8 kernel[16][4],
int32 output[16]){
for (int i = 0; i < 16; i++){
output[i] = 0;
for (int k = 0; k < 4; k++){
output[i] += data[k] * kernel[i][k]
}
}
}
Physically, the kernel array sits in an AVX512 vector register and
the data[4] is broadcasted to another AVX512 vector register. This
function returns a TensorIntrin that can be used to tensorize
a schedule.
Returns
-------
intrin : TensorIntrin
The Cascade Lake int8 TensorIntrin that can be used in tensorizing schedule
"""
int32_lanes = 16 # 16 int32 lanes in AVX512
num_int8_elements = 4 # 4 int8 elements in int32
data = te.placeholder((num_int8_elements,), dtype="uint8", name="data")
kernel = te.placeholder((int32_lanes, num_int8_elements), dtype="int8", name="kernel")
k = te.reduce_axis((0, num_int8_elements), name="k")
C = te.compute(
(int32_lanes,),
lambda i: te.sum(data[k].astype("int32") * kernel[i, k].astype("int32"), axis=k),
name="C",
)
a_buffer = tvm.tir.decl_buffer(
data.shape, dtype="uint8", name="a_buffer", offset_factor=1, strides=[1]
)
b_buffer = tvm.tir.decl_buffer(
kernel.shape, dtype="int8", name="b_buffer", offset_factor=1, strides=[te.var("ldw"), 1]
)
def _intrin_func(ins, outs):
def _instr(index):
ib = tvm.tir.ir_builder.create()
if index == 1:
ib.emit(outs[0].vstore(0, tvm.tir.const(0, "int32x16")))
return ib.get()
a_int8 = ins[0].vload([0], "uint8x4")
re_int32 = tvm.tir.call_intrin("int32", "tir.reinterpret", a_int8)
vec_ai32 = re_int32.astype("int32x16")
vec_b = ins[1].vload([0, 0], "int8x64")
vnni_inst_name = "llvm.x86.avx512.vpdpbusd.512"
llvm_id = tvm.target.codegen.llvm_lookup_intrinsic_id(vnni_inst_name)
if llvm_id != 0: # VNNI is available for current LLVM version
vec_bi32 = tvm.tir.call_intrin("int32x16", "tir.reinterpret", vec_b)
vec_c = outs[0].vload([0], "int32x16")
quad_reduction = tvm.tir.call_llvm_pure_intrin(
"int32x16",
"llvm.x86.avx512.vpdpbusd.512",
tvm.tir.const(0, "uint32"),
vec_c,
vec_ai32,
vec_bi32,
)
ib.emit(outs[0].vstore(0, quad_reduction))
else: # Fall back to the normal AVX512
vec_a = tvm.tir.call_intrin("int8x64", "tir.reinterpret", vec_ai32)
vec_one = tvm.tir.const(1, "int16x32")
pair_reduction = tvm.tir.call_llvm_pure_intrin(
"int16x32",
"llvm.x86.avx512.pmaddubs.w.512",
tvm.tir.const(0, "uint32"),
vec_a,
vec_b,
)
quad_reduction = tvm.tir.call_llvm_pure_intrin(
"int32x16",
"llvm.x86.avx512.pmaddw.d.512",
tvm.tir.const(0, "uint32"),
pair_reduction,
vec_one,
)
if index == 0:
ib.emit(outs[0].vstore(0, quad_reduction))
else:
ib.emit(outs[0].vstore(0, quad_reduction + outs[0].vload([0], "int32x16")))
return ib.get()
# body, reset, update
return _instr(0), _instr(1), _instr(2)
buffer_params = {"offset_factor": 1}
return te.decl_tensor_intrin(
C.op,
_intrin_func,
binds={data: a_buffer, kernel: b_buffer},
default_buffer_params=buffer_params,
)
| https://github.com/zk-ml/tachikoma |
python/tvm/topi/x86/utils.py | # 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.
"""Common x86 related utilities"""
import tvm
@tvm._ffi.register_func("tvm.topi.x86.utils.target_has_sse41")
def target_has_sse41(target):
return (
target_has_sse42(target)
or target_has_avx(target)
or target_has_avx2(target)
or target_has_avx512(target)
or target_has_vnni(target)
or target
in {
"btver2",
"penryn",
}
)
@tvm._ffi.register_func("tvm.topi.x86.utils.target_has_sse42")
def target_has_sse42(target):
return (
target_has_avx(target)
or target_has_avx2(target)
or target_has_avx512(target)
or target_has_vnni(target)
or target
in {
"silvermont",
"slm",
"goldmont",
"goldmont-plus",
"tremont",
"nehalem",
"corei7",
"westmere",
"bdver1",
"bdver2",
"bdver3",
"x86-64-v2",
}
)
@tvm._ffi.register_func("tvm.topi.x86.utils.target_has_avx")
def target_has_avx(target):
return (
target_has_avx2(target)
or target_has_avx512(target)
or target_has_vnni(target)
or target in {"sandybridge", "corei7-avx", "ivybridge", "core-avx-i"}
)
@tvm._ffi.register_func("tvm.topi.x86.utils.target_has_avx2")
def target_has_avx2(target):
return (
target_has_avx512(target)
or target_has_vnni(target)
or target
in {
"haswell",
"core-avx2",
"broadwell",
"skylake",
"bdver4",
"znver1",
"znver2",
"znver3",
"x86-64-v3",
}
)
@tvm._ffi.register_func("tvm.topi.x86.utils.target_has_avx512")
def target_has_avx512(target):
return target in {
"skylake-avx512",
"skx",
"knl",
"knm",
"x86-64-v4",
"cannonlake",
# explicit enumeration of VNNI capable due to collision with alderlake
"cascadelake",
"icelake-client",
"icelake-server",
"rocketlake",
"tigerlake",
"cooperlake",
"sapphirerapids",
}
@tvm._ffi.register_func("tvm.topi.x86.utils.target_has_vnni")
def target_has_vnni(target):
return target in {
"cascadelake",
"icelake-client",
"icelake-server",
"rocketlake",
"tigerlake",
"cooperlake",
"sapphirerapids",
"alderlake",
}
@tvm._ffi.register_func("tvm.topi.x86.utils.get_simd_32bit_lanes")
def get_simd_32bit_lanes():
mcpu = tvm.target.Target.current().mcpu
fp32_vec_len = 4
if target_has_avx512(mcpu):
fp32_vec_len = 16
elif target_has_avx2(mcpu):
fp32_vec_len = 8
return fp32_vec_len
| https://github.com/zk-ml/tachikoma |
python/tvm/utils/__init__.py | # 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.
"""Utilities operating at a graph/model or other "high" level"""
from .roofline import roofline_analysis
| https://github.com/zk-ml/tachikoma |
python/tvm/utils/roofline/__init__.py | # 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.
"""Utilities for computing an approximate roofline model"""
from typing import Dict, Optional, Union
import numpy as np
from ... import IRModule, auto_scheduler, build, get_global_func, nd, relay, tir, topi, transform
from ...contrib import utils
from ...ir.expr import GlobalVar
from ...ir.instrument import pass_instrument
from ...rpc.base import RPC_SESS_MASK
from ...rpc.client import RPCSession
from ...runtime import Device, num_threads, profiler_vm, profiling
from ...script import tir as T
from ...target import Target
from . import cuda, registry, x86
def _create_args(mod: IRModule, dev: Device, func_name: str = "main", remote=None):
if dev.device_type >= RPC_SESS_MASK:
random_fill = remote.get_function("tvm.contrib.random.random_fill")
else:
random_fill = get_global_func("tvm.contrib.random.random_fill")
assert random_fill, "Please make sure USE_RANDOM is ON in config.cmake"
args = []
for arg in mod[func_name].params:
ary = nd.empty(
[x.value for x in arg.type_annotation.shape],
arg.type_annotation.dtype,
device=dev,
)
random_fill(ary)
args.append(ary)
return args
@pass_instrument
class SaveLoweredTIR:
"""Save TIR functions from right before final lowering. Right now this
means right before tir.MakePackedAPI."""
def __init__(self):
self.functions = {}
def run_before_pass(self, mod, info):
if info.name == "tir.MakePackedAPI":
for v, func in mod.functions.items():
if isinstance(func, tir.PrimFunc):
self.functions[v] = func
def roofline_from_existing(
report: profiling.Report,
tir_functions: Dict[GlobalVar, tir.PrimFunc],
target: Target,
dev: Device,
remote: Optional[RPCSession] = None,
) -> profiling.Report:
"""Add roofline and other estimated statistics to an existing profiling report.
:py:func:`roofline_analysis` should always be used instead of this function
unless you need a custom compilation pipeline.
Calculating roofline statistics requires features extracted the TIR
functions in addition to per-operator runtime information (`report`) of the
same TIR features. The features and TIR functions are not included with the
compiled library used to generate the per-operator runtime. It is essential
that the per-operator information comes from the exact same compilation
pipeline as the TIR functions.
Example
-------
..code: : python
import tvm
import tvm.relay
mod, params = tvm.relay.testing.mlp.get_workload()
# it is recommended to use SaveLoweredTIR to get out the tir primfuncs
save_tir = tvm.utils.roofline.SaveLoweredTIR()
with tvm.transform.PassContext(opt_level=3, pass_instrument=[save_tir]):
lib = relay.vm.compile(mod, params=params, target=target)
vmexec = profiler_vm.VirtualMachineProfiler(lib, dev)
report = vmexec.profile(*inputs)
roofline_report = roofline_from_existing(report, save_tir.functions, target, dev)
Parameters
----------
report : Report
Existing profiling report from :py:method:`VirtualMachineProfiler.profile`.
tir_functions : Dict[GlobalVar, PrimFunc]
TIR primfuncs from the module run to generate `report`. It is nessesary
that these functions come before the `tir.MakePackedAPI` pass and are
compatible with auto_scheduler featurization.
:py:class:`SaveLoweredTIR` is the recommended way to collect these
functions.
target : Target
TVM target that `report` was generated with.
dev : Device
Device that `report` was generated with.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
Returns
-------
profiling.Report
New profiling report that includes all information from `report`
along with additional roofline metrics. See
:py:func:`roofline_analysis` for more information on which metrics
are included.
"""
all_features = {
prim.attrs["hash"]: (name, prim, auto_scheduler.feature.named_features_from_primfunc(prim))
for name, prim in tir_functions.items()
if isinstance(prim, tir.PrimFunc) and "hash" in prim.attrs.keys()
}
new_calls = []
for call in report.calls:
if "Hash" in call.keys() and call["Hash"] in all_features:
_, prim, features = all_features[call["Hash"]]
with target:
flops, peak_flops, flops_name = registry.estimate_peak_flops(
prim, features, target, dev, remote
)
loaded_bytes, peak_bandwidth, bandwidth_name = registry.estimate_peak_bandwidth(
prim, features, target, dev, remote
)
ridge_point = peak_flops / peak_bandwidth
runtime = call["Duration (us)"].microseconds * 1e-6
arith_inten = flops / loaded_bytes
call = dict(call)
call["Loaded Bytes"] = profiling.Count(int(loaded_bytes))
call["Estimated FLOPs"] = profiling.Count(int(flops))
call["Arithmetic Intensity"] = profiling.Ratio(arith_inten)
call["FLOP/s"] = profiling.Ratio(flops / runtime)
call["Bandwidth"] = profiling.Ratio(loaded_bytes / runtime)
compute_bound = arith_inten > ridge_point
call["Bound"] = "compute" if compute_bound else "memory"
per_mem_bound = (loaded_bytes / runtime) / peak_bandwidth * 100
per_compute_bound = (flops / runtime) / peak_flops * 100.0
# We use ratio here because the percentages should be averaged instead of summed.
call["Percent of Theoretical Optimal"] = profiling.Ratio(
per_compute_bound if compute_bound else per_mem_bound
)
new_calls.append(call)
else:
new_calls.append(call)
new_configuration = dict(report.configuration.items())
new_configuration[f"Estimated Peak FLOP/s ({flops_name})"] = profiling.Ratio(peak_flops)
new_configuration[
f"Estimated Peak Bandwidth ({bandwidth_name}, byte/second)"
] = profiling.Ratio(peak_bandwidth)
return profiling.Report(new_calls, report.device_metrics, new_configuration)
def roofline_analysis(
mod: IRModule,
params: Dict[str, nd.NDArray],
target: Union[str, Target],
dev: Device,
remote: Optional[RPCSession] = None,
) -> profiling.Report:
"""
Create a profiling report that contains roofline and other estimated
statistics from running a module on the VM.
The roofline model measures how close a operator gets to best possible
memory bandwidth or FLOP/s depending on whether it is memory or compute
bound. This computation uses the runtime of the operator along with two
numbers extracted from the TIR code: bytes of memory touched and number of
floating point operations.
These statistics are calculated by analyzing the lowered TIR of each
operator, so they are estimates of the true values. The statistics are:
- Bound: Is the operator memory or compute bound. This is computed by
assuming that the operator could perfectly cache all loads -- each byte
of memory is only loaded once.
- Percent of Theoretical Optimal: What percent of theoretical optimal for
the bound. i.e. percent of peak memory bandwidth if memory bound,
percent of peak FLOP/s if compute bound.
- Loaded Bytes: estimation of the number of bytes loaded from main memory.
- Estimated Flops: estimated number of floating point operations.
- Arithmetic Intensity: ratio of FLOPs per byte of data.
- FLOP/s: floating point operations per second.
- Bandwidth: Number of bytes loaded per second.
Parameters
----------
mod : IRModule
Uncompiled input module
params : Dict[str, nd.NDArray]
target : Union[str, Target]
Target to run on.
dev : Device
Device to run on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
Returns
-------
report : profiling.Report
Profiling report which includes the estimated statistics.
"""
if isinstance(target, str):
target = Target(target)
save_tir = SaveLoweredTIR()
# copy existing context but add our instrument
pass_ctx = transform.PassContext.current()
with transform.PassContext(
opt_level=pass_ctx.opt_level,
required_pass=pass_ctx.required_pass,
disabled_pass=pass_ctx.disabled_pass,
instruments=list(pass_ctx.instruments) + [save_tir],
config=pass_ctx.config,
):
lib = relay.vm.compile(mod, params=params, target=target)
# upload to remote if running over rpc
if dev.device_type >= RPC_SESS_MASK:
if remote is None:
raise RuntimeError("A RPCSession must be provided when using a remote device.")
temp = utils.tempdir()
path = temp.relpath("roofline_lib.tar")
lib.mod.export_library(path)
remote.upload(path)
lib = remote.load_module("roofline_lib.tar")
vmexec = profiler_vm.VirtualMachineProfiler(lib, dev)
args = _create_args(mod, dev, remote=remote)
report = vmexec.profile(*args)
return roofline_from_existing(report, save_tir.functions, target, dev, remote=remote)
| https://github.com/zk-ml/tachikoma |
python/tvm/utils/roofline/cuda.py | # 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.
"""Estimation of peak flops and memory bandwidth for cuda devices"""
import functools
import re
from typing import Dict, Optional, Tuple
import numpy as np
from ... import build, nd, transform
from ...contrib import nvcc, utils
from ...rpc.base import RPC_SESS_MASK
from ...rpc.client import RPCSession
from ...runtime import Device
from ...script import tir as T
from ...target import Target
from ...tir import PrimFunc
from . import registry
@functools.lru_cache(maxsize=None)
def estimate_peak_flops_tensorcore(
target: Target,
dev: Device,
remote: Optional[RPCSession],
mat_dtype: str = "float16",
acc_dtype: str = "float32",
) -> Tuple[float, float, str]:
"""Estimate the peak FLOP/s of a cuda device with tensorcores.
This estimate should only be used to compare with operators that can use
dense tensorcore mma instructions.
References
----------
Wei Sun, Ang Li, Tong Geng, Sander Stuijk, Henk Corporaal: "Dissecting
Tensor Cores via Microbenchmarks: Latency, Throughput and Numerical
Behaviors", 2022; http://arxiv.org/abs/2206.02874
https://www.nvidia.com/content/PDF/nvidia-ampere-ga-102-gpu-architecture-whitepaper-v2.1.pdf
Parameters
----------
target : Target
Target to run on. This should be as specific to the actual hardware as
possible.
dev : Device
Device to run on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
mat_dtype : str
Dtype of matrices passed to mma instructions.
acc_dtype : str
Dtype of accumulator to use with mma instructions. Should be compatible
with `mat_dtype`.
Returns
-------
peak_flops : float
Approximate sustained FLOP/s of this target/device combo assuming
mma instructions. Addition and multiplications are each counted as
separate FLOPs.
"""
@T.prim_func
def peak_flops_tensorcore_tir(
inp: T.Buffer((16, 16), mat_dtype),
out: T.Buffer((16, 16), acc_dtype),
n: T.int32,
sms: T.int32,
):
# pylint: disable=invalid-name, missing-function-docstring
A = T.alloc_buffer((16, 16), dtype=mat_dtype, scope="wmma.matrix_a")
B = T.alloc_buffer((16, 16), dtype=mat_dtype, scope="wmma.matrix_b")
C = T.alloc_buffer((16, 16), dtype=acc_dtype, scope="wmma.accumulator")
for _ in T.thread_binding(sms, thread="blockIdx.x"):
for _ in T.thread_binding(
8, thread="threadIdx.y"
): # need 8 warps to get enough in-SM parallelism
for _ in T.thread_binding(32, thread="threadIdx.x"):
T.evaluate(
T.tvm_load_matrix_sync(
A.data,
16,
16,
16,
0,
T.tvm_access_ptr(
T.type_annotation(dtype=mat_dtype),
inp.data,
0,
16,
1,
dtype="handle",
),
16,
"row_major",
dtype="handle",
)
)
T.evaluate(T.tvm_fill_fragment(B.data, 16, 16, 16, 0, 0, dtype="handle"))
T.evaluate(T.tvm_fill_fragment(C.data, 16, 16, 16, 0, 0, dtype="handle"))
for _ in range(n):
T.evaluate(
T.tvm_mma_sync(
C.data, 0, A.data, 0, B.data, 0, C.data, 0, dtype="handle"
)
)
T.evaluate(
T.tvm_store_matrix_sync(
C.data,
16,
16,
16,
0,
T.tvm_access_ptr(
T.type_annotation(dtype=acc_dtype),
out.data,
0,
16,
2,
dtype="handle",
),
16,
"row_major",
dtype="handle",
)
)
n = 100000
sms = dev.multi_processor_count
specialized = peak_flops_tensorcore_tir.specialize(
{peak_flops_tensorcore_tir.params[2]: n, peak_flops_tensorcore_tir.params[3]: sms}
)
with transform.PassContext(opt_level=3):
f = build(specialized, target=target)
# upload to remote if running over rpc
if dev.device_type >= RPC_SESS_MASK:
if remote is None:
raise RuntimeError("A RPCSession must be provided when using a remote device.")
temp = utils.tempdir()
path = temp.relpath("peak_fma_flops.tar")
f.export_library(path)
remote.upload(path)
f = remote.load_module("peak_fma_flops.tar")
x = nd.empty((16, 16), dtype=mat_dtype, device=dev)
y = nd.empty((16, 16), dtype=acc_dtype, device=dev)
times = f.time_evaluator(f.entry_name, dev, repeat=10, number=1)(x, y)
# each mma operation computes 16 x 16 x 16 FLOPs
return n * 16 * 16 * 16 * 2 * sms * 8 / times.min
@registry.estimate_peak_flops.register("cuda")
def estimate_peak_flops(
func: PrimFunc, # pylint: disable=unused-argument
features: Dict[str, np.ndarray],
target: Target,
dev: Device,
remote: Optional[RPCSession],
) -> Tuple[float, float, str]:
"""Estimate the peak FLOP/s of a cuda device.
Parameters
----------
func : PrimFunc
Function to estimate peak flops for. Used to check if a specific kind
intrinsic or dtype could be used with this function.
features : Dict[str, np.ndarry]
Features extracted from `func`. Used to check if a specific kind
intrinsic or dtype could be used with this function.
target : Target
Target to run on. This should be as specific to the actual hardware as
possible.
dev : Device
Device to run on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
Returns
-------
flops : float
Estimated number of flops used by `func`.
peak_flops : float
Approximate sustained FLOP/s of this target/device combo. Addition and
multiplications are each counted as separate FLOPs.
name : str
Dtype/intrinsic used by `func` to achieve peak flops.
"""
assert nvcc.have_tensorcore(
dev.compute_version
), "CUDA roofline only works with devices that have tensorcores"
flops = np.sum(
features["float_addsub"]
+ features["float_mul"]
+ features["float_mad"] * 2
+ features["float_divmod"]
)
peak_flops = estimate_peak_flops_tensorcore(target, dev, remote)
return flops, peak_flops, "float16 tensorcore"
@T.prim_func
def peak_bandwidth_tir(a: T.handle, b: T.handle, blocks: T.int32, warp_size: T.int32) -> None:
# pylint: disable=invalid-name, missing-function-docstring
N = T.var("int32")
A = T.match_buffer(a, [blocks, N, 4, warp_size], "float32")
B = T.match_buffer(b, [blocks, 4, warp_size], "float32")
for i in T.thread_binding(blocks, "blockIdx.x"):
for k in T.serial(N):
for l in T.unroll(4):
# vectorized load is necessary to hit peak bandwidth
for j in T.thread_binding(warp_size, "threadIdx.x"):
# += is necessary to introduce a data dependency for all
# elements of A, preventing the backend from removing the
# `k` loop and setting `k` to the loop extent.
B[i, l, j] += A[i, k, l, j]
@functools.lru_cache(maxsize=None)
def estimate_peak_bandwidth_global_mem(
target: Target,
dev: Device,
remote: Optional[RPCSession] = None,
) -> Tuple[float, float, str]:
"""Estimate peak bandwidth of global memory. See estimate_peak_bandwidth"""
warp_size = dev.warp_size
# These sizes seem large enough to give the card time to hit a fixpoint on memory bandwidth
blocks = 1024
size = 1024
specialized = peak_bandwidth_tir.specialize(
{peak_bandwidth_tir.params[2]: blocks, peak_bandwidth_tir.params[3]: warp_size}
)
with transform.PassContext(opt_level=3):
f = build(specialized, target=target)
# upload to remote if running over rpc
if dev.device_type >= RPC_SESS_MASK:
if remote is None:
raise RuntimeError("A RPCSession must be provided when using a remote device.")
temp = utils.tempdir()
path = temp.relpath("peak_bandwidth.tar")
f.export_library(path)
remote.upload(path)
f = remote.load_module("peak_bandwidth.tar")
a = nd.empty((blocks, size, 4, warp_size), dtype="float32", device=dev)
b = nd.empty((blocks, 4, warp_size), dtype="float32", device=dev)
times = f.time_evaluator(f.entry_name, dev, repeat=10, number=1)(a, b)
return a.numpy().size * 4 / times.min # 4 bytes per float32
@registry.estimate_peak_bandwidth.register("cuda")
def estimate_peak_bandwidth(
func: PrimFunc, # pylint: disable=unused-argument
features: Dict[str, np.ndarray],
target: Target,
dev: Device,
remote: Optional[RPCSession] = None,
) -> Tuple[float, float, str]:
"""Estimate peak memory bandwidth of a target/device combo.
Peak bandwidth is estimated by running a small experiment on the underlying
hardware. The peak bandwidth measurement assumes that vector instructions
are being used to load the data.
Parameters
----------
func : PrimFunc
Function to estimate peak bandwidth for. Used to check if a specific
kind of memory could be used with this function.
features : Dict[str, np.ndarry]
Features extracted from `func`. Used to check if a specific kind of
memory could be used with this function.
target : Target
Target to use for measurement. This target should be as specific to the
underlying hardware as possible.
dev : Device
Device to measure peak bandwidth on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
Returns
-------
loaded_bytes : float
Estimated bytes loaded by `func`.
peak_bandwidth : float
Peak memory bandwidth in bytes/seconds.
name : str
Name of the memory being used.
"""
# autoscheduler features do not take into account that 1.
# global and shared memory have very different performance
# characteristics -- both are included in the same bytes
# touched count 2. multiple threads accessing the same byte
# of memory does not use the same amount of bandwidth as
# multiple threads accessing different bytes of memory. We
# use unique bytes accessed here to avoid these two issues,
# but this does bias results towards being more compute
# bound.
loaded_bytes = sum(
[
np.sum(x)
for (k, x) in features.items()
if re.match(r"^B[0-9]+\.unique_bytes$", k) is not None
]
)
peak_bandwidth = estimate_peak_bandwidth_global_mem(target, dev, remote)
return loaded_bytes, peak_bandwidth, "global"
| https://github.com/zk-ml/tachikoma |
python/tvm/utils/roofline/registry.py | # 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.
"""Definition of generic functions for estimating peak flops and bandwidth"""
from typing import Dict, Optional, Tuple
import numpy as np
from ...rpc.client import RPCSession
from ...runtime import Device
from ...target import Target, generic_func
from ...tir import PrimFunc
@generic_func
def estimate_peak_bandwidth(
func: PrimFunc,
features: Dict[str, np.ndarray],
target: Target,
dev: Device,
remote: Optional[RPCSession] = None,
) -> Tuple[float, float, str]:
"""Estimate peak memory bandwidth of a target/device combo.
Peak bandwidth is estimated by running a small experiment on the underlying
hardware. The peak bandwidth measurement assumes that vector instructions
are being used to load the data.
Parameters
----------
func : PrimFunc
Function to estimate peak bandwidth for. Used to check if a specific
kind of memory could be used with this function.
features : Dict[str, np.ndarry]
Features extracted from `func`. Used to check if a specific kind of
memory could be used with this function.
target : Target
Target to use for measurement. This target should be as specific to the
underlying hardware as possible.
dev : Device
Device to measure peak bandwidth on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
Returns
-------
loaded_bytes : float
Estimated bytes loaded by `func`.
peak_bandwidth : float
Peak memory bandwidth in bytes/seconds.
name : str
Name of the memory being used.
"""
raise NotImplementedError()
@generic_func
def estimate_peak_flops(
func: PrimFunc,
features: Dict[str, np.ndarray],
target: Target,
dev: Device,
remote: Optional[RPCSession],
) -> Tuple[float, float, str]:
"""
Estimate the maximum number of FLOP/s this target/device combo is capable
of reaching by running a test program. This is a generic function that
should be overridden for each target.
Parameters
----------
func : PrimFunc
Function to estimate peak flops for. Used to check if a specific kind
intrinsic or dtype could be used with this function.
features : Dict[str, np.ndarry]
Features extracted from `func`. Used to check if a specific kind
intrinsic or dtype could be used with this function.
target : Target
Target to run on. This should be as specific to the actual hardware as
possible to make sure that LLVM generates the best vector code.
dev : Device
Device to run on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
Returns
-------
flops : float
Estimated number of flops used by `func`.
peak_flops : float
Approximate sustained FLOP/s of this target/device combo assuming
vectorized FMA instructions. Each FMA operation counts as two FLOPs.
name : str
Dtype/intrinsic used by `func` to achieve peak flops.
"""
raise NotImplementedError()
| https://github.com/zk-ml/tachikoma |
python/tvm/utils/roofline/x86.py | # 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.
"""Estimate peak flops and bandwidth for x86 devices"""
import functools
import re
from typing import Dict, Optional, Tuple
import numpy as np
from ... import build, get_global_func, nd, topi, transform
from ...contrib import utils
from ...rpc.base import RPC_SESS_MASK
from ...rpc.client import RPCSession
from ...runtime import DataType, Device, num_threads
from ...script import tir as T
from ...target import Target
from ...tir import PrimFunc
from . import registry
def _detect_vec_width_registers(
target: Target, vec_width: Optional[int], num_vector_registers: Optional[int]
):
"""Get the vector width and number of vector registers for a target.
Parameters
----------
target : Target
Target to detect vector width and registers for.
vec_width : Optional[int]
If None, try and detect vector width from target. Otherwise provided input is used.
num_vector_registers : Optional[int]
If None, try and number of vector registers from target. Otherwise provided input is used.
Returns
-------
vec_width: int
Width of a vector register on `target` in bytes.
num_vector_registers: int
Number of vector registers on `target`.
"""
if vec_width is None:
# Only implemented for x86 so far...
if (
str(target.kind) == "llvm"
and target.device_name == ""
and len(target.keys) == 1
and target.keys[0] == "cpu"
):
with target:
vec_width = topi.x86.utils.get_simd_32bit_lanes() * 4 # in number of bytes
else:
raise RuntimeError(f"Cannot determine vector width for target {target}")
if num_vector_registers is None:
if target.device_name == "": # indicates x86
num_vector_registers = 16 # Assuming for all platforms, probably wrong on older ones
else:
raise RuntimeError(f"Cannot determine number of vector registers for target {target}")
return vec_width, num_vector_registers
@functools.lru_cache(maxsize=None)
def estimate_peak_fma_vector_flops(
target: Target,
dev: Device,
remote: Optional[RPCSession],
dtype: DataType,
vec_width: Optional[int] = None,
num_vector_registers: Optional[int] = None,
):
"""Estimate peak flops assuming vector fma instructions and no explicit
intrinsics. See estimate_peak_fma_flops.
"""
@T.prim_func
def peakflops_fma_tir(
a: T.handle,
vec_width: T.int32,
iters: T.int32,
num_vector_registers: T.int32,
threads: T.int32,
) -> None:
# pylint: disable=invalid-name, missing-function-docstring
A = T.match_buffer(a, [threads, num_vector_registers, vec_width], dtype)
for t in T.parallel(threads):
for _j in range(iters):
for l in T.unroll(num_vector_registers):
# We want to use as few registers as possible, so we perform
# all operations on the same element
for k in T.vectorized(vec_width):
A[t, l, k] = A[t, l, k] * A[t, l, k] + A[t, l, k]
vec_width, num_vector_registers = _detect_vec_width_registers(
target, vec_width, num_vector_registers
)
vec_width //= DataType(dtype).bits // 8
iters = 1000000
nthreads = num_threads()
specialized = peakflops_fma_tir.specialize(
{
peakflops_fma_tir.params[1]: vec_width,
peakflops_fma_tir.params[2]: iters,
peakflops_fma_tir.params[3]: num_vector_registers,
peakflops_fma_tir.params[4]: nthreads,
}
)
with transform.PassContext(opt_level=3):
f = build(specialized, target=target)
# upload to remote if running over rpc
if dev.device_type >= RPC_SESS_MASK:
if remote is None:
raise RuntimeError("A RPCSession must be provided when using a remote device.")
temp = utils.tempdir()
path = temp.relpath("peak_fma_flops.tar")
f.export_library(path)
remote.upload(path)
f = remote.load_module("peak_fma_flops.tar")
random_fill = remote.get_function("tvm.contrib.random.random_fill")
else:
random_fill = get_global_func("tvm.contrib.random.random_fill")
assert random_fill, "Please make sure USE_RANDOM is ON in config.cmake"
a = nd.empty((nthreads, num_vector_registers, vec_width), dtype=dtype, device=dev)
random_fill(a)
times = f.time_evaluator(f.entry_name, dev, repeat=100, number=1)(a)
flops = 2 * vec_width * num_vector_registers * nthreads * iters # fma is two flops
return flops / times.min
@registry.estimate_peak_flops.register("cpu")
def estimate_peak_fma_flops(
func: PrimFunc,
features: Dict[str, np.ndarray],
target: Target,
dev: Device,
remote: Optional[RPCSession],
vec_width: Optional[int] = None,
num_vector_registers: Optional[int] = None,
) -> Tuple[float, float, str]:
"""
Estimate the maximum number of FLOP/s this target/device combo is capable
of reaching by running a test program. This assumes vectorized FMA
(fused-multiply-add) instructions.
Parameters
----------
func : PrimFunc
Function to estimate peak flops for. Used to check if a specific kind
intrinsic or dtype could be used with this function.
features : Dict[str, np.ndarry]
Features extracted from `func`. Used to check if a specific kind
intrinsic or dtype could be used with this function.
target : Target
Target to run on. This should be as specific to the actual hardware as
possible to make sure that LLVM generates the best vector code.
dev : Device
Device to run on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
vec_width : Optional[int]
Vector width of SIMD units on the underlying hardware. Will try to
infer if no value is provided.
num_vector_registers : Optional[int]
Number of vector registers on the underlying hardware. Will try to
infer if no value is provided.
Returns
-------
flops : float
Estimated number of flops used by `func`.
peak_flops : float
Approximate sustained FLOP/s of this target/device combo assuming
vectorized FMA instructions. Each FMA operation counts as two FLOPs.
name : str
Dtype/intrinsic used by `func` to achieve peak flops.
"""
# assume that the first argument's dtype is the one we want
dtype = list(func.buffer_map.values())[0].dtype
if "int" in dtype:
flops = np.sum(
features["int_addsub"]
+ features["int_mul"]
+ features["int_mad"] * 2
+ features["int_divmod"]
)
else:
flops = np.sum(
features["float_addsub"]
+ features["float_mul"]
+ features["float_mad"] * 2
+ features["float_divmod"]
)
peak_flops = estimate_peak_fma_vector_flops(
target, dev, remote, dtype, vec_width, num_vector_registers
)
return flops, peak_flops, f"{dtype} FMA"
@T.prim_func
def peak_bandwidth_tir(a: T.handle, b: T.handle, threads: T.int32, vec_width: T.int32) -> None:
# pylint: disable=invalid-name, missing-function-docstring
N = T.var("int32")
A = T.match_buffer(a, [threads, N, 4, vec_width], "float32")
B = T.match_buffer(b, [threads, 4, vec_width], "float32")
# Parallelism is necessary to hit all cores/nodes
for i in T.parallel(threads):
for k in T.serial(N):
for l in T.unroll(4):
# vectorized load is necessary to hit peak bandwidth
for j in T.vectorized(vec_width):
# += is necessary to introduce a data dependency for all
# elements of A, preventing the backend from removing the
# `k` loop and setting `k` to the loop extent.
B[i, l, j] += A[i, k, l, j]
@functools.lru_cache(maxsize=None)
def estimate_peak_bandwidth_dram(
target: Target,
dev: Device,
remote: Optional[RPCSession],
vec_width: Optional[int] = None,
) -> float:
"""Estimate peak bandwidth for DRAM. See estimate_peak_bandwidth."""
vec_width, _ = _detect_vec_width_registers(target, vec_width, 1)
specialized = peak_bandwidth_tir.specialize(
{
peak_bandwidth_tir.params[3]: vec_width,
}
)
with transform.PassContext(opt_level=3):
f = build(specialized, target=target)
# upload to remote if running over rpc
if dev.device_type >= RPC_SESS_MASK:
if remote is None:
raise RuntimeError("A RPCSession must be provided when using a remote device.")
temp = utils.tempdir()
path = temp.relpath("peak_bandwidth.tar")
f.export_library(path)
remote.upload(path)
f = remote.load_module("peak_bandwidth.tar")
random_fill = remote.get_function("tvm.contrib.random.random_fill")
else:
random_fill = get_global_func("tvm.contrib.random.random_fill")
assert random_fill, "Please make sure USE_RANDOM is ON in config.cmake"
threads = num_threads()
# Data size needs to be larger than last level of cache. We don't have a
# way of getting cache sizes, so this number should give us a large enough
# size.
size = 10**8 // (4 * threads * vec_width)
a = nd.empty((threads, size, 4, vec_width), dtype="float32", device=dev)
random_fill(a)
b = nd.empty((threads, 4, vec_width), dtype="float32", device=dev)
random_fill(b)
times = f.time_evaluator(f.entry_name, dev, repeat=10, number=1)(a, b, threads)
return a.numpy().size * 4 / times.min # 4 bytes per float32
@registry.estimate_peak_bandwidth.register("cpu")
def estimate_peak_bandwidth(
func: PrimFunc, # pylint: disable=unused-argument
features: Dict[str, np.ndarray],
target: Target,
dev: Device,
remote: Optional[RPCSession],
vec_width: Optional[int] = None,
) -> Tuple[float, float, str]:
"""Estimate peak memory bandwidth of a target/device combo.
Peak bandwidth is estimated by running a small experiment on the underlying
hardware. The peak bandwidth measurement assumes that vector instructions
are being used to load the data.
Parameters
----------
func : PrimFunc
Function to estimate peak bandwidth for. Used to check if a specific
kind of memory could be used with this function.
features : Dict[str, np.ndarry]
Features extracted from `func`. Used to check if a specific kind of
memory could be used with this function.
target : Target
Target to use for measurement. This target should be as specific to the
underlying hardware as possible.
dev : Device
Device to measure peak bandwidth on.
remote : Optional[RPCSession]
Remote session used to upload artifacts for runtime evaluation. Must be
the same session used to create `dev`.
vec_width : Optional[int]
Vector unit width, determined from target if not supplied.
Returns
-------
loaded_bytes : float
Estimated bytes loaded by `func`.
peak_bandwidth : float
Peak memory bandwidth in bytes/seconds.
name : str
Name of the memory being used.
"""
# Ideally we'd be able to use this code to measure peak bandwidth of the
# different cache levels. If we could just generate load commands, then we
# could use those in a tight loop. Instead we need some code that is
# limited on the cache bandwidth. With the L1 cache we need an operation
# that has a very low arithmetic intensity and we haven't come up with one
# yet.
peak_bandwidth = estimate_peak_bandwidth_dram(target, dev, remote, vec_width)
loaded_bytes = sum(
[np.sum(x) for (k, x) in features.items() if re.match(r"^B[0-9]+\.bytes$", k) is not None]
)
return loaded_bytes, peak_bandwidth, "DRAM"
| https://github.com/zk-ml/tachikoma |
rust/compiler-ext/src/lib.rs | /*
* 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.
*/
use env_logger;
use tvm::export;
fn diagnostics() -> Result<(), tvm::Error> {
tvm::ir::diagnostics::codespan::init()
}
export!(diagnostics);
#[no_mangle]
extern "C" fn compiler_ext_initialize() -> i32 {
let _ = env_logger::try_init();
tvm_export("rust_ext").expect("failed to initialize the Rust compiler extensions.");
log::debug!("Loaded the Rust compiler extension.");
return 0;
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/allocator.rs | /*
* 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.
*/
use std::alloc::{self, Layout, LayoutError};
const DEFAULT_ALIGN_BYTES: usize = 4;
#[derive(PartialEq, Eq)]
pub struct Allocation {
layout: Layout,
ptr: *mut u8,
}
impl Allocation {
/// Allocates a chunk of memory of `size` bytes with optional alignment.
pub fn new(size: usize, align: Option<usize>) -> Result<Self, LayoutError> {
let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES);
let layout = Layout::from_size_align(size, alignment)?;
let ptr = unsafe { alloc::alloc(layout) };
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}
Ok(Self { ptr, layout })
}
pub fn as_mut_ptr(&self) -> *mut u8 {
self.ptr
}
/// Returns the size of the Allocation in bytes.
pub fn size(&self) -> usize {
self.layout.size()
}
/// Returns the byte alignment of the Allocation.
pub fn align(&self) -> usize {
self.layout.align()
}
/// Returns a view of the Allocation.
pub fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.as_mut_ptr(), self.size()) }
}
/// Returns a mutable view of the Allocation.
pub fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.size()) }
}
}
impl Drop for Allocation {
fn drop(&mut self) {
unsafe {
alloc::dealloc(self.ptr, self.layout);
}
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/array.rs | /*
* 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.
*/
use std::{convert::TryFrom, mem, os::raw::c_void, ptr, slice};
use ndarray;
use tvm_sys::{ffi::DLTensor, DataType, Device};
use crate::allocator::Allocation;
use crate::errors::ArrayError;
use std::alloc::LayoutError;
/// A `Storage` is a container which holds `Tensor` data.
#[derive(PartialEq)]
pub enum Storage<'a> {
/// A `Storage` which owns its contained bytes.
Owned(Allocation),
/// A view of an existing `Storage`.
View(&'a mut [u8], usize), // ptr, align
}
impl<'a> Storage<'a> {
pub fn new(size: usize, align: Option<usize>) -> Result<Storage<'static>, LayoutError> {
Ok(Storage::Owned(Allocation::new(size, align)?))
}
pub fn as_mut_ptr(&self) -> *mut u8 {
match self {
Storage::Owned(alloc) => alloc.as_mut_ptr(),
Storage::View(slice, _) => slice.as_ptr() as *mut u8,
}
}
pub fn size(&self) -> usize {
match self {
Storage::Owned(alloc) => alloc.size(),
Storage::View(slice, _) => slice.len(),
}
}
pub fn align(&self) -> usize {
match self {
Storage::Owned(alloc) => alloc.align(),
Storage::View(_, align) => *align,
}
}
pub fn as_ptr(&self) -> *const u8 {
self.as_mut_ptr() as *const _
}
/// Returns a `Storage::View` which points to an owned `Storage::Owned`.
pub fn view(&self) -> Storage<'a> {
match self {
Storage::Owned(alloc) => Storage::View(
unsafe { slice::from_raw_parts_mut(alloc.as_mut_ptr(), self.size()) },
self.align(),
),
Storage::View(slice, _) => Storage::View(
unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), slice.len()) },
self.align(),
),
}
}
pub fn is_owned(&self) -> bool {
match self {
Storage::Owned(_) => true,
_ => false,
}
}
/// Returns an owned version of this storage via cloning.
pub fn to_owned(&self) -> Storage<'static> {
let s = Storage::new(self.size(), Some(self.align())).unwrap();
unsafe {
s.as_mut_ptr()
.copy_from_nonoverlapping(self.as_ptr(), self.size());
}
s
}
/// Returns a view of the stored data.
pub fn as_slice(&self) -> &[u8] {
match self {
Storage::Owned(alloc) => alloc.as_slice(),
Storage::View(slice, _) => &*slice,
}
}
/// Returns a mutable view of the stored data.
pub fn as_mut_slice(&mut self) -> &mut [u8] {
match self {
Storage::Owned(alloc) => alloc.as_mut_slice(),
Storage::View(slice, _) => slice,
}
}
}
impl<'d, 's, T> From<&'d [T]> for Storage<'s> {
fn from(data: &'d [T]) -> Self {
let data = unsafe {
slice::from_raw_parts_mut(
data.as_ptr() as *const u8 as *mut u8,
data.len() * mem::size_of::<T>() as usize,
)
};
Storage::View(data, mem::align_of::<T>())
}
}
/// A n-dimensional array type which can be converted to/from `tvm::DLTensor` and `ndarray::Array`.
/// `Tensor` is primarily a holder of data which can be operated on via TVM (via `DLTensor`) or
/// converted to `ndarray::Array` for non-TVM processing.
///
/// # Examples
///
/// ```
/// extern crate ndarray;
/// use std::convert::TryInto;
/// use tvm_graph_rt::{call_packed, DLTensor, ArgValue, RetValue, Tensor};
///
/// let mut a_nd: ndarray::Array1<f32> = ndarray::Array::from_vec(vec![1f32, 2., 3., 4.]);
/// let mut a: Tensor = a_nd.into();
/// let mut a_dl: DLTensor = (&mut a).into();
///
/// let tvm_fn = |args: &[ArgValue]| -> Result<RetValue, ()> { Ok(RetValue::default()) };
/// call_packed!(tvm_fn, &mut a_dl);
///
/// // Array -> Tensor is mostly useful when post-processing TVM graph outputs.
/// let mut a_nd: ndarray::ArrayD<f32> = a.try_into().unwrap();
/// ```
#[derive(PartialEq)]
pub struct Tensor<'a> {
/// The bytes which contain the data this `Tensor` represents.
pub(crate) data: Storage<'a>,
pub(crate) device: Device,
pub(crate) dtype: DataType,
pub(crate) shape: Vec<i64>,
// ^ not usize because `typedef int64_t tvm_index_t` in c_runtime_api.h
/// The `Tensor` strides. Can be `None` if the `Tensor` is contiguous.
pub(crate) strides: Option<Vec<usize>>,
pub(crate) byte_offset: isize,
/// The number of elements in the `Tensor`.
pub(crate) size: usize,
}
unsafe impl<'a> Send for Tensor<'a> {}
impl<'a> Tensor<'a> {
pub fn shape(&self) -> Vec<i64> {
self.shape.clone()
}
pub fn data(&self) -> &Storage {
&self.data
}
pub fn data_mut(&mut self) -> &'a mut Storage {
&mut self.data
}
/// Returns the data of this `Tensor` as a `Vec`.
///
/// # Panics
///
/// Panics if the `Tensor` is not contiguous or does not contain elements of type `T`.
pub fn to_vec<T: 'static + std::fmt::Debug + Clone>(&self) -> Vec<T> {
assert!(self.is_contiguous());
assert!(self.dtype.is_type::<T>());
unsafe { slice::from_raw_parts(self.data.as_ptr() as *const T, self.size).to_vec() }
}
/// Returns `true` iff this `Tensor` is represented by a contiguous region of memory.
pub fn is_contiguous(&self) -> bool {
match self.strides {
None => true,
Some(ref strides) => {
// check that stride for each dimension is the
// product of all trailing dimensons' shapes
self.shape
.iter()
.zip(strides)
.rfold(
(true, 1),
|(is_contig, expected_stride), (shape, stride)| {
(
is_contig && *stride == expected_stride,
expected_stride * (*shape as usize),
)
},
)
.0
}
}
}
/// Returns a clone of this `Tensor`.
///
/// # Panics
///
/// Panics if the `Tensor` is not contiguous or does not contain elements of type `T`.
pub fn copy(&mut self, other: &Tensor) {
assert!(
self.dtype == other.dtype && self.size == other.size,
"Tensor shape/dtype mismatch."
);
assert!(
self.is_contiguous() && other.is_contiguous(),
"copy currently requires contiguous tensors\n`self.strides = {:?}` `other.strides = {:?}`",
self.strides,
other.strides
);
unsafe {
self.data
.as_mut_ptr()
.offset(self.byte_offset as isize)
.copy_from_nonoverlapping(
other.data.as_mut_ptr().offset(other.byte_offset),
other.size * other.dtype.itemsize(),
);
}
}
/// Returns an owned version of this `Tensor` via cloning.
pub fn to_owned(&self) -> Tensor<'static> {
let t = Tensor {
data: self.data.to_owned(),
device: self.device,
dtype: self.dtype,
size: self.size,
shape: self.shape.clone(),
strides: None,
byte_offset: 0,
};
unsafe { mem::transmute::<Tensor<'a>, Tensor<'static>>(t) }
}
fn from_array_storage<'s, T, D: ndarray::Dimension>(
arr: &ndarray::Array<T, D>,
storage: Storage<'s>,
dtype_fn: fn(u8, u16) -> DataType,
) -> Tensor<'s> {
let type_width = mem::size_of::<T>() as u8;
Tensor {
data: storage,
device: Device::default(),
dtype: dtype_fn(8 * type_width, 1),
size: arr.len(),
shape: arr.shape().iter().map(|&v| v as i64).collect(),
strides: Some(arr.strides().iter().map(|&v| v as usize).collect()),
byte_offset: 0,
}
}
pub fn as_dltensor(&self, flatten: bool) -> DLTensor {
assert!(!flatten || self.is_contiguous());
DLTensor {
data: unsafe { self.data.as_mut_ptr().offset(self.byte_offset) } as *mut c_void,
device: self.device.into(),
ndim: if flatten { 1 } else { self.shape.len() } as i32,
dtype: self.dtype.into(),
shape: if flatten {
&self.size as *const _ as *mut i64
} else {
self.shape.as_ptr()
} as *mut i64,
strides: if flatten || self.is_contiguous() {
ptr::null_mut()
} else {
self.strides.as_ref().unwrap().as_ptr()
} as *mut i64,
byte_offset: 0,
..Default::default()
}
}
}
/// Conversions to `ndarray::Array` from `Tensor`, if the types match.
macro_rules! impl_ndarray_try_from_tensor {
($type:ty, $dtype:expr) => {
impl<'t> TryFrom<Tensor<'t>> for ndarray::ArrayD<$type> {
type Error = ArrayError;
fn try_from(tensor: Tensor) -> Result<ndarray::ArrayD<$type>, Self::Error> {
if tensor.dtype != $dtype {
return Err(ArrayError::IncompatibleDataType(tensor.dtype));
}
Ok(ndarray::Array::from_shape_vec(
tensor
.shape
.iter()
.map(|s| *s as usize)
.collect::<Vec<usize>>(),
tensor.to_vec::<$type>(),
)
.map_err(|_| ArrayError::ShapeError(tensor.shape.clone()))?)
}
}
};
}
macro_rules! make_dtype_const {
($name: ident, $cnst:expr) => {
pub const $name: DataType = $cnst;
};
}
make_dtype_const!(DTYPE_INT32, DataType::int(32, 1));
make_dtype_const!(DTYPE_UINT32, DataType::uint(32, 1));
make_dtype_const!(DTYPE_FLOAT32, DataType::float(32, 1));
make_dtype_const!(DTYPE_FLOAT64, DataType::float(64, 1));
impl_ndarray_try_from_tensor!(i32, DTYPE_INT32);
impl_ndarray_try_from_tensor!(u32, DTYPE_UINT32);
impl_ndarray_try_from_tensor!(f32, DTYPE_FLOAT32);
impl_ndarray_try_from_tensor!(f64, DTYPE_FLOAT64);
impl<'a, 't> From<&'a Tensor<'t>> for DLTensor {
fn from(tensor: &'a Tensor<'t>) -> Self {
Tensor::as_dltensor(tensor, false /* flatten */)
}
}
impl<'a, 't> From<&'a mut Tensor<'t>> for DLTensor {
fn from(tensor: &'a mut Tensor<'t>) -> Self {
Tensor::as_dltensor(tensor, false /* flatten */)
}
}
impl<'a> From<DLTensor> for Tensor<'a> {
fn from(dlt: DLTensor) -> Self {
unsafe {
let dtype = DataType::from(dlt.dtype);
let shape = slice::from_raw_parts(dlt.shape, dlt.ndim as usize).to_vec();
let size = shape.iter().map(|v| *v as usize).product::<usize>() as usize;
let storage = Storage::from(slice::from_raw_parts(
dlt.data as *const u8,
dtype.itemsize() * size,
));
Self {
data: storage,
device: Device::default(),
dtype,
size,
shape,
strides: if dlt.strides.is_null() {
None
} else {
Some(slice::from_raw_parts_mut(dlt.strides as *mut usize, size).to_vec())
},
byte_offset: dlt.byte_offset as isize,
}
}
}
}
/// `From` conversions to `Tensor` for owned or borrowed `ndarray::Array`.
///
/// # Panics
///
/// Panics if the ndarray is not contiguous.
macro_rules! impl_tensor_from_ndarray {
($type:ty, $dtype_fn:expr) => {
impl<D: ndarray::Dimension> From<ndarray::Array<$type, D>> for Tensor<'static> {
fn from(arr: ndarray::Array<$type, D>) -> Self {
let storage = Storage::from(arr.as_slice().expect("NDArray must be contiguous"));
Tensor::from_array_storage(&arr, storage.to_owned(), $dtype_fn)
}
}
impl<'a, D: ndarray::Dimension> From<&'a ndarray::Array<$type, D>> for Tensor<'a> {
fn from(arr: &'a ndarray::Array<$type, D>) -> Self {
let storage = Storage::from(arr.as_slice().expect("NDArray must be contiguous"));
Tensor::from_array_storage(arr, storage, $dtype_fn)
}
}
};
}
impl_tensor_from_ndarray!(f32, DataType::float);
impl_tensor_from_ndarray!(f64, DataType::float);
impl_tensor_from_ndarray!(i32, DataType::int);
impl_tensor_from_ndarray!(i64, DataType::int);
impl_tensor_from_ndarray!(u32, DataType::uint);
impl_tensor_from_ndarray!(u64, DataType::uint);
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/errors.rs | /*
* 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.
*/
use thiserror::Error;
use tvm_sys::DataType;
#[derive(Debug, Error)]
pub enum GraphFormatError {
#[error("Failed to parse graph with error: {0}")]
Parse(#[source] serde_json::Error),
#[error("Failed to parse graph parameters with error: {0:?}")]
Params(#[source] Option<nom::Err<(Vec<u8>, nom::error::ErrorKind)>>),
#[error("{0} is missing attribute: {1}")]
MissingAttr(String, String),
#[error("Failed to parse graph attribute '{0}' with error: {1}")]
InvalidAttr(String, #[source] std::num::ParseIntError),
#[error("Missing field: {0}")]
MissingField(&'static str),
#[error("Invalid DLType: {0}")]
InvalidDLType(String),
#[error("Unsupported Op: {0}")]
UnsupportedOp(String),
}
#[derive(Debug, Error)]
#[error("Function {0} not found")]
pub struct FunctionNotFound(pub String);
#[derive(Debug, Error)]
#[error("Pointer {0:?} invalid when freeing")]
pub struct InvalidPointer(pub *mut u8);
#[derive(Debug, Error)]
pub enum ArrayError {
#[error("Cannot convert Tensor with dtype {0} to ndarray")]
IncompatibleDataType(DataType),
#[error("Shape error when casting ndarray to TVM Array with shape {0:?}")]
ShapeError(Vec<i64>),
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/graph.rs | /*
* 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.
*/
use std::{
cmp, collections::HashMap, convert::TryFrom, error::Error, iter::FromIterator, mem, str,
};
use itertools::izip;
use nom::{
character::complete::{alpha1, digit1},
complete, count, do_parse, length_count, map, named,
number::complete::{le_i32, le_i64, le_u16, le_u32, le_u64, le_u8},
opt, tag, take, tuple, Err as NomErr,
};
use serde::{Deserialize, Serialize};
use serde_json;
use tvm_sys::ffi::{DLDataTypeCode_kDLFloat, DLDataTypeCode_kDLInt, DLDataTypeCode_kDLUInt};
use tvm_sys::{ffi::DLTensor, ArgValue, DataType, Device, DeviceType};
use crate::{errors::*, Module, Storage, Tensor};
// @see `kTVMNDArrayMagic` in `ndarray.h`
const _NDARRAY_MAGIC: u64 = 0xDD5E_40F0_96B4_A13F;
// @see `kTVMNDArrayListMagic` in `graph_executor.h`
const _NDARRAY_LIST_MAGIC: u64 = 0xF7E5_8D4F_0504_9CB7;
/// A TVM computation graph.
///
/// # Examples
///
/// ```no_run
/// use tvm_graph_rt::Graph;
/// use std::convert::TryFrom;
/// let graph_json = std::fs::read_to_string("graph.json").unwrap();
/// let graph = Graph::try_from(&graph_json).unwrap();
/// ```
#[derive(Serialize, Deserialize, Debug)]
pub struct Graph {
pub nodes: Vec<Node>,
pub arg_nodes: Vec<usize>,
pub heads: Vec<Entry>,
pub node_row_ptr: Option<Vec<usize>>,
pub attrs: Option<HashMap<String, serde_json::Value>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Entry {
pub id: usize,
pub index: usize,
pub version: usize,
}
impl Graph {
fn entry_index(&self, entry: &Entry) -> Result<usize, GraphFormatError> {
self.node_row_ptr
.as_ref()
.map(|nrp| nrp[entry.id] + entry.index)
.ok_or_else(|| GraphFormatError::MissingField("node_row_ptr"))
}
/// Attempt to deserialize a JSON attribute to a type `T`.
fn get_attr<T: serde::de::DeserializeOwned>(&self, attr: &str) -> Result<T, GraphFormatError> {
Ok(serde_json::from_value::<T>(
self.attrs
.as_ref()
.ok_or(GraphFormatError::MissingField("attrs"))?
.get(attr)
.ok_or_else(|| {
GraphFormatError::MissingAttr("graph".to_string(), attr.to_string())
})?
.to_owned(),
)
.map_err(|err| GraphFormatError::Parse(err.into()))?)
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Node {
pub op: String,
pub name: String,
pub inputs: Vec<Entry>,
pub attrs: Option<HashMap<String, String>>,
pub control_deps: Option<Vec<Entry>>,
}
struct NodeAttrs {
func_name: String,
num_outputs: usize,
flatten_data: bool,
}
macro_rules! get_node_attr {
($node:expr, $attrs:ident, $attr:literal) => {
$attrs
.get($attr)
.ok_or_else(|| GraphFormatError::MissingAttr($node.to_owned(), $attr.to_owned()))
};
}
impl Node {
fn parse_attrs(&self) -> Result<NodeAttrs, GraphFormatError> {
let attrs = self
.attrs
.as_ref()
.ok_or_else(|| GraphFormatError::MissingAttr(self.name.clone(), "attrs".to_owned()))?;
let func_name = get_node_attr!(self.name, attrs, "func_name")?.to_owned();
let num_outputs = get_node_attr!(self.name, attrs, "num_outputs")?
.parse::<usize>()
.map_err(|error| GraphFormatError::InvalidAttr("num_outputs".to_string(), error))?;
let flatten_data = get_node_attr!(self.name, attrs, "flatten_data")?
.parse::<u8>()
.map(|val| val == 1)
.map_err(|error| GraphFormatError::InvalidAttr("flatten_data".to_string(), error))?;
Ok(NodeAttrs {
func_name,
num_outputs,
flatten_data,
})
}
}
impl<'a> TryFrom<&'a String> for Graph {
type Error = GraphFormatError;
fn try_from(graph_json: &String) -> Result<Self, GraphFormatError> {
serde_json::from_str(graph_json).map_err(|error| GraphFormatError::Parse(error))
}
}
impl<'a> TryFrom<&'a str> for Graph {
type Error = GraphFormatError;
fn try_from(graph_json: &'a str) -> Result<Self, Self::Error> {
serde_json::from_str(graph_json).map_err(|error| GraphFormatError::Parse(error))
}
}
/// A executor for a TVM computation graph.
///
/// # Examples
///
/// ```no_compile
/// use ndarray::Array;
///
/// let syslib = SystemLibModule::default(); // a provider of TVM functions
///
/// let mut params_bytes = Vec::new();
/// fs::File::open("graph.params").unwrap().read_to_end(&mut params_bytes).unwrap();
/// let params = tvm::runtime::load_param_dict(¶ms_bytes).unwrap();
///
/// let graph = Graph::try_from(&fs::read_to_string("graph.json").unwrap()).unwrap();
///
/// let mut exec = GraphExecutor::new(graph, &syslib).unwrap();
/// exec.load_params(params);
///
/// let x = Array::from_vec(vec![1f32, 2., 3., 4.]);
/// exec.set_input("data", x.into());
/// exec.run();
/// let output = exec.get_output(0).unwrap();
///
/// println!("{:#?}", Array::try_from(output).unwrap());
/// ```
pub struct GraphExecutor<'m, 't> {
graph: Graph,
op_execs: Vec<Box<dyn Fn() + 'm>>,
tensors: Vec<Tensor<'t>>,
}
unsafe impl<'m, 't> Send for GraphExecutor<'m, 't> {}
impl<'m, 't> GraphExecutor<'m, 't> {
pub fn new<M: 'm + Module>(graph: Graph, lib: &'m M) -> Result<Self, Box<dyn Error>> {
let tensors = Self::setup_storages(&graph)?;
Ok(GraphExecutor {
op_execs: Self::setup_op_execs(&graph, lib, &tensors)?,
tensors,
graph,
})
}
/// Runs the computation graph.
pub fn run(&mut self) {
self.op_execs.iter().for_each(|op_exec| {
op_exec();
});
}
/// Allocates `Storages` for each `storage_id` and returns `Tensor`s to hold each output.
fn setup_storages<'a>(graph: &'a Graph) -> Result<Vec<Tensor<'t>>, Box<dyn Error>> {
let storage_ids = graph.get_attr::<(String, Vec<usize>)>("storage_id")?.1;
let shapes = graph.get_attr::<(String, Vec<Vec<i64>>)>("shape")?.1;
let dtypes = graph
.get_attr::<(String, Vec<String>)>("dltype")?
.1
.iter()
.map(|dltype| {
if let Ok((_, dtype)) = tvm_str_to_type(dltype) {
Ok(dtype)
} else {
Err(GraphFormatError::InvalidDLType(dltype.to_string()))
}
})
.collect::<Result<Vec<DataType>, GraphFormatError>>()?;
let align = dtypes.iter().map(|dtype| dtype.bits() as usize).max();
let mut storage_num_bytes = vec![0usize; *storage_ids.iter().max().unwrap_or(&1) + 1];
for (i, &storage_id) in storage_ids.iter().enumerate() {
let dtype_size = (dtypes[i].bits() * dtypes[i].lanes()) >> 3;
let nbytes = dtype_size * shapes[i].iter().product::<i64>() as usize;
storage_num_bytes[storage_id] = cmp::max(nbytes, storage_num_bytes[storage_id]);
}
let mut storages: Vec<Storage> = storage_num_bytes
.into_iter()
.map(|nbytes| Storage::new(nbytes, align))
.collect::<Result<Vec<Storage>, std::alloc::LayoutError>>()?;
let tensors = izip!(storage_ids, shapes, dtypes)
.map(|(storage_id, shape, dtype)| {
let storage = storages[storage_id].view();
Tensor {
data: mem::replace(&mut storages[storage_id], storage),
device: Device::default(),
dtype,
size: shape.iter().product::<i64>() as usize,
shape,
strides: None,
byte_offset: 0,
}
})
.collect();
Ok(tensors)
}
/// Creates closures which represent the computation performed by this graph.
fn setup_op_execs<M: 'm + Module>(
graph: &Graph,
lib: &'m M,
tensors: &[Tensor<'t>],
) -> Result<Vec<Box<dyn Fn() + 'm>>, Box<dyn Error + 'static>> {
if !graph.node_row_ptr.is_some() {
return Err(GraphFormatError::MissingField("node_row_ptr").into());
}
let node_row_ptr = graph.node_row_ptr.as_ref().unwrap();
let mut op_execs = Vec::new();
for (i, node) in graph.nodes.iter().enumerate() {
if node.op == "null" {
continue;
}
if node.op != "tvm_op" {
return Err(GraphFormatError::UnsupportedOp(node.op.to_owned()).into());
}
if !node.attrs.is_some() {
return Err(GraphFormatError::MissingAttr(node.op.clone(), "".to_string()).into());
}
let attrs: NodeAttrs = node.parse_attrs()?.into();
if attrs.func_name == "__nop" {
continue;
}
let func = lib
.get_function(&attrs.func_name)
.ok_or_else(|| FunctionNotFound(attrs.func_name.clone()))?;
let arg_indices = node
.inputs
.iter()
.map(|entry| graph.entry_index(entry))
.chain((0..attrs.num_outputs).map(|oi| Ok(node_row_ptr[i] + oi)));
let dl_tensors: Vec<DLTensor> = arg_indices
.map(|idx| {
let tensor = &tensors[idx?];
Ok(if attrs.flatten_data {
Tensor::as_dltensor(tensor, true /* flatten */)
} else {
DLTensor::from(tensor)
})
})
.collect::<Result<Vec<DLTensor>, GraphFormatError>>()?
.into();
let op: Box<dyn Fn()> = Box::new(move || {
let args: Vec<ArgValue> = dl_tensors
.iter()
.map(|t| t.into())
.collect::<Vec<ArgValue>>();
let err_str = format!("Function {} failed to execute", attrs.func_name);
func(&args).expect(&err_str);
});
op_execs.push(op);
}
Ok(op_execs)
}
pub fn load_params(&mut self, params: HashMap<String, Tensor>) {
params.into_iter().for_each(|(name, param)| {
self.set_input(name, param);
})
}
#[allow(clippy::if_same_then_else)]
pub fn set_input<S: AsRef<str>>(&mut self, name: S, value: Tensor) {
if let Some(idx) = self.get_input_index(name.as_ref()) {
// TODO: consider `new_with_params` to avoid ever allocating
let ptr = self.tensors[idx].data.as_ptr();
let mut to_replace = self.tensors.iter_mut().filter(|t| t.data.as_ptr() == ptr);
let owner = to_replace.nth(0).unwrap();
if value.data.is_owned() {
// FIXME: for no-copy, need setup_op_execs to not capture tensor ptr
// mem::replace(&mut (*owner), value);
// to_replace.for_each(|t| {
// panic!("replacing");
// t.data = owner.data.view();
// });
owner.copy(&value);
} else {
owner.copy(&value);
}
} else {
println!("Unexpected input `{}`", name.as_ref());
}
}
/// Returns the graph input with name `name`, if it exists.
pub fn get_input<S: AsRef<str>>(&mut self, name: S) -> Option<&Tensor> {
self.get_input_index(name.as_ref())
.map(move |idx| &self.tensors[idx])
}
/// Returns the graph output with index `index`, if it exists.
pub fn get_output(&self, idx: usize) -> Option<&Tensor> {
let graph = &self.graph;
graph.heads.get(idx).and_then(|entry| {
graph
.entry_index(entry)
.map(|idx| self.tensors.get(idx))
.unwrap_or(None)
})
}
/// Returns the index for graph input with name `name`, if it exists.
pub fn get_input_index<S: AsRef<str>>(&self, name: S) -> Option<usize> {
let graph = &self.graph;
(0..graph.nodes.len())
.skip_while(|&i| graph.nodes[i].name != name.as_ref())
.nth(0)
.and_then(|i| {
if graph.arg_nodes.iter().any(|&id| id == i) {
graph.node_row_ptr.as_ref().map(|nrp| nrp[i])
} else {
None
}
})
}
}
// Converts a string to TVM DLDataTypeCode. @see `String2DLDataType` in packed_func.h
named! {
tvm_str_to_type<&str, DataType>,
do_parse!(
type_name: alpha1 >>
bits: digit1 >>
lanes: opt!(complete!(tuple!(tag!("x"), digit1))) >>
(
DataType::new(
match type_name {
"int" => DLDataTypeCode_kDLInt,
"uint" => DLDataTypeCode_kDLUInt,
"float" => DLDataTypeCode_kDLFloat,
_ => DLDataTypeCode_kDLFloat,
} as u8,
bits.parse::<u8>().unwrap() as u8,
lanes
.map(|(_, lanes)| lanes.parse::<u16>().unwrap() as u16)
.unwrap_or(1),
)
)
)
}
// Converts a bytes to String.
named! {
name<String>,
do_parse!(
len_l: le_u32 >>
len_h: le_u32 >>
data: take!(len_l) >>
(
if len_h == 0 {
String::from_utf8(data.to_vec()).unwrap()
} else {
panic!("Too long string")
}
)
)
}
// Parses a Device
named! {
tvm_device<&[u8], Device>,
do_parse!(
device_type: le_u32 >>
device_id: le_i32 >>
(
Device {
device_type: DeviceType::from(device_type),
device_id: device_id as usize,
}
)
)
}
// Parses a DataType
named! {
data_type<&[u8], DataType>,
do_parse!(
code: le_u8 >>
bits: le_u8 >>
lanes: le_u16 >>
(DataType::new(code, bits, lanes)))
}
// Parses a Tensor from a TVM array file.
named! {
tensor<Tensor>,
do_parse!(
take!(8) >>
le_u64 >>
device: tvm_device >>
ndim: le_u32 >>
dtype: data_type >>
shape: count!(map!(le_i64, |sz| sz as i64), ndim as usize) >>
length: le_i64 >>
data: take!(length) >>
(
Tensor {
data: Storage::from(data),
device: device,
dtype: dtype,
size: shape.iter().product::<i64>() as usize,
shape: shape,
strides: None,
byte_offset: 0,
}
)
)
}
// Parses a graph params dict from a params binary file.
named! {
parse_param_dict<HashMap<String, Tensor>>,
do_parse!(
take!(8) >>
le_u64 >>
names: length_count!(le_u64, name) >>
tensors: length_count!(le_u64, tensor) >>
(
HashMap::from_iter(names.into_iter().zip(tensors.into_iter()))
)
)
}
/// Loads a param dict saved using `runtime.save_param_dict`.
pub fn load_param_dict(bytes: &[u8]) -> Result<HashMap<String, Tensor>, GraphFormatError> {
match parse_param_dict(bytes) {
Ok((remaining_bytes, param_dict)) => {
if remaining_bytes.is_empty() {
Ok(param_dict)
} else {
Err(GraphFormatError::Params(None))
}
}
Err(error) => Err(match error {
NomErr::Incomplete(error) => GraphFormatError::Params(Some(NomErr::Incomplete(error))),
NomErr::Error((remainder, error_kind)) => {
GraphFormatError::Params(Some(NomErr::Error((remainder.into(), error_kind))))
}
NomErr::Failure((remainder, error_kind)) => {
GraphFormatError::Params(Some(NomErr::Failure((remainder.into(), error_kind))))
}
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_str_to_type() {
assert_eq!(
tvm_str_to_type("float24").unwrap().1,
DataType::float(24, 1)
);
assert_eq!(
tvm_str_to_type("uint111x44").unwrap().1,
DataType::uint(111, 44)
);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/lib.rs | /*
* 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.
*/
//! This crate is an implementation of the TVM runtime for modules compiled with `--system-lib`.
//! It's mainly useful for compiling to WebAssembly and SGX,
//! but also native if you prefer Rust to C++.
//!
//! For TVM graphs, the entrypoint to this crate is `runtime::GraphExecutor`.
//! Single-function modules are used via the `packed_func!` macro after obtaining
//! the function from `runtime::SystemLibModule`
//!
//! The main entrypoints to this crate are `GraphExecutor`
//! For examples of use, please refer to the multi-file tests in the `tests` directory.
extern crate tvm_macros;
extern crate tvm_sys;
// Re-export the import_module macro.
pub use tvm_macros::import_module;
// Re-export the called pack macro, eventually remove as its not a very good
// abstraction.
pub use tvm_sys::call_packed;
use lazy_static::lazy_static;
mod allocator;
mod array;
pub mod errors;
mod graph;
mod module;
mod threading;
mod workspace;
pub use tvm_sys::{
errors::*,
ffi::{self, DLTensor},
packed_func::{self, *},
ArgValue, RetValue,
};
pub use self::{array::*, errors::*, graph::*, module::*, threading::*, workspace::*};
lazy_static! {
static ref LAST_ERROR: std::sync::RwLock<Option<&'static std::ffi::CStr>> =
std::sync::RwLock::new(None);
}
#[no_mangle]
pub unsafe extern "C" fn TVMAPISetLastError(cmsg: *const i8) {
*LAST_ERROR.write().unwrap() = Some(std::ffi::CStr::from_ptr(cmsg));
}
#[no_mangle]
pub extern "C" fn TVMGetLastError() -> *const std::os::raw::c_char {
match *LAST_ERROR.read().unwrap() {
Some(err) => err.as_ptr(),
None => std::ptr::null(),
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/module/dso.rs | /*
* 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.
*/
use std::{
cell::RefCell,
collections::HashMap,
ffi::CStr,
os::raw::{c_char, c_int, c_void},
pin::Pin,
};
use tvm_sys::{ffi::BackendPackedCFunc, packed_func::PackedFunc};
use crate::{
threading::{TVMBackendParallelBarrier, TVMBackendParallelLaunch},
workspace::{TVMBackendAllocWorkspace, TVMBackendFreeWorkspace},
TVMAPISetLastError,
};
use super::Module;
const TVM_MAIN: &[u8] = b"__tvm_main__";
const TVM_MODULE_CTX: &[u8] = b"__tvm_module_ctx";
/// A module backed by a Dynamic Shared Object (dylib).
pub struct DsoModule<'a> {
lib: libloading::Library,
packed_funcs: RefCell<HashMap<String, &'a (dyn PackedFunc)>>,
_pin: std::marker::PhantomPinned,
}
macro_rules! init_context_func {
($lib:ident, $( ($fn:ident, $sig:ty) ),+ $(,)?) => {
unsafe {
$(
let fn_ptr = $lib.get::<*mut $sig>(concat!("__", stringify!($fn)).as_bytes());
if let Ok(fn_ptr) = fn_ptr {
**fn_ptr = $fn;
}
)+
}
};
}
impl<'a> DsoModule<'a> {
pub fn new<P: AsRef<std::ffi::OsStr>>(filename: P) -> Result<Pin<Box<Self>>, std::io::Error> {
let lib = libloading::Library::new(filename)?;
init_context_func!(
lib,
(TVMAPISetLastError, unsafe extern "C" fn(*const i8)),
(
TVMBackendAllocWorkspace,
unsafe extern "C" fn(c_int, c_int, u64, c_int, c_int) -> *mut c_void
),
(
TVMBackendFreeWorkspace,
unsafe extern "C" fn(c_int, c_int, *mut c_void) -> c_int
),
(
TVMBackendParallelLaunch,
unsafe extern "C" fn(
crate::threading::FTVMParallelLambda,
*const c_void,
usize,
) -> c_int
),
(
TVMBackendParallelBarrier,
unsafe extern "C" fn(usize, *const tvm_sys::ffi::TVMParallelGroupEnv)
),
);
// Pin the module in memory so that `ctx` pointer (below) is stable.
let dso_mod = Box::pin(Self {
lib,
packed_funcs: RefCell::new(HashMap::new()),
_pin: std::marker::PhantomPinned,
});
unsafe {
if let Ok(ctx) = dso_mod.lib.get::<*mut *const c_void>(TVM_MODULE_CTX) {
**ctx = &dso_mod as *const _ as *const c_void;
}
}
Ok(dso_mod)
}
}
impl<'a> Module for DsoModule<'a> {
fn get_function<S: AsRef<str>>(&self, name: S) -> Option<&(dyn PackedFunc)> {
let name = name.as_ref();
let func = match unsafe {
self.lib
.get::<BackendPackedCFunc>(if name.as_bytes() == TVM_MAIN {
// If __tvm_main__ is present, it contains the name of the
// actual main function.
match self
.lib
.get::<*const c_char>(TVM_MAIN)
.map(|p| CStr::from_ptr(*p))
{
Ok(m) => m.to_bytes(),
_ => return None,
}
} else {
name.as_bytes()
})
} {
Ok(func) => unsafe { func.into_raw() },
Err(_) => return None,
};
self.packed_funcs.borrow_mut().insert(
name.to_string(),
&*Box::leak(super::wrap_backend_packed_func(name.to_string(), *func)),
);
self.packed_funcs.borrow().get(name).copied()
}
}
impl<'a> Drop for DsoModule<'a> {
fn drop(&mut self) {
self.packed_funcs
.replace(HashMap::new())
.into_iter()
.map(|(_name, f)| unsafe { Box::from_raw(f as *const _ as *mut (dyn PackedFunc)) })
.for_each(std::mem::drop);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/module/mod.rs | /*
* 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.
*/
#[cfg(not(any(target_arch = "wasm32", target_env = "sgx")))]
mod dso;
mod syslib;
use tvm_sys::{
ffi::BackendPackedCFunc,
packed_func::{ArgValue, PackedFunc, RetValue, TVMValue},
};
#[cfg(not(any(target_arch = "wasm32", target_env = "sgx")))]
pub use dso::DsoModule;
pub use syslib::SystemLibModule;
pub trait Module {
fn get_function<S: AsRef<str>>(&self, name: S) -> Option<&(dyn PackedFunc)>;
}
// @see `WrapPackedFunc` in `llvm_module.cc`.
fn wrap_backend_packed_func(func_name: String, func: BackendPackedCFunc) -> Box<dyn PackedFunc> {
Box::new(move |args: &[ArgValue]| {
let (values, type_codes): (Vec<TVMValue>, Vec<i32>) = args
.iter()
.map(|arg| {
let (val, code) = arg.to_tvm_value();
(val, code as i32)
})
.unzip();
let ret: RetValue = RetValue::default();
let (mut ret_val, mut ret_type_code) = ret.to_tvm_value();
let exit_code = func(
values.as_ptr(),
type_codes.as_ptr(),
values.len() as i32,
&mut ret_val,
&mut ret_type_code,
std::ptr::null_mut(),
);
if exit_code == 0 {
Ok(RetValue::from_tvm_value(ret_val, ret_type_code))
} else {
Err(tvm_sys::errors::FuncCallError::get_with_context(
func_name.clone(),
))
}
})
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/module/syslib.rs | /*
* 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.
*/
use std::{
collections::HashMap, convert::AsRef, ffi::CStr, os::raw::c_char, string::String, sync::RwLock,
};
use lazy_static::lazy_static;
use tvm_sys::{ffi::BackendPackedCFunc, packed_func::PackedFunc};
use super::Module;
pub struct SystemLibModule;
#[cfg(target_env = "sgx")]
extern "C" {
fn __tvm_module_startup();
}
lazy_static! {
static ref SYSTEM_LIB_FUNCTIONS: RwLock<HashMap<String, &'static (dyn PackedFunc)>> =
RwLock::new(HashMap::new());
}
impl Module for SystemLibModule {
fn get_function<S: AsRef<str>>(&self, name: S) -> Option<&(dyn PackedFunc)> {
SYSTEM_LIB_FUNCTIONS
.read()
.unwrap()
.get(name.as_ref())
.copied()
}
}
impl Default for SystemLibModule {
fn default() -> Self {
#[cfg(target_env = "sgx")]
unsafe {
__tvm_module_startup();
}
SystemLibModule {}
}
}
#[no_mangle]
pub extern "C" fn TVMBackendRegisterSystemLibSymbol(
cname: *const c_char,
func: BackendPackedCFunc,
) -> i32 {
let name = unsafe { CStr::from_ptr(cname).to_str().unwrap() };
SYSTEM_LIB_FUNCTIONS.write().unwrap().insert(
name.to_string(),
&*Box::leak(super::wrap_backend_packed_func(name.to_string(), func)),
);
0
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/threading.rs | /*
* 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.
*/
use std::{
os::raw::{c_int, c_void},
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Barrier,
},
thread::{self, JoinHandle},
};
#[cfg(not(target_arch = "wasm32"))]
use std::env;
use crossbeam_channel::{bounded, Receiver, Sender};
use tvm_sys::ffi::TVMParallelGroupEnv;
pub(crate) type FTVMParallelLambda =
extern "C" fn(task_id: usize, penv: *const TVMParallelGroupEnv, cdata: *const c_void) -> i32;
/// Holds a parallel job request made by a TVM library function.
struct Job {
cb: FTVMParallelLambda,
cdata: *const c_void,
req_num_tasks: usize,
pending: Arc<AtomicUsize>,
}
impl Job {
/// Splits this job into a number of `Task`s which can be scheduled.
fn tasks(&self, num_workers: usize) -> Vec<Task> {
let num_tasks = if self.req_num_tasks == 0 {
num_workers
} else {
self.req_num_tasks.min(num_workers)
};
self.pending.store(num_tasks, Ordering::SeqCst);
let barrier = Arc::new(Barrier::new(num_tasks));
(0..num_tasks)
.map(move |i| Task {
id: i,
flambda: self.cb,
penv: TVMParallelGroupEnv {
sync_handle: &Arc::clone(&barrier) as *const _ as *mut c_void,
num_task: num_tasks as i32,
},
cdata: self.cdata,
pending: Arc::clone(&self.pending),
})
.collect()
}
/// Waits for all tasks in this `Job` to be completed.
fn wait(&self) {
while self.pending.load(Ordering::Acquire) > 0 {
thread::yield_now();
}
}
}
/// A chunk of work requested by a TVM function.
struct Task {
id: usize,
flambda: FTVMParallelLambda,
penv: TVMParallelGroupEnv,
cdata: *const c_void,
pending: Arc<AtomicUsize>,
}
unsafe impl Send for Task {}
unsafe impl Sync for Task {}
impl Task {
fn run(self) -> i32 {
let status = (self.flambda)(self.id, &self.penv as *const _, self.cdata);
self.pending.fetch_sub(1, Ordering::AcqRel);
status
}
}
#[derive(Default)]
struct Threads {
#[allow(unused)]
handles: Vec<JoinHandle<()>>,
queues: Vec<Sender<Task>>,
}
impl<'a> Threads {
fn launch<F: Sync + Send + FnOnce(Receiver<Task>) + 'static + Copy>(
num_threads: usize,
cb: F,
) -> Self {
let (handles, queues) = (0..num_threads)
.map(|_| {
let (p, c) = bounded(2);
let handle = thread::spawn(move || cb(c.into()));
(handle, p)
})
.unzip();
Threads { handles, queues }
}
}
struct ThreadPool {
num_workers: usize,
#[allow(unused)]
threads: Threads,
}
thread_local!(static THREAD_POOL: ThreadPool = ThreadPool::new());
impl ThreadPool {
fn new() -> Self {
let num_workers = max_concurrency();
ThreadPool {
num_workers,
threads: Threads::launch(num_workers, ThreadPool::run_worker),
}
}
fn launch(&self, job: Job) {
let mut tasks = job.tasks(self.num_workers + 1);
for (i, task) in tasks.split_off(1).into_iter().enumerate() {
self.threads.queues[i].send(task).expect("should send");
}
tasks.pop().unwrap().run();
job.wait();
}
fn run_worker(queue: Receiver<Task>) {
loop {
let task = match queue.recv() {
Ok(v) => v,
Err(_) => break,
};
let result = task.run();
if result == <i32>::min_value() {
break;
} else if result != 0 {
panic!("Error running task.");
}
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn max_concurrency() -> usize {
if let Ok(threads_str) = env::var("TVM_NUM_THREADS").or_else(|_| env::var("OMP_NUM_THREADS")) {
if let Ok(threads) = usize::from_str_radix(&threads_str, 10) {
return threads;
}
}
num_cpus::get()
}
#[cfg(target_arch = "wasm32")]
fn max_concurrency() -> usize {
0 // wasm doesn't support threads yet
}
#[no_mangle]
pub extern "C" fn TVMBackendParallelLaunch(
cb: FTVMParallelLambda,
cdata: *const c_void,
num_task: usize,
) -> c_int {
if max_concurrency() < 2 {
let penv = TVMParallelGroupEnv {
sync_handle: std::ptr::null_mut(),
num_task: 1,
};
cb(0, &penv as *const _, cdata);
} else {
THREAD_POOL.with(|pool| {
pool.launch(Job {
cb,
cdata,
req_num_tasks: num_task,
pending: Arc::new(AtomicUsize::new(0)),
});
});
}
0
}
// @see issue 988 for information on why this function is used.
#[no_mangle]
pub unsafe extern "C" fn TVMBackendParallelBarrier(
_task_id: usize,
penv: *const TVMParallelGroupEnv,
) {
let barrier: &Arc<Barrier> = &*((*penv).sync_handle as *const Arc<Barrier>);
barrier.wait();
}
#[cfg(test)]
mod tests {
use std::{thread, time::Duration};
use super::*;
#[test]
fn test_max_concurrency() {
env::set_var("TVM_NUM_THREADS", "42");
env::set_var("OMP_NUM_THREADS", "24");
assert_eq!(max_concurrency(), 42);
env::remove_var("TVM_NUM_THREADS");
assert_eq!(max_concurrency(), 24);
}
extern "C" fn _flambda(
task_id: usize,
penv: *const TVMParallelGroupEnv,
cdata: *const c_void,
) -> i32 {
if cdata.is_null() {
return 0;
}
unsafe {
let &(ref counter, ref task_ids_sum) = &*(cdata as *const (AtomicUsize, AtomicUsize));
thread::sleep(Duration::from_millis(50 * task_id as u64));
counter.fetch_add(1, Ordering::SeqCst);
task_ids_sum.fetch_add(task_id, Ordering::SeqCst);
assert_eq!((*penv).num_task, 3);
}
0
}
// #[test]
// fn test_parallel_launch() {
// TVMBackendParallelLaunch(flambda, ptr::null(), 6);
// let counter = AtomicUsize::new(0);
// let task_ids_sum = AtomicUsize::new(0);
// let cdata = (counter, task_ids_sum);
// let num_tasks = 3;
// TVMBackendParallelLaunch(flambda, &cdata as *const _ as *const c_void, num_tasks);
// assert_eq!(cdata.0.load(Ordering::SeqCst), num_tasks);
// assert_eq!(
// cdata.1.load(Ordering::SeqCst),
// (0..num_tasks).sum::<usize>()
// );
// }
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/src/workspace.rs | /*
* 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.
*/
use std::{
cell::RefCell,
error::Error,
os::raw::{c_int, c_void},
ptr,
};
use crate::allocator::Allocation;
use crate::errors::InvalidPointer;
use std::alloc::LayoutError;
const WS_ALIGN: usize = 64; // taken from `kTempAllocaAlignment` in `device_api.h`
pub fn remove_item<T: PartialEq>(vec: &mut Vec<T>, item: &T) -> Option<T> {
let pos = vec.iter().position(|x| *x == *item)?;
Some(vec.remove(pos))
}
struct WorkspacePool {
workspaces: Vec<Allocation>,
free: Vec<usize>,
in_use: Vec<usize>,
}
impl WorkspacePool {
fn new() -> Self {
WorkspacePool {
workspaces: Vec::new(),
free: Vec::new(),
in_use: Vec::new(),
}
}
fn alloc_new(&mut self, size: usize) -> Result<*mut u8, LayoutError> {
self.workspaces.push(Allocation::new(size, Some(WS_ALIGN))?);
self.in_use.push(self.workspaces.len() - 1);
Ok(self.workspaces[self.workspaces.len() - 1].as_mut_ptr())
}
fn alloc(&mut self, size: usize) -> Result<*mut u8, LayoutError> {
if self.free.is_empty() {
return self.alloc_new(size);
}
let idx = self
.free
.iter()
.fold(None, |cur_ws_idx: Option<usize>, &idx| {
let ws_size = self.workspaces[idx].size();
if ws_size < size {
return cur_ws_idx;
}
cur_ws_idx.or(Some(idx)).and_then(|cur_idx| {
let cur_size = self.workspaces[cur_idx].size();
Some(if ws_size <= cur_size { idx } else { cur_idx })
})
});
match idx {
Some(idx) => {
remove_item(&mut self.free, &idx).unwrap();
self.in_use.push(idx);
Ok(self.workspaces[idx].as_mut_ptr())
}
None => self.alloc_new(size),
}
}
fn free(&mut self, ptr: *mut u8) -> Result<(), Box<dyn Error>> {
let mut ws_idx = None;
for i in 0..self.in_use.len() {
let idx = self.in_use[i];
if self.workspaces[idx].as_mut_ptr() == ptr {
self.in_use.remove(i);
ws_idx = Some(idx);
break;
}
}
let ws_idx = ws_idx.ok_or_else(|| InvalidPointer(ptr))?;
self.free.push(ws_idx);
Ok(())
}
}
thread_local!(static WORKSPACE_POOL: RefCell<WorkspacePool> = RefCell::new(WorkspacePool::new()));
const WORKSPACE_PAGE_SIZE: usize = 4 << 10;
#[no_mangle]
pub extern "C" fn TVMBackendAllocWorkspace(
_device_type: c_int,
_device_id: c_int,
size: u64,
_dtype_code_hint: c_int,
_dtype_bits_hint: c_int,
) -> *mut c_void {
let nbytes = if size == 0 {
WORKSPACE_PAGE_SIZE
} else {
size as usize
};
WORKSPACE_POOL.with(|pool_cell| {
pool_cell
.borrow_mut()
.alloc(nbytes as usize)
.unwrap_or(ptr::null_mut()) as *mut c_void
})
}
#[no_mangle]
pub extern "C" fn TVMBackendFreeWorkspace(
_device_type: c_int,
_device_id: c_int,
ptr: *mut c_void,
) -> c_int {
WORKSPACE_POOL.with(|pool_cell| {
(match pool_cell.borrow_mut().free(ptr as *mut u8) {
Ok(()) => 0,
Err(_) => -1,
}) as c_int
})
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/build_model.py | #!/usr/bin/env python3
# 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.
"""Builds a simple graph for testing."""
from os import path as osp
import numpy as np
import tvm
from tvm import te
from tvm import relay, runtime
from tvm.relay import testing
CWD = osp.dirname(osp.abspath(osp.expanduser(__file__)))
def _get_model(dshape):
data = relay.var("data", shape=dshape)
fc = relay.nn.dense(data, relay.var("dense_weight"), units=dshape[-1] * 2)
fc = relay.nn.bias_add(fc, relay.var("dense_bias"))
left, right = relay.split(fc, indices_or_sections=2, axis=1)
one = relay.const(1, dtype="float32")
return relay.Tuple([(left + one), (right - one), fc])
def main():
dshape = (32, 16)
net = _get_model(dshape)
mod, params = testing.create_workload(net)
graph, lib, params = relay.build(mod, "llvm", params=params)
with open(osp.join(CWD, "graph.json"), "w") as f_resnet:
f_resnet.write(graph)
with open(osp.join(CWD, "graph.params"), "wb") as f_params:
f_params.write(runtime.save_param_dict(params))
if __name__ == "__main__":
main()
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_graph_serde.rs | /*
* 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.
*/
use std::{convert::TryFrom, fs, io::Read};
use tvm_graph_rt::Graph;
macro_rules! mf_dir {
($p:literal) => {
concat!(env!("CARGO_MANIFEST_DIR"), $p)
};
}
static PARAMS_FIXTURE_PATH: &str = mf_dir!("/tests/graph.params");
#[test]
fn test_load_graph() {
let output = std::process::Command::new(mf_dir!("/tests/build_model.py"))
.env(
"PYTHONPATH",
concat!(mf_dir!("/../../python"), ":", mf_dir!("/../../nnvm/python")),
)
.output()
.expect("Failed to build test model");
assert!(
std::path::Path::new(PARAMS_FIXTURE_PATH).exists(),
"Could not build test graph fixture: STDOUT:\n\n{}\nSTDERR: {}\n\n",
String::from_utf8(output.stdout).unwrap(),
String::from_utf8(output.stderr).unwrap()
);
let mut params_bytes = Vec::new();
fs::File::open(PARAMS_FIXTURE_PATH)
.unwrap()
.read_to_end(&mut params_bytes)
.unwrap();
let _params = tvm_graph_rt::load_param_dict(¶ms_bytes);
let graph = Graph::try_from(
&fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/graph.json")).unwrap(),
)
.unwrap();
assert_eq!(graph.nodes[3].op, "tvm_op");
assert_eq!(
graph.nodes[3]
.attrs
.as_ref()
.unwrap()
.get("func_name")
.unwrap(),
"tvmgen_default_fused_nn_dense_nn_bias_add"
);
assert_eq!(graph.nodes[3].inputs[0].index, 0);
assert_eq!(graph.nodes[4].inputs[0].index, 0);
assert_eq!(graph.heads.len(), 3);
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_nn/build.rs | /*
* 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.
*/
extern crate ar;
use std::{env, fs::File, path::Path, process::Command};
use anyhow::{Context, Result};
use ar::Builder;
fn main() -> Result<()> {
let out_dir = env::var("OUT_DIR")?;
let out_dir = Path::new(&out_dir).join("test_nn");
std::fs::create_dir_all(&out_dir)?;
let manifest_dir = env::var("CARGO_MANIFEST_DIR")?;
let manifest_dir = Path::new(&manifest_dir);
let generator = manifest_dir.join("src").join("build_test_graph.py");
let graph_path = out_dir.join("graph.o");
let output = Command::new(&generator)
.arg(&out_dir)
.output()
.with_context(|| format!("Failed to execute: {:?}", generator))?;
assert!(
graph_path.exists(),
"Could not build graph lib: {}",
String::from_utf8(output.stderr)
.unwrap()
.trim()
.split("\n")
.last()
.unwrap_or("")
);
let lib_file = out_dir.join("libtestnn.a");
let file = File::create(&lib_file).context("failed to create library file")?;
let mut builder = Builder::new(file);
builder.append_path(graph_path)?;
let status = Command::new("ranlib").arg(&lib_file).status()?;
assert!(status.success());
println!("cargo:rustc-link-lib=static=testnn");
println!("cargo:rustc-link-search=native={}", out_dir.display());
println!("cargo:rerun-if-changed={}", generator.display());
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_nn/src/build_test_graph.py | #!/usr/bin/env python3
# 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.
"""Builds a simple graph for testing."""
from os import path as osp
import sys
from tvm import runtime as tvm_runtime
from tvm import relay
from tvm.relay import testing
def _get_model(dshape):
data = relay.var("data", shape=dshape)
fc = relay.nn.dense(data, relay.var("dense_weight"), units=dshape[-1] * 2)
fc = relay.nn.bias_add(fc, relay.var("dense_bias"))
left, right = relay.split(fc, indices_or_sections=2, axis=1)
one = relay.const(1, dtype="float32")
return relay.Tuple([(left + one), (right - one), fc])
def main():
dshape = (4, 8)
net = _get_model(dshape)
mod, params = testing.create_workload(net)
runtime = relay.backend.Runtime("cpp", {"system-lib": True})
graph, lib, params = relay.build(mod, "llvm", runtime=runtime, params=params)
out_dir = sys.argv[1]
lib.save(osp.join(sys.argv[1], "graph.o"))
with open(osp.join(out_dir, "graph.json"), "w") as f_resnet:
f_resnet.write(graph)
with open(osp.join(out_dir, "graph.params"), "wb") as f_params:
f_params.write(tvm_runtime.save_param_dict(params))
if __name__ == "__main__":
main()
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_nn/src/main.rs | /*
* 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.
*/
use std::{collections::HashMap, convert::TryFrom, fs, io::Read};
use ndarray::{s, Array};
use tvm_graph_rt::{Graph, GraphExecutor, SystemLibModule, Tensor};
const BATCH_SIZE: usize = 4;
const IN_DIM: usize = 8;
macro_rules! check_sum {
($e:expr, $a:ident, $b:ident) => {
let a = Array::try_from($e.get_input(stringify!($a)).unwrap().to_owned()).unwrap();
check_sum!(a, $b);
};
($e:expr, $a:expr, $b:ident) => {
let a = Array::try_from($e.get_output($a).unwrap().to_owned()).unwrap();
check_sum!(a, $b);
};
($a:ident, $b:ident) => {
let a_sum: f32 = $a.scalar_sum();
let b_sum: f32 = $b.scalar_sum();
assert!((a_sum - b_sum).abs() < 1e-2, "{} != {}", a_sum, b_sum);
};
}
fn main() {
let syslib = SystemLibModule::default();
let mut params_bytes = Vec::new();
fs::File::open(concat!(env!("OUT_DIR"), "/test_nn/graph.params"))
.unwrap()
.read_to_end(&mut params_bytes)
.unwrap();
let params = tvm_graph_rt::load_param_dict(¶ms_bytes)
.unwrap()
.into_iter()
.map(|(k, v)| (k, v.to_owned()))
.collect::<HashMap<String, Tensor<'static>>>();
let graph = Graph::try_from(
&fs::read_to_string(concat!(env!("OUT_DIR"), "/test_nn/graph.json")).unwrap(),
)
.unwrap();
let mut exec = GraphExecutor::new(graph, &syslib).unwrap();
let x = Array::from_shape_vec(
(BATCH_SIZE, IN_DIM),
(0..BATCH_SIZE * IN_DIM)
.map(|x| x as f32)
.collect::<Vec<f32>>(),
)
.unwrap();
let p0 = params.get("p0").unwrap().to_owned();
let p1 = params.get("p1").unwrap().to_owned();
println!("p0: {:?}", p0.shape());
println!("p1: {:?}", p1.shape());
let w = Array::try_from(p0)
.unwrap()
.into_shape((BATCH_SIZE * 4, IN_DIM))
.unwrap();
let b = Array::try_from(p1).unwrap();
let dense = x.dot(&w.t()) + &b;
let left = dense.slice(s![.., 0..IN_DIM]);
let right = dense.slice(s![.., IN_DIM..]);
let expected_o0 = &left + 1f32;
let expected_o1 = &right - 1f32;
exec.load_params(params);
exec.set_input("data", (&x).into());
check_sum!(exec, data, x);
check_sum!(exec, p0, w);
check_sum!(exec, p1, b);
exec.run();
check_sum!(exec, 0, expected_o0);
check_sum!(exec, 1, expected_o1);
check_sum!(exec, 2, dense);
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_tvm_basic/build.rs | /*
* 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.
*/
extern crate ar;
use std::{path::PathBuf, process::Command};
use std::fs::File;
use anyhow::Result;
use ar::Builder;
fn main() -> Result<()> {
let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
out_dir.push("lib");
if !out_dir.is_dir() {
std::fs::create_dir(&out_dir)?;
}
let obj_file = out_dir.join("test.o");
let lib_file = out_dir.join("libtest_basic.a");
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()?;
assert!(
obj_file.exists(),
"Could not build tvm lib: {}",
String::from_utf8(output.stderr)?
.trim()
.split("\n")
.last()
.unwrap_or("")
);
let mut builder = Builder::new(File::create(&lib_file)?);
builder.append_path(&obj_file)?;
drop(builder);
let status = Command::new("ranlib").arg(&lib_file).status()?;
assert!(status.success());
println!("cargo:rustc-link-lib=static=test_basic");
println!("cargo:rustc-link-search=native={}", out_dir.display());
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_tvm_basic/src/build_test_lib.py | #!/usr/bin/env python3
# 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.
"""Prepares a simple TVM library for testing."""
from os import path as osp
import sys
import tvm
from tvm.relay.backend import Runtime
from tvm import te
def main():
n = te.var("n")
A = te.placeholder((n,), name="A")
B = te.placeholder((n,), name="B")
C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name="C")
s = tvm.te.create_schedule(C.op)
s[C].parallel(s[C].op.axis[0])
runtime = Runtime("cpp", {"system-lib": True})
print(tvm.lower(s, [A, B, C], simple_mode=True))
tvm.build(s, [A, B, C], "llvm", runtime=runtime).save(osp.join(sys.argv[1], "test.o"))
if __name__ == "__main__":
main()
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_tvm_basic/src/main.rs | /*
* 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.
*/
use ndarray::Array;
use tvm_graph_rt::{DLTensor, Module as _, SystemLibModule};
mod tvm_mod {
tvm_graph_rt::import_module!("lib/test.o");
}
fn main() {
// try static
let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);
let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);
let mut c = Array::from_vec(vec![0f32; 4]);
let e = Array::from_vec(vec![2f32, 2., 4., 4.]);
let mut a_dl: DLTensor = (&mut a).into();
let mut b_dl: DLTensor = (&mut b).into();
let mut c_dl: DLTensor = (&mut c).into();
let args = vec![(&mut a_dl).into(), (&mut b_dl).into(), (&mut c_dl).into()];
tvm_mod::default_function(&args[..]).unwrap();
assert!(c.all_close(&e, 1e-8f32));
// try runtime
let syslib = SystemLibModule::default();
let add = syslib
.get_function("default_function")
.expect("main function not found");
add(&args[..]).unwrap();
assert!(c.all_close(&e, 1e-8f32));
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_tvm_dso/build.rs | /*
* 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.
*/
use std::{env, path::Path, process::Command};
use anyhow::{Context, Result};
fn main() -> Result<()> {
let out_dir = env::var("OUT_DIR").unwrap();
let exe = concat!(env!("CARGO_MANIFEST_DIR"), "/src/build_test_lib.py");
let output = Command::new(exe)
.arg(&out_dir)
.output()
.with_context(|| anyhow::anyhow!("Failed to execute: {} {}", exe, &out_dir))?;
assert!(
Path::new(&format!("{}/test.so", out_dir)).exists(),
"Could not build tvm lib: {}",
String::from_utf8(output.stderr)
.unwrap()
.trim()
.split("\n")
.last()
.unwrap_or("")
);
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_tvm_dso/src/build_test_lib.py | #!/usr/bin/env python3
# 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.
"""Prepares a simple TVM library for testing."""
from os import path as osp
import sys
import tvm
from tvm import te
from tvm.contrib import cc
def main():
n = te.var("n")
A = te.placeholder((n,), name="A")
B = te.placeholder((n,), name="B")
C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name="C")
s = tvm.te.create_schedule(C.op)
s[C].parallel(s[C].op.axis[0])
print(tvm.lower(s, [A, B, C], simple_mode=True))
obj_file = osp.join(sys.argv[1], "test.o")
tvm.build(s, [A, B, C], "llvm").save(obj_file)
cc.create_shared(osp.join(sys.argv[1], "test.so"), [obj_file])
if __name__ == "__main__":
main()
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_tvm_dso/src/main.rs | /*
* 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.
*/
use ndarray::Array;
use tvm_graph_rt::{DLTensor, DsoModule, Module};
fn main() {
tvm_graph_rt::TVMGetLastError();
let module = DsoModule::new(concat!(env!("OUT_DIR"), "/test.so")).unwrap();
let add = module
.get_function("__tvm_main__")
.expect("main function not found");
let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);
let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);
let mut c = Array::from_vec(vec![0f32; 4]);
let e = Array::from_vec(vec![2f32, 2., 4., 4.]);
let mut a_dl: DLTensor = (&mut a).into();
let mut b_dl: DLTensor = (&mut b).into();
let mut c_dl: DLTensor = (&mut c).into();
let args = vec![(&mut a_dl).into(), (&mut b_dl).into(), (&mut c_dl).into()];
add(&args[..]).unwrap();
assert!(c.all_close(&e, 1e-8f32));
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_wasm32/build.rs | /*
* 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.
*/
use std::{path::PathBuf, process::Command};
use anyhow::{Context, Result};
fn main() -> Result<()> {
let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
out_dir.push("lib");
if !out_dir.is_dir() {
std::fs::create_dir(&out_dir).context("failed to create directory for WASM outputs")?;
}
let obj_file = out_dir.join("test.o");
let lib_file = out_dir.join("libtest_wasm32.a");
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()
.context("failed to execute Python script for generating TVM library")?;
assert!(
obj_file.exists(),
"Could not build tvm lib: {}",
String::from_utf8(output.stderr)
.unwrap()
.trim()
.split("\n")
.last()
.unwrap_or("")
);
let ar = option_env!("LLVM_AR").unwrap_or("llvm-ar-8");
let output = Command::new(ar)
.arg("rcs")
.arg(&lib_file)
.arg(&obj_file)
.output()
.context("failed to run LLVM_AR command")?;
assert!(
lib_file.exists(),
"Could not create archive: {}",
String::from_utf8(output.stderr)
.unwrap()
.trim()
.split("\n")
.last()
.unwrap_or("")
);
println!("cargo:rustc-link-lib=static=test_wasm32");
println!("cargo:rustc-link-search=native={}", out_dir.display());
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_wasm32/src/build_test_lib.py | #!/usr/bin/env python3
# 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.
"""Prepares a simple TVM library for testing."""
from os import path as osp
import sys
import tvm
from tvm import te
from tvm.relay.backend import Runtime
def main():
n = te.var("n")
A = te.placeholder((n,), name="A")
B = te.placeholder((n,), name="B")
C = te.compute(A.shape, lambda *i: A(*i) + B(*i), name="C")
s = tvm.te.create_schedule(C.op)
s[C].parallel(s[C].op.axis[0])
print(tvm.lower(s, [A, B, C], simple_mode=True))
runtime = Runtime("cpp", {"system-lib": True})
tvm.build(s, [A, B, C], "llvm -mtriple=wasm32-unknown-unknown", runtime=runtime).save(
osp.join(sys.argv[1], "test.o")
)
if __name__ == "__main__":
main()
| https://github.com/zk-ml/tachikoma |
rust/tvm-graph-rt/tests/test_wasm32/src/main.rs | /*
* 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.
*/
extern "C" {
static __tvm_module_ctx: i32;
}
#[no_mangle]
unsafe fn __get_tvm_module_ctx() -> i32 {
// Refer a symbol in the libtest_wasm32.a to make sure that the link of the
// library is not optimized out.
__tvm_module_ctx
}
extern crate ndarray;
#[macro_use]
extern crate tvm_graph_rt;
use ndarray::Array;
use tvm_graph_rt::{DLTensor, Module as _, SystemLibModule};
fn main() {
// try static
let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);
let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]);
let mut c = Array::from_vec(vec![0f32; 4]);
let e = Array::from_vec(vec![2f32, 2., 4., 4.]);
let mut a_dl: DLTensor = (&mut a).into();
let mut b_dl: DLTensor = (&mut b).into();
let mut c_dl: DLTensor = (&mut c).into();
let syslib = SystemLibModule::default();
let add = syslib
.get_function("default_function")
.expect("main function not found");
call_packed!(add, &mut a_dl, &mut b_dl, &mut c_dl).unwrap();
assert!(c.all_close(&e, 1e-8f32));
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-macros/src/external.rs | /*
* 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.
*/
use proc_macro2::Span;
use proc_macro_error::abort;
use quote::quote;
use syn::parse::{Parse, ParseStream, Result};
use syn::{
token::Semi, Attribute, FnArg, Generics, Ident, Lit, Meta, NestedMeta, Pat, ReturnType,
Signature, Type, Visibility,
};
struct ExternalItem {
attrs: Vec<Attribute>,
visibility: Visibility,
sig: Signature,
}
impl Parse for ExternalItem {
fn parse(input: ParseStream) -> Result<Self> {
let item = ExternalItem {
attrs: input.call(Attribute::parse_outer)?,
visibility: input.parse()?,
sig: input.parse()?,
};
let _semi: Semi = input.parse()?;
Ok(item)
}
}
struct External {
visibility: Visibility,
tvm_name: String,
ident: Ident,
generics: Generics,
inputs: Vec<FnArg>,
ret_type: ReturnType,
}
impl Parse for External {
fn parse(input: ParseStream) -> Result<Self> {
let method: ExternalItem = input.parse()?;
let visibility = method.visibility;
assert_eq!(method.attrs.len(), 1);
let sig = method.sig;
let tvm_name = method.attrs[0].parse_meta()?;
let tvm_name = match tvm_name {
Meta::List(meta_list) => {
let name = meta_list.path.get_ident().expect("name");
assert_eq!(name.to_string(), "name".to_string());
match meta_list.nested.first() {
Some(NestedMeta::Lit(Lit::Str(lit))) => lit.value(),
_ => panic!(),
}
}
_ => panic!(),
};
let ident = sig.ident;
let generics = sig.generics;
let inputs = sig
.inputs
.iter()
.cloned()
.map(|param| param.clone())
.collect();
let ret_type = sig.output;
Ok(External {
visibility,
tvm_name,
ident,
generics,
inputs,
ret_type,
})
}
}
struct ExternalInput {
externs: Vec<External>,
}
impl Parse for ExternalInput {
fn parse(input: ParseStream) -> Result<Self> {
let mut externs: Vec<External> = Vec::new();
loop {
if input.is_empty() {
break;
}
externs.push(input.parse()?);
}
Ok(ExternalInput { externs })
}
}
pub fn macro_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ext_input = syn::parse_macro_input!(input as ExternalInput);
let tvm_rt_crate = crate::util::get_tvm_rt_crate();
let result_type = quote! { #tvm_rt_crate::function::Result };
let mut items = Vec::new();
for external in &ext_input.externs {
let visibility = &external.visibility;
let name = &external.ident;
let global_name = format!("global_{}", external.ident);
let global_name = Ident::new(&global_name, Span::call_site());
let ext_name = &external.tvm_name;
let ty_params: Vec<syn::TypeParam> = external
.generics
.params
.iter()
.map(|ty_param| match ty_param {
syn::GenericParam::Type(param) => param.clone(),
_ => abort! { ty_param,
"Only supports type parameters."
},
})
.collect();
let args = &external.inputs;
let (args, tys): (Vec<Ident>, Vec<Type>) = args
.iter()
.map(|arg| match arg {
FnArg::Typed(pat_type) => match &*pat_type.pat {
Pat::Ident(pat_ident) => {
let ident: Ident = pat_ident.ident.clone();
let ty: Type = *pat_type.ty.clone();
(ident, ty)
}
_ => abort! { pat_type,
"Only supports type parameters."
},
},
pat => abort! {
pat, "invalid pattern type for function";
note = "{:?} is not allowed here", pat;
},
})
.unzip();
let ret_type = match &external.ret_type {
ReturnType::Type(_, rtype) => *rtype.clone(),
ReturnType::Default => syn::parse_str::<Type>("()").unwrap(),
};
let global = quote! {
#[allow(non_upper_case_globals)]
static #global_name: ::once_cell::sync::Lazy<#tvm_rt_crate::Function> =
::once_cell::sync::Lazy::new(|| {
#tvm_rt_crate::Function::get(#ext_name)
.expect(concat!("unable to load external function", stringify!(#ext_name), "from TVM registry."))
});
};
items.push(global);
let wrapper = quote! {
#visibility fn #name<#(#ty_params),*>(#(#args : #tys),*) -> #result_type<#ret_type> {
let func_ref: #tvm_rt_crate::Function = #global_name.clone();
let func_ref: Box<dyn Fn(#(#tys),*) -> #result_type<#ret_type>> = func_ref.into();
let res: #ret_type = func_ref(#(#args),*)?;
Ok(res)
}
};
items.push(wrapper);
}
proc_macro::TokenStream::from(quote! {
#(#items
)*
})
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-macros/src/import_module.rs | /*
* 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.
*/
use quote::quote;
use std::{fs::File, io::Read};
use syn::parse::{Parse, ParseStream, Result};
use syn::LitStr;
use std::path::PathBuf;
struct ImportModule {
importing_file: LitStr,
}
impl Parse for ImportModule {
fn parse(input: ParseStream) -> Result<Self> {
let importing_file: LitStr = input.parse()?;
Ok(ImportModule { importing_file })
}
}
pub fn macro_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let import_module_args = syn::parse_macro_input!(input as ImportModule);
let manifest =
std::env::var("CARGO_MANIFEST_DIR").expect("variable should always be set by Cargo.");
let mut path = PathBuf::new();
path.push(manifest);
path = path.join(import_module_args.importing_file.value());
let mut fd = File::open(&path)
.unwrap_or_else(|_| panic!("Unable to find TVM object file at `{}`", path.display()));
let mut buffer = Vec::new();
fd.read_to_end(&mut buffer).unwrap();
let fn_names = match goblin::Object::parse(&buffer).unwrap() {
goblin::Object::Elf(elf) => elf
.syms
.iter()
.filter_map(|s| {
if s.st_type() == 0 || goblin::elf::sym::type_to_str(s.st_type()) == "FILE" {
return None;
}
match elf.strtab.get(s.st_name) {
Some(Ok(name)) if name != "" => {
Some(syn::Ident::new(name, proc_macro2::Span::call_site()))
}
_ => None,
}
})
.collect::<Vec<_>>(),
goblin::Object::Mach(goblin::mach::Mach::Binary(obj)) => {
obj.symbols()
.filter_map(|s| match s {
Ok((name, ref nlist))
if nlist.is_global()
&& nlist.n_sect != 0
&& !name.ends_with("tvm_module_ctx") =>
{
Some(syn::Ident::new(
if name.starts_with('_') {
// Mach objects prepend a _ to globals.
&name[1..]
} else {
&name
},
proc_macro2::Span::call_site(),
))
}
_ => None,
})
.collect::<Vec<_>>()
}
_ => panic!("Unsupported object format."),
};
let extern_fns = quote! {
mod ext {
extern "C" {
#(
pub(super) fn #fn_names(
args: *const tvm_graph_rt::ffi::TVMValue,
type_codes: *const std::os::raw::c_int,
num_args: std::os::raw::c_int
) -> std::os::raw::c_int;
)*
}
}
};
let fns = quote! {
use tvm_graph_rt::{ffi::TVMValue, ArgValue, RetValue, FuncCallError};
#extern_fns
#(
pub fn #fn_names(args: &[ArgValue]) -> Result<RetValue, FuncCallError> {
let (values, type_codes): (Vec<TVMValue>, Vec<i32>) = args
.into_iter()
.map(|arg| {
let (val, code) = arg.to_tvm_value();
(val, code as i32)
})
.unzip();
let exit_code = unsafe {
ext::#fn_names(values.as_ptr(), type_codes.as_ptr(), values.len() as i32)
};
if exit_code == 0 {
Ok(RetValue::default())
} else {
Err(FuncCallError::get_with_context(stringify!(#fn_names).to_string()))
}
}
)*
};
proc_macro::TokenStream::from(fns)
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-macros/src/lib.rs | /*
* 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.
*/
use proc_macro::TokenStream;
use proc_macro_error::proc_macro_error;
mod external;
mod import_module;
mod object;
mod util;
#[proc_macro]
pub fn import_module(input: TokenStream) -> TokenStream {
import_module::macro_impl(input)
}
#[proc_macro_error]
#[proc_macro_derive(Object, attributes(base, ref_name, type_key, no_derive))]
pub fn macro_impl(input: TokenStream) -> TokenStream {
// let input = proc_macro2::TokenStream::from(input);
TokenStream::from(object::macro_impl(input))
}
#[proc_macro_error]
#[proc_macro]
pub fn external(input: TokenStream) -> TokenStream {
external::macro_impl(input)
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-macros/src/object.rs | /*
* 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.
*/
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::DeriveInput;
use syn::Ident;
use crate::util::*;
pub fn macro_impl(input: proc_macro::TokenStream) -> TokenStream {
let tvm_rt_crate = get_tvm_rt_crate();
let result = quote! { #tvm_rt_crate::function::Result };
let error = quote! { #tvm_rt_crate::errors::Error };
let derive_input = syn::parse_macro_input!(input as DeriveInput);
let payload_id = derive_input.ident.clone();
let type_key = get_attr(&derive_input, "type_key")
.map(attr_to_str)
.expect("Failed to get type_key");
let derive = get_attr(&derive_input, "no_derive")
.map(|_| false)
.unwrap_or(true);
let ref_id = get_attr(&derive_input, "ref_name")
.map(|a| Ident::new(attr_to_str(a).value().as_str(), Span::call_site()))
.unwrap_or_else(|| {
let id = payload_id.to_string();
let suffixes = ["Node", "Obj"];
if let Some(suf) = suffixes
.iter()
.find(|&suf| id.len() > suf.len() && id.ends_with(suf))
{
Ident::new(&id[..id.len() - suf.len()], payload_id.span())
} else {
panic!(
"Either 'ref_name' must be given, or the struct name must end one of {:?}",
suffixes
)
}
});
let base_tokens = match &derive_input.data {
syn::Data::Struct(s) => s.fields.iter().next().and_then(|f| {
let (base_id, base_ty) = (f.ident.clone()?, f.ty.clone());
if base_id == "base" {
// The transitive case of subtyping
Some(quote! {
impl<O> AsRef<O> for #payload_id
where #base_ty: AsRef<O>
{
fn as_ref(&self) -> &O {
self.#base_id.as_ref()
}
}
})
} else {
None
}
}),
_ => panic!("derive only works for structs"),
};
let ref_derives = if derive {
quote! { #[derive(Debug, Clone)]}
} else {
quote! { #[derive(Clone)] }
};
let mut expanded = quote! {
unsafe impl #tvm_rt_crate::object::IsObject for #payload_id {
const TYPE_KEY: &'static str = #type_key;
}
// a silly AsRef impl is necessary for subtyping to work
impl AsRef<#payload_id> for #payload_id {
fn as_ref(&self) -> &Self {
self
}
}
#ref_derives
pub struct #ref_id(Option<#tvm_rt_crate::object::ObjectPtr<#payload_id>>);
impl #tvm_rt_crate::object::IsObjectRef for #ref_id {
type Object = #payload_id;
fn as_ptr(&self) -> Option<&#tvm_rt_crate::object::ObjectPtr<Self::Object>> {
self.0.as_ref()
}
fn into_ptr(self) -> Option<#tvm_rt_crate::object::ObjectPtr<Self::Object>> {
self.0
}
fn from_ptr(object_ptr: Option<#tvm_rt_crate::object::ObjectPtr<Self::Object>>) -> Self {
#ref_id(object_ptr)
}
}
impl std::ops::Deref for #ref_id {
type Target = #payload_id;
fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap()
}
}
impl std::convert::From<#payload_id> for #ref_id {
fn from(payload: #payload_id) -> Self {
let ptr = #tvm_rt_crate::object::ObjectPtr::new(payload);
#tvm_rt_crate::object::IsObjectRef::from_ptr(Some(ptr))
}
}
impl std::convert::From<#tvm_rt_crate::object::ObjectPtr<#payload_id>> for #ref_id {
fn from(ptr: #tvm_rt_crate::object::ObjectPtr<#payload_id>) -> Self {
#tvm_rt_crate::object::IsObjectRef::from_ptr(Some(ptr))
}
}
impl std::convert::TryFrom<#tvm_rt_crate::RetValue> for #ref_id {
type Error = #error;
fn try_from(ret_val: #tvm_rt_crate::RetValue) -> #result<#ref_id> {
use std::convert::TryInto;
let ptr: #tvm_rt_crate::object::ObjectPtr<#payload_id> = ret_val.try_into()?;
Ok(ptr.into())
}
}
impl<'a> From<&'a #ref_id> for #tvm_rt_crate::ArgValue<'a> {
fn from(object_ref: &'a #ref_id) -> #tvm_rt_crate::ArgValue<'a> {
use std::ffi::c_void;
let object_ptr = &object_ref.0;
match object_ptr {
None => {
#tvm_rt_crate::ArgValue::
ObjectHandle(std::ptr::null::<c_void>() as *mut c_void)
}
Some(value) => value.into()
}
}
}
impl<'a> std::convert::TryFrom<#tvm_rt_crate::ArgValue<'a>> for #ref_id {
type Error = #error;
fn try_from(arg_value: #tvm_rt_crate::ArgValue<'a>) -> #result<#ref_id> {
use std::convert::TryInto;
let optr = arg_value.try_into()?;
Ok(#ref_id(Some(optr)))
}
}
impl From<#ref_id> for #tvm_rt_crate::RetValue {
fn from(object_ref: #ref_id) -> #tvm_rt_crate::RetValue {
use std::ffi::c_void;
let object_ptr = &object_ref.0;
match object_ptr {
None => {
#tvm_rt_crate::RetValue::ObjectHandle(std::ptr::null::<c_void>() as *mut c_void)
}
Some(value) => value.clone().into()
}
}
}
};
expanded.extend(base_tokens);
if derive {
let derives = quote! {
impl std::hash::Hash for #ref_id {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
impl std::cmp::PartialEq for #ref_id {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl std::cmp::Eq for #ref_id {}
};
expanded.extend(derives);
}
TokenStream::from(expanded)
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-macros/src/util.rs | /*
* 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.
*/
use proc_macro2::TokenStream;
use quote::quote;
use std::env;
pub fn get_tvm_rt_crate() -> TokenStream {
if env::var("CARGO_PKG_NAME").unwrap() == "tvm-rt" {
quote!(crate)
} else {
quote!(tvm_rt)
}
}
pub(crate) fn get_attr<'a>(
derive_input: &'a syn::DeriveInput,
name: &str,
) -> Option<&'a syn::Attribute> {
derive_input.attrs.iter().find(|a| a.path.is_ident(name))
}
pub(crate) fn attr_to_str(attr: &syn::Attribute) -> syn::LitStr {
match attr.parse_meta() {
Ok(syn::Meta::NameValue(syn::MetaNameValue {
lit: syn::Lit::Str(s),
..
})) => s,
Ok(m) => panic!("Expected a string literal, got {:?}", m),
Err(e) => panic!("{}", e),
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/array.rs | /*
* 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.
*/
use std::convert::{TryFrom, TryInto};
use std::iter::{FromIterator, IntoIterator, Iterator};
use std::marker::PhantomData;
use crate::errors::Error;
use crate::object::{IsObjectRef, Object, ObjectPtr, ObjectRef};
use crate::{
external,
function::{Function, Result},
ArgValue, RetValue,
};
#[repr(C)]
#[derive(Clone)]
pub struct Array<T: IsObjectRef> {
object: ObjectRef,
_data: PhantomData<T>,
}
// TODO(@jroesch): convert to use generics instead of casting inside
// the implementation.
external! {
#[name("runtime.ArrayGetItem")]
fn array_get_item(array: ObjectRef, index: isize) -> ObjectRef;
#[name("runtime.ArraySize")]
fn array_size(array: ObjectRef) -> i64;
}
impl<T: IsObjectRef + 'static> IsObjectRef for Array<T> {
type Object = Object;
fn as_ptr(&self) -> Option<&ObjectPtr<Self::Object>> {
self.object.as_ptr()
}
fn into_ptr(self) -> Option<ObjectPtr<Self::Object>> {
self.object.into_ptr()
}
fn from_ptr(object_ptr: Option<ObjectPtr<Self::Object>>) -> Self {
let object_ref = match object_ptr {
Some(o) => o.into(),
_ => panic!(),
};
Array {
object: object_ref,
_data: PhantomData,
}
}
}
impl<T: IsObjectRef> Array<T> {
pub fn from_vec(data: Vec<T>) -> Result<Array<T>> {
let iter = data.iter().map(T::into_arg_value).collect();
let func = Function::get("runtime.Array").expect(
"runtime.Array function is not registered, this is most likely a build or linking error",
);
// let array_data = func.invoke(iter)?;
// let array_data: ObjectRef = func.invoke(iter)?.try_into()?;
let array_data: ObjectPtr<Object> = func.invoke(iter)?.try_into()?;
debug_assert!(
array_data.count() >= 1,
"array reference count is {}",
array_data.count()
);
Ok(Array {
object: array_data.into(),
_data: PhantomData,
})
}
pub fn get(&self, index: isize) -> Result<T>
where
T: TryFrom<RetValue, Error = Error>,
{
let oref: ObjectRef = array_get_item(self.object.clone(), index)?;
oref.downcast()
}
pub fn len(&self) -> i64 {
array_size(self.object.clone()).expect("size should never fail")
}
}
impl<T: IsObjectRef> std::fmt::Debug for Array<T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
let as_vec: Vec<T> = self.clone().into_iter().collect();
write!(formatter, "{:?}", as_vec)
}
}
pub struct IntoIter<T: IsObjectRef> {
array: Array<T>,
pos: isize,
size: isize,
}
impl<T: IsObjectRef> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.pos < self.size {
let item =
self.array.get(self.pos)
.expect("Can not index as in-bounds position after bounds checking.\nNote: this error can only be do to an uncaught issue with API bindings.");
self.pos += 1;
Some(item)
} else {
None
}
}
}
impl<T: IsObjectRef> IntoIterator for Array<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
let size = self.len() as isize;
IntoIter {
array: self,
pos: 0,
size: size,
}
}
}
impl<T: IsObjectRef> FromIterator<T> for Array<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Array::from_vec(iter.into_iter().collect()).unwrap()
}
}
impl<'a, T: IsObjectRef> From<&'a Array<T>> for ArgValue<'a> {
fn from(array: &'a Array<T>) -> ArgValue<'a> {
(&array.object).into()
}
}
impl<T: IsObjectRef> From<Array<T>> for RetValue {
fn from(array: Array<T>) -> RetValue {
array.object.into()
}
}
impl<'a, T: IsObjectRef> TryFrom<ArgValue<'a>> for Array<T> {
type Error = Error;
fn try_from(array: ArgValue<'a>) -> Result<Array<T>> {
let object_ref: ObjectRef = array.try_into()?;
// TODO: type check
Ok(Array {
object: object_ref,
_data: PhantomData,
})
}
}
impl<'a, T: IsObjectRef> TryFrom<RetValue> for Array<T> {
type Error = Error;
fn try_from(array: RetValue) -> Result<Array<T>> {
let object_ref = array.try_into()?;
Ok(Array {
object: object_ref,
_data: PhantomData,
})
}
}
#[cfg(test)]
mod tests {
use super::Array;
use crate::function::Result;
use crate::object::{IsObjectRef, ObjectRef};
use crate::string::String;
#[test]
fn create_array_and_get() -> Result<()> {
let vec: Vec<String> = vec!["foo".into(), "bar".into(), "baz".into()];
let array = Array::from_vec(vec)?;
assert_eq!(array.get(0)?.to_string(), "foo");
assert_eq!(array.get(1)?.to_string(), "bar");
assert_eq!(array.get(2)?.to_string(), "baz");
Ok(())
}
#[test]
fn downcast() -> Result<()> {
let vec: Vec<String> = vec!["foo".into(), "bar".into(), "baz".into()];
let array: ObjectRef = ObjectRef::from_ptr(Array::from_vec(vec)?.into_ptr());
let array: Array<ObjectRef> = array.downcast::<Array<ObjectRef>>().unwrap();
assert_eq!(array.get(1)?.downcast::<String>().unwrap(), "bar");
Ok(())
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/device.rs | /*
* 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.
*/
use std::os::raw::c_void;
use std::ptr;
use crate::errors::Error;
use tvm_sys::ffi;
pub use tvm_sys::device::*;
trait DeviceExt {
/// Checks whether the device exists or not.
fn exist(&self) -> bool;
fn sync(&self) -> Result<(), Error>;
fn max_threads_per_block(&self) -> isize;
fn warp_size(&self) -> isize;
fn max_shared_memory_per_block(&self) -> isize;
fn compute_version(&self) -> isize;
fn device_name(&self) -> isize;
fn max_clock_rate(&self) -> isize;
fn multi_processor_count(&self) -> isize;
fn max_thread_dimensions(&self) -> isize;
}
macro_rules! impl_device_attrs {
($(($attr_name:ident, $attr_kind:expr));+) => {
$(
fn $attr_name(&self) -> isize {
get_device_attr(self.device_type as i32, self.device_id as i32, 0)
.expect("should not fail") as isize
}
)+
};
}
crate::external! {
#[name("runtime.GetDeviceAttr")]
fn get_device_attr(device_type: i32, device_id: i32, device_kind: i32) -> i32;
}
impl DeviceExt for Device {
fn exist(&self) -> bool {
let exists = get_device_attr(self.device_type as i32, self.device_id as i32, 0)
.expect("should not fail");
exists != 0
}
/// Synchronize the device stream.
fn sync(&self) -> Result<(), Error> {
check_call!(ffi::TVMSynchronize(
self.device_type as i32,
self.device_id as i32,
ptr::null_mut() as *mut c_void
));
Ok(())
}
impl_device_attrs!((max_threads_per_block, 1);
(warp_size, 2);
(max_shared_memory_per_block, 3);
(compute_version, 4);
(device_name, 5);
(max_clock_rate, 6);
(multi_processor_count, 7);
(max_thread_dimensions, 8));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sync() {
let dev = Device::cpu(0);
assert!(dev.sync().is_ok())
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/errors.rs | /*
* 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.
*/
use crate::DataType;
use thiserror::Error;
#[derive(Debug, Error)]
#[error("Function was not set in `function::Builder`")]
pub struct FunctionNotFoundError;
#[derive(Debug, Error)]
#[error("Expected type `{expected}` but found `{actual}`")]
pub struct TypeMismatchError {
pub expected: String,
pub actual: String,
}
#[derive(Debug, Error)]
pub enum NDArrayError {
#[error("Cannot convert from an empty array.")]
EmptyArray,
#[error("Invalid datatype when attempting to convert ndarray.")]
InvalidDatatype(#[from] tvm_sys::datatype::ParseDataTypeError),
#[error("a shape error occurred in the Rust ndarray library")]
ShapeError(#[from] ndarray::ShapeError),
#[error("Expected type `{expected}` but found `{actual}`")]
DataTypeMismatch {
expected: DataType,
actual: DataType,
},
}
#[derive(Debug, Error)]
pub enum Error {
#[error("{0}")]
Downcast(#[from] tvm_sys::errors::ValueDowncastError),
#[error("raw pointer passed across boundary was null")]
Null,
#[error("failed to load module due to invalid path {0}")]
ModuleLoadPath(String),
#[error("failed to convert String into CString due to embedded nul character")]
ToCString(#[from] std::ffi::NulError),
#[error("failed to convert CString into String")]
FromCString(#[from] std::ffi::IntoStringError),
#[error("Handle `{0}` is null.")]
NullHandle(String),
#[error("{0}")]
NDArray(#[from] NDArrayError),
#[error("{0}")]
CallFailed(String),
#[error("this case will never occur")]
Infallible(#[from] std::convert::Infallible),
#[error("a panic occurred while executing a Rust packed function")]
Panic,
#[error(
"one or more error diagnostics were emitted, please check diagnostic render for output."
)]
DiagnosticError(String),
#[error("{0}")]
Raw(String),
}
impl Error {
pub fn from_raw_tvm(raw: &str) -> Error {
let err_header = raw.find(":").unwrap_or(0);
let (err_ty, err_content) = raw.split_at(err_header);
match err_ty {
"DiagnosticError" => Error::DiagnosticError((&err_content[1..]).into()),
_ => Error::Raw(raw.into()),
}
}
}
impl Error {
pub fn downcast(actual_type: String, expected_type: &'static str) -> Error {
Self::Downcast(tvm_sys::errors::ValueDowncastError {
actual_type,
expected_type,
})
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/function.rs | /*
* 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.
*/
//! This module provides an idiomatic Rust API for creating and working with TVM functions.
//!
//! For calling an already registered TVM function use [`function::Builder`]
//! To register a TVM packed function from Rust side either
//! use [`function::register`] or the macro [`register_global_func`].
//!
//! See the tests and examples repository for more examples.
use std::convert::{TryFrom, TryInto};
use std::sync::Arc;
use std::{
ffi::CString,
os::raw::{c_char, c_int},
ptr, str,
};
use crate::errors::Error;
pub use super::to_function::{RawArgs, ToFunction, Typed};
use crate::object::AsArgValue;
pub use tvm_sys::{ffi, ArgValue, RetValue};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Hash)]
struct FunctionPtr {
handle: ffi::TVMFunctionHandle,
}
// NB(@jroesch): I think this is ok, need to double check,
// if not we should mutex the pointer or move to Rc.
unsafe impl Send for FunctionPtr {}
unsafe impl Sync for FunctionPtr {}
impl FunctionPtr {
fn from_raw(handle: ffi::TVMFunctionHandle) -> Self {
FunctionPtr { handle }
}
}
impl Drop for FunctionPtr {
fn drop(&mut self) {
check_call!(ffi::TVMFuncFree(self.handle));
}
}
/// An owned thread-safe version of `tvm::PackedFunc` for consumption in Rust.
#[derive(Debug, Hash)]
pub struct Function {
inner: Arc<FunctionPtr>,
}
impl Function {
pub(crate) fn from_raw(handle: ffi::TVMFunctionHandle) -> Self {
Function {
inner: Arc::new(FunctionPtr::from_raw(handle)),
}
}
pub unsafe fn null() -> Self {
Function::from_raw(std::ptr::null_mut())
}
/// For a given function, it returns a function by name.
pub fn get<S: AsRef<str>>(name: S) -> Option<Function> {
let name = CString::new(name.as_ref()).unwrap();
let mut handle = ptr::null_mut() as ffi::TVMFunctionHandle;
check_call!(ffi::TVMFuncGetGlobal(
name.as_ptr() as *const c_char,
&mut handle as *mut _
));
if handle.is_null() {
None
} else {
Some(Function::from_raw(handle))
}
}
pub fn get_boxed<F, S>(name: S) -> Option<Box<F>>
where
S: AsRef<str>,
F: ?Sized,
Self: Into<Box<F>>,
{
Self::get(name).map(|f| f.into())
}
/// Returns the underlying TVM function handle.
pub fn handle(&self) -> ffi::TVMFunctionHandle {
self.inner.handle
}
/// Calls the function that created from `Builder`.
pub fn invoke<'a>(&self, arg_buf: Vec<ArgValue<'a>>) -> Result<RetValue> {
let num_args = arg_buf.len();
let (mut values, mut type_codes): (Vec<ffi::TVMValue>, Vec<ffi::TVMArgTypeCode>) =
arg_buf.into_iter().map(|arg| arg.to_tvm_value()).unzip();
let mut ret_val = ffi::TVMValue { v_int64: 0 };
let mut ret_type_code = 0i32;
let ret_code = unsafe {
ffi::TVMFuncCall(
self.handle(),
values.as_mut_ptr() as *mut ffi::TVMValue,
type_codes.as_mut_ptr() as *mut c_int,
num_args as c_int,
&mut ret_val as *mut _,
&mut ret_type_code as *mut _,
)
};
if ret_code != 0 {
let raw_error = crate::get_last_error();
let error = match Error::from_raw_tvm(raw_error) {
Error::Raw(string) => Error::CallFailed(string),
e => e,
};
return Err(error);
}
let rv = RetValue::from_tvm_value(ret_val, ret_type_code as u32);
Ok(rv)
}
}
macro_rules! impl_to_fn {
() => { impl_to_fn!(@impl); };
($t:ident, $($ts:ident,)*) => { impl_to_fn!(@impl $t, $($ts,)*); impl_to_fn!($($ts,)*); };
(@impl $($t:ident,)*) => {
impl<Err, Out, $($t,)*> From<Function> for Box<dyn Fn($($t,)*) -> Result<Out>>
where
Error: From<Err>,
Out: TryFrom<RetValue, Error = Err>,
$($t: for<'a> AsArgValue<'a>),*
{
fn from(func: Function) -> Self {
#[allow(non_snake_case)]
Box::new(move |$($t : $t),*| {
let args = vec![ $((&$t).as_arg_value()),* ];
Ok(func.invoke(args)?.try_into()?)
})
}
}
};
}
impl_to_fn!(T1, T2, T3, T4, T5, T6,);
impl Clone for Function {
fn clone(&self) -> Function {
Function {
inner: self.inner.clone(),
}
}
}
impl From<Function> for RetValue {
fn from(func: Function) -> RetValue {
RetValue::FuncHandle(func.handle())
}
}
impl TryFrom<RetValue> for Function {
type Error = Error;
fn try_from(ret_value: RetValue) -> Result<Function> {
match ret_value {
RetValue::FuncHandle(handle) => Ok(Function::from_raw(handle)),
_ => Err(Error::downcast(
format!("{:?}", ret_value),
"FunctionHandle",
)),
}
}
}
impl<'a> From<&'a Function> for ArgValue<'a> {
fn from(func: &'a Function) -> ArgValue<'a> {
if func.handle().is_null() {
ArgValue::Null
} else {
ArgValue::FuncHandle(func.handle())
}
}
}
impl<'a> TryFrom<ArgValue<'a>> for Function {
type Error = Error;
fn try_from(arg_value: ArgValue<'a>) -> Result<Function> {
match arg_value {
ArgValue::FuncHandle(handle) => Ok(Function::from_raw(handle)),
_ => Err(Error::downcast(
format!("{:?}", arg_value),
"FunctionHandle",
)),
}
}
}
impl<'a> TryFrom<&ArgValue<'a>> for Function {
type Error = Error;
fn try_from(arg_value: &ArgValue<'a>) -> Result<Function> {
match arg_value {
ArgValue::FuncHandle(handle) => Ok(Function::from_raw(*handle)),
_ => Err(Error::downcast(
format!("{:?}", arg_value),
"FunctionHandle",
)),
}
}
}
/// Registers a Rust function with an arbitrary type signature in
/// the TVM registry.
///
///
/// A function is convertible if and only if its arguments and return types are convertible
/// to and from TVM values respectively.
///
/// Use [`register_override`] if control of overriding existing global TVM function
/// is required, this function will panic if a function is already registered.
///
/// ## Example
///
/// ```
/// # use tvm_rt::{ArgValue, RetValue};
/// # use tvm_rt::function::{Function, Result, register};
///
/// fn sum(x: i64, y: i64, z: i64) -> i64 {
/// x + y + z
/// }
///
/// register(sum, "mysum".to_owned()).unwrap();
/// let func = Function::get("mysum").unwrap();
/// let boxed_fn: Box<dyn Fn(i64, i64, i64) -> Result<i64>> = func.into();
/// let ret = boxed_fn(10, 20, 30).unwrap();
/// assert_eq!(ret, 60);
/// ```
pub fn register<F, I, O, S: Into<String>>(f: F, name: S) -> Result<()>
where
F: ToFunction<I, O>,
F: Typed<I, O>,
{
register_override(f, name, false)
}
/// Register a function with explicit control over whether to override an existing registration or not.
///
/// See `register` for more details on how to use the registration API.
pub fn register_override<F, I, O, S: Into<String>>(f: F, name: S, override_: bool) -> Result<()>
where
F: ToFunction<I, O>,
F: Typed<I, O>,
{
let func = f.to_function();
let name = name.into();
// Not sure about this code
let handle = func.handle();
let name = CString::new(name)?;
check_call!(ffi::TVMFuncRegisterGlobal(
name.into_raw(),
handle,
override_ as c_int
));
Ok(())
}
pub fn register_untyped<S: Into<String>>(
f: for<'a> fn(Vec<ArgValue<'a>>) -> Result<RetValue>,
name: S,
override_: bool,
) -> Result<()> {
//TODO(@jroesch): can we unify the untpyed and typed registration functions.
let func = ToFunction::<RawArgs, RetValue>::to_function(f);
let name = name.into();
// Not sure about this code
let handle = func.handle();
let name = CString::new(name)?;
check_call!(ffi::TVMFuncRegisterGlobal(
name.into_raw(),
handle,
override_ as c_int
));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::function::Function;
static CANARY: &str = "runtime.ModuleLoadFromFile";
#[test]
fn get_fn() {
assert!(Function::get(CANARY).is_some());
assert!(Function::get("does not exists!").is_none());
}
#[test]
fn register_and_call_closure0() {
use crate::function;
use function::Result;
fn constfn() -> i64 {
return 10;
}
function::register_override(constfn, "constfn".to_owned(), true).unwrap();
let func = Function::get_boxed::<dyn Fn() -> Result<i32>, _>("constfn").unwrap();
let ret = func().unwrap();
assert_eq!(ret, 10);
}
#[test]
fn register_and_call_closure1() {
use crate::function::{self};
fn ident(x: i64) -> i64 {
return x;
}
function::register_override(ident, "ident".to_owned(), true).unwrap();
let func = Function::get_boxed::<dyn Fn(i32) -> Result<i32>, _>("ident").unwrap();
assert_eq!(func(60).unwrap(), 60);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/graph_rt.rs | /*
* 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.
*/
use std::convert::TryInto;
use crate::Function;
use crate::{function::Result, ByteArray, Device, Module, NDArray};
/// An instance of the C++ graph executor.
///
/// An efficient and light weight runtime for static deep learning models.
pub struct GraphRt {
/// The backing graph executor module which exposes a set of packed functions
/// which can be invoked by a client.
///
/// In the graph executor module, it exposes create, load_params, set_input, get_output, and run.
module: Module,
}
impl GraphRt {
/// Create a graph executor directly from a runtime module.
pub fn from_module(module: Module, dev: Device) -> Result<GraphRt> {
let default: Box<dyn Fn(Device) -> Result<Module>> =
module.get_function("default", false)?.into();
Ok(Self {
module: default(dev)?,
})
}
/// Create a graph executor from the deprecated graph, lib, dev triple.
pub fn create_from_parts(graph: &str, lib: Module, dev: Device) -> Result<Self> {
let runtime_create_fn = Function::get("tvm.graph_executor.create").unwrap();
let runtime_create_fn_ret = runtime_create_fn.invoke(vec![
graph.into(),
(&lib).into(),
(&dev.device_type).into(),
// NOTE you must pass the device id in as i32 because that's what TVM expects
(dev.device_id as i32).into(),
]);
let graph_executor_module: Module = runtime_create_fn_ret?.try_into()?;
Ok(Self {
module: graph_executor_module,
})
}
/// Load the parameters of the model into the runtime.
pub fn load_params<P>(&mut self, params: P) -> Result<()>
where
P: Into<ByteArray>,
{
let load_param_fn = self.module.get_function("load_params", false)?;
let params: ByteArray = params.into();
load_param_fn.invoke(vec![(¶ms).into()])?;
Ok(())
}
/// Set the input with name `name` with the value of `input`.
pub fn set_input(&mut self, name: &str, input: NDArray) -> Result<()> {
let ref set_input_fn = self.module.get_function("set_input", false)?;
set_input_fn.invoke(vec![name.into(), (&input).into()])?;
Ok(())
}
/// Run the graph module, once setting parameters and inputs.
pub fn run(&mut self) -> Result<()> {
let ref run_fn = self.module.get_function("run", false)?;
// execute the run function. Note that it has no argument
run_fn.invoke(vec![])?;
Ok(())
}
/// Extract the ith output from the graph executor and returns it.
pub fn get_output(&mut self, i: i64) -> Result<NDArray> {
let get_output_fn = self.module.get_function("get_output", false)?;
get_output_fn.invoke(vec![i.into()])?.try_into()
}
/// Extract the ith output from the graph executor and write the results into output.
pub fn get_output_into(&mut self, i: i64, output: NDArray) -> Result<()> {
let get_output_fn = self.module.get_function("get_output", false)?;
get_output_fn.invoke(vec![i.into(), (&output).into()])?;
Ok(())
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/lib.rs | /*
* 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.
*/
//! [TVM](https://github.com/apache/tvm) is a compiler stack for deep learning systems.
//!
//! This crate provides an idiomatic Rust API for TVM runtime.
//!
//! The TVM runtime API contains the data structures used by higher-level TVM executors.
//! Specifically it exposes the basic types such as NDArray, as well as the more general object system.
//! The TVM object system enables cross-language interoperability including that of closures for all
//! supported languages including C++, and Python.
// Macro to check the return call to TVM runtime shared library.
#[macro_export]
macro_rules! tvm_call {
($e:expr) => {{
if unsafe { $e } != 0 {
Err($crate::get_last_error().into())
} else {
Ok(())
}
}};
}
#[macro_export]
macro_rules! check_call {
($e:expr) => {{
if unsafe { $e } != 0 {
panic!("{}", $crate::get_last_error());
}
}};
}
// Define all sumodules.
pub mod array;
pub mod device;
pub mod errors;
pub mod function;
pub mod graph_rt;
pub mod map;
pub mod module;
pub mod ndarray;
pub mod object;
pub mod string;
mod to_function;
pub use object::*;
pub use string::*;
use std::{
ffi::{CStr, CString},
str,
};
pub use crate::{
device::{Device, DeviceType},
errors::*,
function::Function,
module::Module,
ndarray::NDArray,
};
pub use function::{ArgValue, RetValue};
pub use tvm_sys::byte_array::ByteArray;
pub use tvm_sys::datatype::DataType;
use tvm_sys::ffi;
pub use tvm_macros::external;
/// Gets the last error message.
pub fn get_last_error() -> &'static str {
unsafe {
match CStr::from_ptr(ffi::TVMGetLastError()).to_str() {
Ok(s) => s,
Err(_) => "Invalid UTF-8 message",
}
}
}
pub(crate) fn set_last_error<E: std::error::Error>(err: &E) {
let c_string = CString::new(err.to_string()).unwrap();
unsafe {
ffi::TVMAPISetLastError(c_string.as_ptr());
}
}
/// Outputs the current TVM version.
pub fn version() -> &'static str {
match str::from_utf8(ffi::TVM_VERSION) {
Ok(s) => s,
Err(_) => "Invalid UTF-8 string",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ByteArray, DataType, Device};
use std::{convert::TryInto, str::FromStr};
#[test]
fn print_version() {
println!("TVM version: {}", version());
}
#[test]
fn set_error() {
let err = errors::NDArrayError::EmptyArray;
set_last_error(&err);
assert_eq!(
get_last_error().trim(),
errors::NDArrayError::EmptyArray.to_string()
);
}
// todo(@jroesch): #8800 Follow up with ByteArray RetValue ownership.
// #[test]
// fn bytearray() {
// let w = vec![1u8, 2, 3, 4, 5];
// let v = ByteArray::from(w.as_slice());
// let tvm: ByteArray = RetValue::from(v).try_into().unwrap();
// assert_eq!(
// tvm.data(),
// w.iter().copied().collect::<Vec<u8>>().as_slice()
// );
// }
#[test]
fn ty() {
let t = DataType::from_str("int32").unwrap();
let tvm: DataType = RetValue::from(t).try_into().unwrap();
assert_eq!(tvm, t);
}
#[test]
fn device() {
let c = Device::from_str("cuda").unwrap();
let tvm: Device = RetValue::from(c).try_into().unwrap();
assert_eq!(tvm, c);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/map.rs | /*
* 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.
*/
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::iter::FromIterator;
use std::marker::PhantomData;
use crate::object::debug_print;
use crate::array::Array;
use crate::errors::Error;
use crate::object::{IsObjectRef, Object, ObjectPtr, ObjectRef};
use crate::ArgValue;
use crate::{
external,
function::{Function, Result},
RetValue,
};
#[repr(C)]
#[derive(Clone)]
pub struct Map<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
object: ObjectRef,
_data: PhantomData<(K, V)>,
}
// TODO(@jroesch): convert to use generics instead of casting inside
// the implementation.
external! {
#[name("runtime.MapSize")]
fn map_size(map: ObjectRef) -> i64;
#[name("runtime.MapGetItem")]
fn map_get_item(map_object: ObjectRef, key: ObjectRef) -> ObjectRef;
#[name("runtime.MapCount")]
fn map_count(map: ObjectRef, key: ObjectRef) -> ObjectRef;
#[name("runtime.MapItems")]
fn map_items(map: ObjectRef) -> Array<ObjectRef>;
}
impl<'a, K: 'a, V: 'a> FromIterator<(&'a K, &'a V)> for Map<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
fn from_iter<T: IntoIterator<Item = (&'a K, &'a V)>>(iter: T) -> Self {
let iter = iter.into_iter();
let (lower_bound, upper_bound) = iter.size_hint();
let mut buffer: Vec<ArgValue> = Vec::with_capacity(upper_bound.unwrap_or(lower_bound) * 2);
for (k, v) in iter {
buffer.push(k.into_arg_value());
buffer.push(v.into_arg_value());
}
Self::from_data(buffer).expect("failed to convert from data")
}
}
impl<K, V> Map<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
pub fn from_data(data: Vec<ArgValue>) -> Result<Map<K, V>> {
let func = Function::get("runtime.Map").expect(
"runtime.Map function is not registered, this is most likely a build or linking error",
);
let map_data: ObjectPtr<Object> = func.invoke(data)?.try_into()?;
debug_assert!(
map_data.count() >= 1,
"map_data count is {}",
map_data.count()
);
Ok(Map {
object: map_data.into(),
_data: PhantomData,
})
}
pub fn get(&self, key: &K) -> Result<V>
where
V: TryFrom<RetValue, Error = Error>,
{
let key = key.clone();
let oref: ObjectRef = map_get_item(self.object.clone(), key.upcast())?;
oref.downcast()
}
pub fn empty() -> Self {
Self::from_iter(vec![].into_iter())
}
//(@jroesch): I don't think this is a correct implementation.
pub fn null() -> Self {
Map {
object: ObjectRef::null(),
_data: PhantomData,
}
}
}
pub struct IntoIter<K, V> {
// NB: due to FFI this isn't as lazy as one might like
key_and_values: Array<ObjectRef>,
next_key: i64,
_data: PhantomData<(K, V)>,
}
impl<K, V> Iterator for IntoIter<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
type Item = (K, V);
#[inline]
fn next(&mut self) -> Option<(K, V)> {
if self.next_key < self.key_and_values.len() {
let key = self
.key_and_values
.get(self.next_key as isize)
.expect("this should always succeed");
let value = self
.key_and_values
.get((self.next_key as isize) + 1)
.expect("this should always succeed");
self.next_key += 2;
Some((key.downcast().unwrap(), value.downcast().unwrap()))
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
((self.key_and_values.len() / 2) as usize, None)
}
}
impl<K, V> IntoIterator for Map<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> IntoIter<K, V> {
let items = map_items(self.object).expect("unable to get map items");
IntoIter {
key_and_values: items,
next_key: 0,
_data: PhantomData,
}
}
}
use std::fmt;
impl<K, V> fmt::Debug for Map<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let ctr = debug_print(self.object.clone()).unwrap();
fmt.write_fmt(format_args!("{:?}", ctr))
}
}
impl<K, V, S> From<Map<K, V>> for HashMap<K, V, S>
where
K: Eq + std::hash::Hash,
K: IsObjectRef,
V: IsObjectRef,
S: std::hash::BuildHasher + std::default::Default,
{
fn from(map: Map<K, V>) -> HashMap<K, V, S> {
HashMap::from_iter(map.into_iter())
}
}
impl<'a, K, V> From<&'a Map<K, V>> for ArgValue<'a>
where
K: IsObjectRef,
V: IsObjectRef,
{
fn from(map: &'a Map<K, V>) -> ArgValue<'a> {
(&map.object).into()
}
}
impl<K, V> From<Map<K, V>> for RetValue
where
K: IsObjectRef,
V: IsObjectRef,
{
fn from(map: Map<K, V>) -> RetValue {
map.object.into()
}
}
impl<'a, K, V> TryFrom<ArgValue<'a>> for Map<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
type Error = Error;
fn try_from(array: ArgValue<'a>) -> Result<Map<K, V>> {
let object_ref: ObjectRef = array.try_into()?;
// TODO: type check
Ok(Map {
object: object_ref,
_data: PhantomData,
})
}
}
impl<K, V> TryFrom<RetValue> for Map<K, V>
where
K: IsObjectRef,
V: IsObjectRef,
{
type Error = Error;
fn try_from(array: RetValue) -> Result<Map<K, V>> {
let object_ref = array.try_into()?;
// TODO: type check
Ok(Map {
object: object_ref,
_data: PhantomData,
})
}
}
#[cfg(test)]
mod test {
use std::collections::HashMap;
use super::*;
use crate::string::String as TString;
#[test]
fn test_from_into_hash_map() {
let mut std_map: HashMap<TString, TString> = HashMap::new();
std_map.insert("key1".into(), "value1".into());
std_map.insert("key2".into(), "value2".into());
let tvm_map = Map::from_iter(std_map.iter());
let back_map = tvm_map.into();
assert_eq!(std_map, back_map);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/module.rs | /*
* 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.
*/
//! Provides the [`Module`] type and methods for working with runtime TVM modules.
use std::{
ffi::CString,
os::raw::{c_char, c_int},
path::Path,
ptr,
};
use crate::object::Object;
use tvm_macros::Object;
use tvm_sys::ffi;
use crate::errors::Error;
use crate::String as TString;
use crate::{errors, function::Function};
/// Wrapper around TVM module handle which contains an entry function.
/// The entry function can be applied to an imported module through [`entry_func`].
///
/// [`entry_func`]:struct.Module.html#method.entry_func
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Module"]
#[type_key = "runtime.Module"]
pub struct ModuleNode {
base: Object,
}
crate::external! {
#[name("runtime.RuntimeEnabled")]
fn runtime_enabled(target: CString) -> i32;
#[name("runtime.ModuleLoadFromFile")]
fn load_from_file(file_name: CString, format: CString) -> Module;
#[name("runtime.ModuleSaveToFile")]
fn save_to_file(module: Module, name: TString, fmt: TString);
// TODO(@jroesch): we need to refactor this
#[name("tvm.relay.module_export_library")]
fn export_library(module: Module, file_name: TString);
}
impl Module {
pub fn default_fn(&mut self) -> Result<Function, Error> {
self.get_function("default", true)
}
/// Gets a function by name from a registered module.
pub fn get_function(&self, name: &str, query_import: bool) -> Result<Function, Error> {
let name = CString::new(name)?;
let mut fhandle = ptr::null_mut() as ffi::TVMFunctionHandle;
check_call!(ffi::TVMModGetFunction(
self.handle(),
name.as_ptr() as *const c_char,
query_import as c_int,
&mut fhandle as *mut _
));
if fhandle.is_null() {
return Err(errors::Error::NullHandle(name.into_string()?.to_string()));
}
Ok(Function::from_raw(fhandle))
}
/// Imports a dependent module such as `.ptx` for cuda gpu.
pub fn import_module(&self, dependent_module: Module) {
check_call!(ffi::TVMModImport(self.handle(), dependent_module.handle()))
}
/// Loads a module shared library from path.
pub fn load<P: AsRef<Path>>(path: &P) -> Result<Module, Error> {
let ext = CString::new(
path.as_ref()
.extension()
.unwrap_or_else(|| std::ffi::OsStr::new(""))
.to_str()
.ok_or_else(|| Error::ModuleLoadPath(path.as_ref().display().to_string()))?,
)?;
let cpath = CString::new(
path.as_ref()
.to_str()
.ok_or_else(|| Error::ModuleLoadPath(path.as_ref().display().to_string()))?,
)?;
let module = load_from_file(cpath, ext)?;
Ok(module)
}
pub fn save_to_file(&self, name: String, fmt: String) -> Result<(), Error> {
save_to_file(self.clone(), name.into(), fmt.into())
}
pub fn export_library(&self, name: String) -> Result<(), Error> {
export_library(self.clone(), name.into())
}
/// Checks if a target device is enabled for a module.
pub fn enabled(&self, target: &str) -> bool {
let target = CString::new(target).unwrap();
let enabled = runtime_enabled(target).unwrap();
enabled != 0
}
/// Returns the underlying module handle.
pub unsafe fn handle(&self) -> ffi::TVMModuleHandle {
self.0.clone().unwrap().into_raw() as *mut _
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/ndarray.rs | /*
* 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.
*/
//! This module implements the [`NDArray`] type for working with *TVM tensors* or
//! coverting from a Rust's ndarray to TVM `NDArray`.
//!
//! One can create an empty NDArray given the shape, device and dtype using [`empty`].
//! To create an NDArray from a mutable buffer in cpu use [`copy_from_buffer`].
//! To copy an NDArray to different device use [`copy_to_device`].
//!
//! Given a [`Rust's dynamic ndarray`], one can convert it to TVM NDArray as follows:
//!
//! # Example
//!
//! ```
//! # use tvm_rt::{NDArray, DataType, Device};
//! # use ndarray::{Array, ArrayD};
//! # use std::str::FromStr;
//! use std::convert::TryFrom;
//!
//! let a = Array::from_shape_vec((2, 2), vec![1f32, 2., 3., 4.])
//! .unwrap()
//! .into_dyn(); // Rust's ndarray
//! let nd = NDArray::from_rust_ndarray(&a, Device::cpu(0), DataType::from_str("float32").unwrap()).unwrap();
//! assert_eq!(nd.shape(), &[2, 2]);
//! let rnd: ArrayD<f32> = ArrayD::try_from(&nd).unwrap();
//! assert!(rnd.all_close(&a, 1e-8f32));
//! ```
//!
//! [`Rust's dynamic ndarray`]:https://docs.rs/ndarray/0.12.1/ndarray/
//! [`copy_from_buffer`]:struct.NDArray.html#method.copy_from_buffer
//! [`copy_to_device`]:struct.NDArray.html#method.copy_to_device
use std::ffi::c_void;
use std::{borrow::Cow, convert::TryInto};
use std::{convert::TryFrom, mem, os::raw::c_int, ptr, slice, str::FromStr};
use mem::size_of;
use tvm_macros::Object;
use tvm_sys::ffi::DLTensor;
use tvm_sys::{ffi, ByteArray, DataType, Device};
use ndarray::{Array, ArrayD};
use num_traits::Num;
use crate::errors::NDArrayError;
use crate::object::{Object, ObjectPtr, ObjectRef};
/// See the [`module-level documentation`](../ndarray/index.html) for more details.
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "NDArray"]
#[type_key = "runtime.NDArray"]
pub struct NDArrayContainer {
base: Object,
// Container Base
dl_tensor: DLTensor,
manager_ctx: *mut c_void,
shape: ObjectRef,
}
impl NDArrayContainer {
pub(crate) fn from_raw(handle: ffi::TVMArrayHandle) -> Option<ObjectPtr<Self>> {
let base_offset = memoffset::offset_of!(NDArrayContainer, dl_tensor) as isize;
let base_ptr = unsafe { (handle as *mut i8).offset(-base_offset) };
let object_ptr = ObjectPtr::from_raw(base_ptr.cast());
object_ptr.map(|ptr| {
ptr.downcast::<NDArrayContainer>()
.expect("we know this is an NDArray container")
})
}
pub fn leak<'a>(object_ptr: ObjectPtr<NDArrayContainer>) -> &'a mut NDArrayContainer
where
NDArrayContainer: 'a,
{
let base_offset = memoffset::offset_of!(NDArrayContainer, dl_tensor) as isize;
unsafe {
&mut *std::mem::ManuallyDrop::new(object_ptr)
.ptr
.as_ptr()
.cast::<u8>()
.offset(base_offset)
.cast::<NDArrayContainer>()
}
}
pub fn as_mut_ptr<'a>(object_ptr: &ObjectPtr<NDArrayContainer>) -> *mut NDArrayContainer
where
NDArrayContainer: 'a,
{
let base_offset = memoffset::offset_of!(NDArrayContainer, dl_tensor) as isize;
unsafe {
object_ptr
.ptr
.as_ptr()
.cast::<u8>()
.offset(base_offset)
.cast::<NDArrayContainer>()
}
}
}
fn cow_usize<'a>(slice: &[i64]) -> Cow<'a, [usize]> {
if std::mem::size_of::<usize>() == 64 {
debug_assert!(slice.iter().all(|&x| x >= 0));
let shape: &[usize] = unsafe { std::mem::transmute(slice) };
Cow::Borrowed(shape)
} else {
let shape: Vec<usize> = slice
.iter()
.map(|&x| usize::try_from(x).unwrap_or_else(|_| panic!("Cannot fit into usize: {}", x)))
.collect();
Cow::Owned(shape)
}
}
impl NDArray {
pub(crate) fn _from_raw(handle: ffi::TVMArrayHandle) -> Self {
let ptr = NDArrayContainer::from_raw(handle);
NDArray(ptr)
}
// I think these should be marked as unsafe functions? projecting a reference is bad news.
pub fn as_dltensor(&self) -> &DLTensor {
&self.dl_tensor
}
pub(crate) fn as_raw_dltensor(&self) -> *mut DLTensor {
unsafe { std::mem::transmute(self.as_dltensor()) }
}
pub fn is_view(&self) -> bool {
false
}
/// Returns the shape of the NDArray.
pub fn shape(&self) -> &[i64] {
let arr = self.as_dltensor();
if arr.shape.is_null() || arr.data.is_null() {
&[]
} else {
unsafe { slice::from_raw_parts(arr.shape, self.ndim()) }
}
}
/// Returns the shape of the NDArray as a &[usize]
///
/// On 64-bit platforms, this is zero-cost and uses the shape from the DLTensor.
/// On other platforms, this copies into a buffer.
pub fn shape_usize(&self) -> Cow<[usize]> {
cow_usize(self.shape())
}
/// Returns the strides of the underlying NDArray.
pub fn strides(&self) -> Option<&[i64]> {
let arr = self.as_dltensor();
if arr.strides.is_null() {
None
} else {
Some(unsafe { slice::from_raw_parts(arr.strides, self.ndim()) })
}
}
/// Returns the strides of the NDArray as a &[usize]
///
/// On 64-bit platforms, this is zero-cost and uses the strides from the DLTensor.
/// On other platforms, this copies into a buffer.
pub fn strides_usize(&self) -> Option<Cow<[usize]>> {
self.strides().map(cow_usize)
}
/// Returns true if the tensor is empty
pub fn is_empty(&self) -> bool {
self.as_dltensor().data.is_null()
}
/// Returns the total number of entries of the NDArray.
pub fn len(&self) -> usize {
let len: i64 = self.shape().iter().product();
usize::try_from(len).unwrap_or_else(|_| panic!("bad len: {}", len))
}
/// Returns the total bytes taken up by the data.
/// This is equal to `nd.len() * nd.dtype().itemsize()`
pub fn size(&self) -> usize {
self.len() * self.dtype().itemsize()
}
/// Returns the device which the NDArray was defined.
pub fn device(&self) -> Device {
self.as_dltensor().device.into()
}
/// Returns the type of the entries of the NDArray.
pub fn dtype(&self) -> DataType {
self.as_dltensor().dtype.into()
}
/// Returns the number of dimensions of the NDArray.
pub fn ndim(&self) -> usize {
self.as_dltensor()
.ndim
.try_into()
.expect("number of dimensions must always be positive")
}
/// Shows whether the underlying ndarray is contiguous in memory or not.
pub fn is_contiguous(&self) -> bool {
match self.strides() {
None => true,
Some(strides) => {
// NDArrayError::MissingShape in case shape is not determined
self.shape()
.iter()
.zip(strides)
.rfold(
(true, 1),
|(is_contig, expected_stride), (shape, stride)| {
(
is_contig && *stride == expected_stride,
expected_stride * shape,
)
},
)
.0
}
}
}
pub fn byte_offset(&self) -> isize {
self.as_dltensor().byte_offset as isize
}
/// Flattens the NDArray to a `Vec` of the same type in cpu.
///
/// ## Example
///
/// ```
/// # use tvm_rt::{Device, DataType, NDArray};
/// # use std::str::FromStr;
/// let mut shape = [4];
/// let mut data = vec![1i32, 2, 3, 4];
/// let dev = Device::cpu(0);
/// let mut ndarray = NDArray::empty(&mut shape, dev, DataType::from_str("int32").unwrap());
/// ndarray.copy_from_buffer(&mut data);
/// assert_eq!(ndarray.shape(), shape);
/// assert_eq!(ndarray.to_vec::<i32>().unwrap(), data);
/// ```
pub fn to_vec<T>(&self) -> Result<Vec<T>, NDArrayError> {
let n = self.size() / size_of::<T>();
let mut vec: Vec<T> = Vec::with_capacity(n);
let ptr = vec.as_mut_ptr();
let slice = unsafe { slice::from_raw_parts_mut(ptr, n) };
self.copy_to_buffer(slice);
unsafe { vec.set_len(n) };
Ok(vec)
}
/// Converts the NDArray to [`ByteArray`].
pub fn to_bytearray(&self) -> Result<ByteArray, NDArrayError> {
let v = self.to_vec::<u8>()?;
Ok(ByteArray::from(v))
}
/// Creates an NDArray from a mutable buffer of types i32, u32 or f32 in cpu.
///
/// ## Example
///
/// ```
/// # use tvm_rt::{Device, DataType, NDArray};
/// # use std::str::FromStr;
/// let shape = &mut [2];
/// let mut data = vec![1f32, 2.0];
/// let dev = Device::cpu(0);
/// let mut ndarray = NDArray::empty(shape, dev, DataType::from_str("int32").unwrap());
/// ndarray.copy_from_buffer(&mut data);
/// ```
///
/// *Note*: if something goes wrong during the copy, it will panic
/// from TVM side. See `TVMArrayCopyFromBytes` in `include/tvm/runtime/c_runtime_api.h`.
pub fn copy_from_buffer<T: Num32>(&mut self, data: &[T]) {
check_call!(ffi::TVMArrayCopyFromBytes(
self.as_raw_dltensor(),
data.as_ptr() as *mut _,
(data.len() * mem::size_of::<T>()) as _,
));
}
pub fn copy_to_buffer<T>(&self, data: &mut [T]) {
assert_eq!(self.size(), data.len() * size_of::<T>());
check_call!(ffi::TVMArrayCopyToBytes(
self.as_raw_dltensor(),
data.as_ptr() as *mut _,
self.size() as _,
));
}
pub fn fill_from_iter<T, I>(&mut self, iter: I)
where
T: Num32,
I: ExactSizeIterator<Item = T>,
{
assert!(self.is_contiguous());
assert_eq!(self.size(), size_of::<T>() * iter.len());
let mut ptr: *mut T = self.as_dltensor().data.cast();
iter.for_each(|x| unsafe {
ptr.write(x);
ptr = ptr.add(1);
})
}
/// Copies the NDArray to another target NDArray.
pub fn copy_to_ndarray(&self, target: NDArray) -> Result<NDArray, NDArrayError> {
if self.dtype() != target.dtype() {
return Err(NDArrayError::DataTypeMismatch {
expected: self.dtype(),
actual: target.dtype(),
});
}
check_call!(ffi::TVMArrayCopyFromTo(
self.as_raw_dltensor(),
target.as_raw_dltensor(),
ptr::null_mut() as ffi::TVMStreamHandle
));
Ok(target)
}
/// Copies the NDArray to a target device.
pub fn copy_to_device(&self, target: &Device) -> Result<NDArray, NDArrayError> {
let tmp = NDArray::empty(self.shape(), *target, self.dtype());
let copy = self.copy_to_ndarray(tmp)?;
Ok(copy)
}
/// Converts a Rust's ndarray to TVM NDArray.
pub fn from_rust_ndarray<T: Num32 + Copy>(
input_nd: &ArrayD<T>,
dev: Device,
dtype: DataType,
) -> Result<Self, NDArrayError> {
let shape: Vec<i64> = input_nd.shape().iter().map(|&x| x as i64).collect();
let mut nd = NDArray::empty(&shape, dev, dtype);
nd.fill_from_iter(input_nd.iter().copied());
Ok(nd)
}
/// Allocates and creates an empty NDArray given the shape, device and dtype.
pub fn empty(shape: &[i64], dev: Device, dtype: DataType) -> NDArray {
let mut handle = ptr::null_mut() as ffi::TVMArrayHandle;
let dtype: tvm_sys::ffi::DLDataType = dtype.into();
check_call!(ffi::TVMArrayAlloc(
shape.as_ptr(),
shape.len() as c_int,
i32::from(dtype.code) as c_int,
i32::from(dtype.bits) as c_int,
i32::from(dtype.lanes) as c_int,
dev.device_type as c_int,
dev.device_id as c_int,
&mut handle as *mut _,
));
let ptr = NDArrayContainer::from_raw(handle)
.map(|o| o.downcast().expect("this should never fail"));
NDArray(ptr)
}
pub fn zeroed(self) -> NDArray {
unsafe {
let dltensor = self.as_raw_dltensor();
let bytes_ptr: *mut u8 = std::mem::transmute((*dltensor).data);
println!("size {}", self.size());
std::ptr::write_bytes(bytes_ptr, 0, self.size());
self
}
}
}
macro_rules! impl_from_ndarray_rustndarray {
($type:ty, $type_name:tt) => {
impl<'a> TryFrom<&'a NDArray> for ArrayD<$type> {
type Error = NDArrayError;
fn try_from(nd: &NDArray) -> Result<ArrayD<$type>, Self::Error> {
assert_eq!(nd.dtype(), DataType::from_str($type_name)?, "Type mismatch");
Ok(Array::from_shape_vec(
&*nd.shape_usize(),
nd.to_vec::<$type>()?,
)?)
}
}
impl<'a> TryFrom<&'a mut NDArray> for ArrayD<$type> {
type Error = NDArrayError;
fn try_from(nd: &mut NDArray) -> Result<ArrayD<$type>, Self::Error> {
assert_eq!(nd.dtype(), DataType::from_str($type_name)?, "Type mismatch");
Ok(Array::from_shape_vec(
&*nd.shape_usize(),
nd.to_vec::<$type>()?,
)?)
}
}
};
}
impl_from_ndarray_rustndarray!(i32, "int");
impl_from_ndarray_rustndarray!(u32, "uint");
impl_from_ndarray_rustndarray!(f32, "float");
mod sealed {
/// Private trait to prevent other traits from being implemeneted in downstream crates.
pub trait Sealed {}
}
/// A trait for the supported 32-bits numerical types in frontend.
pub trait Num32: Num + sealed::Sealed {
const BITS: u8 = 32;
}
macro_rules! impl_num32 {
($($type:ty),+) => {
$(
impl sealed::Sealed for $type {}
impl Num32 for $type {}
)+
};
}
impl_num32!(i32, u32, f32);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basics() {
let shape = &[1, 2, 3];
let dev = Device::cpu(0);
println!("before empty");
let ndarray = NDArray::empty(shape, dev, DataType::from_str("int32").unwrap());
println!("after empty");
assert_eq!(ndarray.shape(), shape);
assert_eq!(ndarray.len(), shape.iter().product::<i64>() as usize);
assert_eq!(ndarray.ndim(), 3);
assert!(ndarray.strides().is_none());
assert_eq!(ndarray.byte_offset(), 0);
}
#[test]
fn copy() {
let shape = &[4];
let data = vec![1i32, 2, 3, 4];
let dev = Device::cpu(0);
let mut ndarray = NDArray::empty(shape, dev, DataType::int(32, 1)).zeroed();
assert_eq!(ndarray.to_vec::<i32>().unwrap(), vec![0, 0, 0, 0]);
ndarray.copy_from_buffer(&data);
assert_eq!(ndarray.shape(), shape);
assert_eq!(ndarray.to_vec::<i32>().unwrap(), data);
assert_eq!(ndarray.ndim(), 1);
assert!(ndarray.is_contiguous());
assert_eq!(ndarray.byte_offset(), 0);
let shape = vec![4];
let e = NDArray::empty(&shape, Device::cpu(0), DataType::from_str("int32").unwrap());
let nd = ndarray.copy_to_ndarray(e);
assert!(nd.is_ok());
assert_eq!(nd.unwrap().to_vec::<i32>().unwrap(), data);
}
/// This occasionally panics on macOS: https://github.com/rust-lang/rust/issues/71397
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err`")]
fn copy_wrong_dtype() {
let shape = vec![4];
let mut data = vec![1f32, 2., 3., 4.];
let dev = Device::cpu(0);
let mut nd_float = NDArray::empty(&shape, dev, DataType::from_str("float32").unwrap());
nd_float.copy_from_buffer(&mut data);
let empty_int = NDArray::empty(&shape, dev, DataType::from_str("int32").unwrap());
nd_float.copy_to_ndarray(empty_int).unwrap();
}
#[test]
fn rust_ndarray() {
let a = Array::from_shape_vec((2, 2), vec![1f32, 2., 3., 4.])
.unwrap()
.into_dyn();
let nd =
NDArray::from_rust_ndarray(&a, Device::cpu(0), DataType::from_str("float32").unwrap())
.unwrap();
assert_eq!(nd.shape(), &[2, 2]);
let rnd: ArrayD<f32> = ArrayD::try_from(&nd).unwrap();
assert!(rnd.all_close(&a, 1e-8f32));
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/object/mod.rs | /*
* 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.
*/
use std::convert::TryFrom;
use std::ffi::CString;
use crate::errors::Error;
use crate::external;
use tvm_sys::{ArgValue, RetValue};
mod object_ptr;
pub use object_ptr::{IsObject, Object, ObjectPtr, ObjectRef};
pub trait AsArgValue<'a> {
fn as_arg_value(&'a self) -> ArgValue<'a>;
}
impl<'a, T: 'static> AsArgValue<'a> for T
where
&'a T: Into<ArgValue<'a>>,
{
fn as_arg_value(&'a self) -> ArgValue<'a> {
self.into()
}
}
// TODO we would prefer to blanket impl From/TryFrom ArgValue/RetValue, but we
// can't because of coherence rules. Instead, we generate them in the macro, and
// add what we can (including Into instead of From) as subtraits.
// We also add named conversions for clarity
pub trait IsObjectRef:
Sized
+ Clone
+ Into<RetValue>
+ for<'a> AsArgValue<'a>
+ TryFrom<RetValue, Error = Error>
+ for<'a> TryFrom<ArgValue<'a>, Error = Error>
+ std::fmt::Debug
{
type Object: IsObject;
fn as_ptr(&self) -> Option<&ObjectPtr<Self::Object>>;
fn into_ptr(self) -> Option<ObjectPtr<Self::Object>>;
fn from_ptr(object_ptr: Option<ObjectPtr<Self::Object>>) -> Self;
fn null() -> Self {
Self::from_ptr(None)
}
fn into_arg_value<'a>(&'a self) -> ArgValue<'a> {
self.as_arg_value()
}
fn from_arg_value<'a>(arg_value: ArgValue<'a>) -> Result<Self, Error> {
Self::try_from(arg_value)
}
fn into_ret_value<'a>(self) -> RetValue {
self.into()
}
fn from_ret_value<'a>(ret_value: RetValue) -> Result<Self, Error> {
Self::try_from(ret_value)
}
fn upcast<U>(self) -> U
where
U: IsObjectRef,
Self::Object: AsRef<U::Object>,
{
let ptr = self.into_ptr().map(ObjectPtr::upcast);
U::from_ptr(ptr)
}
fn downcast<U>(self) -> Result<U, Error>
where
U: IsObjectRef,
U::Object: AsRef<Self::Object>,
{
let ptr = self.into_ptr().map(ObjectPtr::downcast);
let ptr = ptr.transpose()?;
Ok(U::from_ptr(ptr))
}
}
external! {
#[name("ir.DebugPrint")]
pub fn debug_print(object: ObjectRef) -> CString;
#[name("node.StructuralHash")]
fn structural_hash(object: ObjectRef, map_free_vars: bool) -> i64;
#[name("node.StructuralEqual")]
fn structural_equal(lhs: ObjectRef, rhs: ObjectRef, assert_mode: bool, map_free_vars: bool) -> bool;
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/object/object_ptr.rs | /*
* 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.
*/
use std::convert::TryFrom;
use std::ffi::CString;
use std::fmt;
use std::os::raw::c_char;
use std::ptr::NonNull;
use std::sync::atomic::AtomicI32;
use tvm_macros::Object;
use tvm_sys::ffi::{
self, TVMObjectFree, TVMObjectRetain, TVMObjectTypeIndex2Key, TVMObjectTypeKey2Index,
};
use tvm_sys::{ArgValue, RetValue};
use crate::errors::Error;
type Deleter = unsafe extern "C" fn(object: *mut Object) -> ();
/// A TVM intrusive smart pointer header, in TVM all FFI compatible types
/// start with an Object as their first field. The base object tracks
/// a type_index which is an index into the runtime type information
/// table, an atomic reference count, and a customized deleter which
/// will be invoked when the reference count is zero.
///
#[derive(Debug, Object)]
#[ref_name = "ObjectRef"]
#[type_key = "runtime.Object"]
#[repr(C)]
pub struct Object {
/// The index into TVM's runtime type information table.
pub(self) type_index: u32,
// TODO(@jroesch): pretty sure Rust and C++ atomics are the same, but not sure.
// NB: in general we should not touch this in Rust.
/// The reference count of the smart pointer.
pub(self) ref_count: AtomicI32,
/// The deleter function which is used to deallocate the underlying data
/// when the reference count is zero. This field must always be set for
/// all objects.
///
/// The common use case is ensuring that the allocator which allocated the
/// data is also the one that deletes it.
pub(self) fdeleter: Deleter,
}
/// The default deleter for objects allocated in Rust, we use a bit of
/// trait magic here to get a monomorphized deleter for each object
/// "subtype".
///
/// This function just converts the pointer to the correct type
/// and reconstructs a Box which then is dropped to deallocate
/// the underlying allocation.
unsafe extern "C" fn delete<T: IsObject>(object: *mut Object) {
let typed_object: *mut T = object as *mut T;
let boxed: Box<T> = Box::from_raw(typed_object);
drop(boxed);
}
fn derived_from(child_type_index: u32, parent_type_index: u32) -> bool {
let mut is_derived = 0;
crate::check_call!(ffi::TVMObjectDerivedFrom(
child_type_index,
parent_type_index,
&mut is_derived
));
if is_derived == 0 {
false
} else {
true
}
}
impl Object {
fn new(type_index: u32, deleter: Deleter) -> Object {
Object {
type_index,
// NB(@jroesch): I believe it is sound to use Rust atomics
// in conjunction with C++ atomics given the memory model
// is nearly identical.
//
// Of course these are famous last words which I may later
// regret.
ref_count: AtomicI32::new(0),
fdeleter: deleter,
}
}
fn get_type_key(&self) -> String {
let mut cstring: *mut c_char = std::ptr::null_mut();
unsafe {
if TVMObjectTypeIndex2Key(self.type_index, &mut cstring as *mut _) != 0 {
panic!("{}", crate::get_last_error());
}
return CString::from_raw(cstring)
.into_string()
.expect("type keys should be valid utf-8");
}
}
fn get_type_index<T: IsObject>() -> u32 {
let type_key = T::TYPE_KEY;
let cstring = CString::new(type_key).expect("type key must not contain null characters");
// TODO(@jroesch): look into TVMObjectTypeKey2Index.
if type_key == "runtime.Object" {
return 0;
} else {
let mut index = 0;
unsafe {
if TVMObjectTypeKey2Index(cstring.as_ptr(), &mut index) != 0 {
panic!("{}", crate::get_last_error())
}
}
return index;
}
}
pub fn count(&self) -> i32 {
// need to do atomic read in C++
// ABI compatible atomics is funky/hard.
self.ref_count.load(std::sync::atomic::Ordering::Relaxed)
}
/// Allocates a base object value for an object subtype of type T.
/// By using associated constants and generics we can provide a
/// type indexed abstraction over allocating objects with the
/// correct index and deleter.
pub fn base<T: IsObject>() -> Object {
let index = Object::get_type_index::<T>();
Object::new(index, delete::<T>)
}
/// Increases the object's reference count by one.
pub(self) fn inc_ref(&self) {
let raw_ptr = self as *const Object as *mut Object as *mut std::ffi::c_void;
unsafe {
assert_eq!(TVMObjectRetain(raw_ptr), 0);
}
}
/// Decreases the object's reference count by one.
pub(self) fn dec_ref(&self) {
let raw_ptr = self as *const Object as *mut Object as *mut std::ffi::c_void;
unsafe {
assert_eq!(TVMObjectFree(raw_ptr), 0);
}
}
}
/// An unsafe trait which should be implemented for an object
/// subtype.
///
/// The trait contains the type key needed to compute the type
/// index, a method for accessing the base object given the
/// subtype, and a typed delete method which is specialized
/// to the subtype.
pub unsafe trait IsObject: AsRef<Object> + std::fmt::Debug {
const TYPE_KEY: &'static str;
}
/// A smart pointer for types which implement IsObject.
/// This type directly corresponds to TVM's C++ type ObjectPtr<T>.
///
/// See object.h for more details.
#[repr(C)]
pub struct ObjectPtr<T: IsObject> {
pub ptr: NonNull<T>,
}
impl ObjectPtr<Object> {
pub fn from_raw(object_ptr: *mut Object) -> Option<ObjectPtr<Object>> {
let non_null = NonNull::new(object_ptr);
non_null.map(|ptr| {
debug_assert!(unsafe { ptr.as_ref().count() } >= 0);
ObjectPtr { ptr }
})
}
}
impl<T: IsObject> Clone for ObjectPtr<T> {
fn clone(&self) -> Self {
unsafe { self.ptr.as_ref().as_ref().inc_ref() }
ObjectPtr { ptr: self.ptr }
}
}
impl<T: IsObject> Drop for ObjectPtr<T> {
fn drop(&mut self) {
unsafe { self.ptr.as_ref().as_ref().dec_ref() }
}
}
impl<T: IsObject> ObjectPtr<T> {
pub fn leak<'a>(object_ptr: ObjectPtr<T>) -> &'a mut T
where
T: 'a,
{
unsafe { &mut *std::mem::ManuallyDrop::new(object_ptr).ptr.as_ptr() }
}
pub fn new(object: T) -> ObjectPtr<T> {
object.as_ref().inc_ref();
let object_ptr = Box::new(object);
let object_ptr = Box::leak(object_ptr);
let ptr = NonNull::from(object_ptr);
ObjectPtr { ptr }
}
pub fn count(&self) -> i32 {
// need to do atomic read in C++
// ABI compatible atomics is funky/hard.
self.as_ref()
.ref_count
.load(std::sync::atomic::Ordering::Relaxed)
}
/// This method avoid running the destructor on self once it's dropped, so we don't accidentally release the memory
unsafe fn cast<U: IsObject>(self) -> ObjectPtr<U> {
let ptr = self.ptr.cast();
std::mem::forget(self);
ObjectPtr { ptr }
}
pub fn upcast<U>(self) -> ObjectPtr<U>
where
U: IsObject,
T: AsRef<U>,
{
unsafe { self.cast() }
}
pub fn downcast<U>(self) -> Result<ObjectPtr<U>, Error>
where
U: IsObject + AsRef<T>,
{
let child_index = Object::get_type_index::<U>();
let object_index = self.as_ref().type_index;
let is_derived = if child_index == object_index {
true
} else {
// TODO(@jroesch): write tests
derived_from(object_index, child_index)
};
if is_derived {
Ok(unsafe { self.cast() })
} else {
let type_key = self.as_ref().get_type_key();
Err(Error::downcast(type_key.into(), U::TYPE_KEY))
}
}
pub unsafe fn into_raw(self) -> *mut T {
self.ptr.as_ptr()
}
pub unsafe fn as_ptr(&self) -> *mut T {
self.ptr.as_ptr()
}
}
impl<T: IsObject> std::ops::Deref for ObjectPtr<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { self.ptr.as_ref() }
}
}
impl<T: IsObject> fmt::Debug for ObjectPtr<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use std::ops::Deref;
write!(f, "{:?}", self.deref())
}
}
impl<'a, T: IsObject> From<ObjectPtr<T>> for RetValue {
fn from(object_ptr: ObjectPtr<T>) -> RetValue {
let raw_object_ptr = ObjectPtr::leak(object_ptr) as *mut T as *mut std::ffi::c_void;
assert!(!raw_object_ptr.is_null());
RetValue::ObjectHandle(raw_object_ptr)
}
}
impl<'a, T: IsObject> TryFrom<RetValue> for ObjectPtr<T> {
type Error = Error;
fn try_from(ret_value: RetValue) -> Result<ObjectPtr<T>, Self::Error> {
use crate::ffi::DLTensor;
use crate::ndarray::NDArrayContainer;
match ret_value {
RetValue::ObjectHandle(handle) | RetValue::ModuleHandle(handle) => {
let optr = ObjectPtr::from_raw(handle as *mut Object).ok_or(Error::Null)?;
debug_assert!(optr.count() >= 1);
optr.downcast()
}
RetValue::NDArrayHandle(handle) => {
let optr: ObjectPtr<NDArrayContainer> =
NDArrayContainer::from_raw(handle as *mut DLTensor).ok_or(Error::Null)?;
debug_assert!(optr.count() >= 1);
optr.upcast::<Object>().downcast()
}
_ => Err(Error::downcast(format!("{:?}", ret_value), T::TYPE_KEY)),
}
}
}
impl<'a, T: IsObject> From<&'a ObjectPtr<T>> for ArgValue<'a> {
fn from(object_ptr: &'a ObjectPtr<T>) -> ArgValue<'a> {
debug_assert!(object_ptr.count() >= 1);
let object_ptr = object_ptr.clone().upcast::<Object>();
match T::TYPE_KEY {
"runtime.NDArray" => {
use crate::ndarray::NDArrayContainer;
let dcast_ptr = object_ptr.downcast().unwrap();
let raw_ptr = NDArrayContainer::as_mut_ptr(&dcast_ptr) as *mut std::ffi::c_void;
assert!(!raw_ptr.is_null());
ArgValue::NDArrayHandle(raw_ptr)
}
"runtime.Module" => {
let raw_ptr = unsafe { object_ptr.as_ptr() } as *mut std::ffi::c_void;
assert!(!raw_ptr.is_null());
ArgValue::ModuleHandle(raw_ptr)
}
_ => {
let raw_ptr = unsafe { object_ptr.as_ptr() } as *mut std::ffi::c_void;
assert!(!raw_ptr.is_null());
ArgValue::ObjectHandle(raw_ptr)
}
}
}
}
impl<'a, T: IsObject> TryFrom<ArgValue<'a>> for ObjectPtr<T> {
type Error = Error;
fn try_from(arg_value: ArgValue<'a>) -> Result<ObjectPtr<T>, Self::Error> {
use crate::ffi::DLTensor;
use crate::ndarray::NDArrayContainer;
match arg_value {
ArgValue::ObjectHandle(handle) | ArgValue::ModuleHandle(handle) => {
let optr = ObjectPtr::from_raw(handle as *mut Object).ok_or(Error::Null)?;
optr.inc_ref();
// We are building an owned, ref-counted view into the underlying ArgValue, in order to be safe we must
// bump the reference count by one.
assert!(optr.count() >= 1);
optr.downcast()
}
ArgValue::NDArrayHandle(handle) => {
let optr =
NDArrayContainer::from_raw(handle as *mut DLTensor).ok_or(Error::Null)?;
// We are building an owned, ref-counted view into the underlying ArgValue, in order to be safe we must
// bump the reference count by one.
assert!(optr.count() >= 1);
// TODO(@jroesch): figure out if there is a more optimal way to do this
let object = optr.upcast::<Object>();
object.inc_ref();
object.downcast()
}
_ => Err(Error::downcast(format!("{:?}", arg_value), "ObjectHandle")),
}
}
}
impl<T: IsObject> std::hash::Hash for ObjectPtr<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
state.write_i64(
super::structural_hash(ObjectRef(Some(self.clone().upcast())), false).unwrap(),
)
}
}
impl<T: IsObject> PartialEq for ObjectPtr<T> {
fn eq(&self, other: &Self) -> bool {
let lhs = ObjectRef(Some(self.clone().upcast()));
let rhs = ObjectRef(Some(other.clone().upcast()));
super::structural_equal(lhs, rhs, false, false).unwrap()
}
}
impl<T: IsObject> Eq for ObjectPtr<T> {}
#[cfg(test)]
mod tests {
use super::{Object, ObjectPtr};
use anyhow::{ensure, Result};
use std::convert::TryInto;
use tvm_sys::{ArgValue, RetValue};
#[test]
fn test_new_object() -> anyhow::Result<()> {
let object = Object::base::<Object>();
let ptr = ObjectPtr::new(object);
assert_eq!(ptr.count(), 1);
Ok(())
}
#[test]
fn test_leak() -> anyhow::Result<()> {
let ptr = ObjectPtr::new(Object::base::<Object>());
assert_eq!(ptr.count(), 1);
let object = ObjectPtr::leak(ptr);
assert_eq!(object.count(), 1);
Ok(())
}
#[test]
fn test_clone() -> anyhow::Result<()> {
let ptr = ObjectPtr::new(Object::base::<Object>());
assert_eq!(ptr.count(), 1);
let ptr2 = ptr.clone();
assert_eq!(ptr2.count(), 2);
drop(ptr);
assert_eq!(ptr2.count(), 1);
Ok(())
}
#[test]
fn roundtrip_retvalue() -> Result<()> {
let ptr = ObjectPtr::new(Object::base::<Object>());
assert_eq!(ptr.count(), 1);
let ret_value: RetValue = ptr.clone().into();
let ptr2: ObjectPtr<Object> = ret_value.try_into()?;
assert_eq!(ptr.count(), ptr2.count());
assert_eq!(ptr.count(), 2);
ensure!(
ptr.type_index == ptr2.type_index,
"type indices do not match"
);
ensure!(
ptr.fdeleter == ptr2.fdeleter,
"objects have different deleters"
);
// After dropping the second pointer we should only see only refcount.
drop(ptr2);
assert_eq!(ptr.count(), 1);
Ok(())
}
#[test]
fn roundtrip_argvalue() -> Result<()> {
let ptr = ObjectPtr::new(Object::base::<Object>());
assert_eq!(ptr.count(), 1);
let ptr_clone = ptr.clone();
assert_eq!(ptr.count(), 2);
let arg_value: ArgValue = (&ptr_clone).into();
assert_eq!(ptr.count(), 2);
let ptr2: ObjectPtr<Object> = arg_value.try_into()?;
assert_eq!(ptr2.count(), 3);
assert_eq!(ptr.count(), ptr2.count());
drop(ptr_clone);
assert_eq!(ptr.count(), 2);
ensure!(
ptr.type_index == ptr2.type_index,
"type indices do not match"
);
ensure!(
ptr.fdeleter == ptr2.fdeleter,
"objects have different deleters"
);
// After dropping the second pointer we should only see only refcount.
drop(ptr2);
assert_eq!(ptr.count(), 1);
Ok(())
}
fn test_fn_raw<'a>(
mut args: crate::to_function::ArgList<'a>,
) -> crate::function::Result<RetValue> {
let v: ArgValue = args.remove(0);
let v2: ArgValue = args.remove(0);
// assert_eq!(o.count(), 2);
let o: ObjectPtr<Object> = v.try_into().unwrap();
assert_eq!(o.count(), 2);
let o2: ObjectPtr<Object> = v2.try_into().unwrap();
assert_eq!(o2.count(), 3);
drop(o2);
assert_eq!(o.count(), 2);
Ok(o.into())
}
#[test]
fn test_ref_count_raw_fn() {
use super::*;
use crate::function::{register_untyped, Function};
let ptr = ObjectPtr::new(Object::base::<Object>());
// Call the function without the wrapping for TVM.
assert_eq!(ptr.count(), 1);
let same = test_fn_raw(vec![(&ptr).into(), (&ptr).into()]).unwrap();
let output: ObjectPtr<Object> = same.try_into().unwrap();
assert_eq!(output.count(), 2);
drop(output);
assert_eq!(ptr.count(), 1);
register_untyped(test_fn_raw, "test_fn_raw", true).unwrap();
let raw_func = Function::get("test_fn_raw").unwrap();
let output = raw_func.invoke(vec![(&ptr).into(), (&ptr).into()]).unwrap();
let output: ObjectPtr<Object> = output.try_into().unwrap();
assert_eq!(output.count(), 2);
drop(output);
assert_eq!(ptr.count(), 1);
}
fn test_fn_typed(o: ObjectPtr<Object>, o2: ObjectPtr<Object>) -> ObjectPtr<Object> {
assert_eq!(o.count(), 3);
assert_eq!(o2.count(), 3);
drop(o2);
assert_eq!(o.count(), 2);
return o;
}
#[test]
fn test_ref_count_typed() {
use super::*;
use crate::function::{register, Function};
let ptr = ObjectPtr::new(Object::base::<Object>());
// Call the function without the wrapping for TVM.
assert_eq!(ptr.count(), 1);
let output = test_fn_typed(ptr.clone(), ptr.clone());
assert_eq!(output.count(), 2);
drop(output);
assert_eq!(ptr.count(), 1);
register(test_fn_typed, "test_fn_typed").unwrap();
let typed_func = Function::get("test_fn_typed").unwrap();
let output = typed_func
.invoke(vec![(&ptr).into(), (&ptr).into()])
.unwrap();
let output: ObjectPtr<Object> = output.try_into().unwrap();
assert_eq!(output.count(), 2);
drop(output);
assert_eq!(ptr.count(), 1);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/string.rs | /*
* 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.
*/
use std::cmp::{Ordering, PartialEq};
use std::hash::{Hash, Hasher};
use super::Object;
use tvm_macros::Object;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "String"]
#[type_key = "runtime.String"]
#[no_derive]
pub struct StringObj {
base: Object,
data: *const u8,
size: u64,
}
impl From<std::string::String> for String {
fn from(s: std::string::String) -> Self {
let size = s.len() as u64;
let data = Box::into_raw(s.into_boxed_str()).cast();
let base = Object::base::<StringObj>();
StringObj { base, data, size }.into()
}
}
impl From<&'static str> for String {
fn from(s: &'static str) -> Self {
let size = s.len() as u64;
let data = s.as_bytes().as_ptr();
let base = Object::base::<StringObj>();
StringObj { base, data, size }.into()
}
}
impl AsRef<[u8]> for String {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl std::fmt::Display for String {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_string_lossy().fmt(f)
}
}
impl String {
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size as usize
}
pub fn as_bytes(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.data, self.len()) }
}
pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
std::str::from_utf8(self.as_bytes())
}
pub fn to_string_lossy(&self) -> std::borrow::Cow<str> {
std::string::String::from_utf8_lossy(self.as_bytes())
}
}
impl<T: AsRef<[u8]>> PartialEq<T> for String {
fn eq(&self, other: &T) -> bool {
self.as_bytes() == other.as_ref()
}
}
impl<T: AsRef<[u8]>> PartialOrd<T> for String {
fn partial_cmp(&self, other: &T) -> Option<Ordering> {
self.as_bytes().partial_cmp(other.as_ref())
}
}
impl Eq for String {}
impl Ord for String {
fn cmp(&self, other: &Self) -> Ordering {
self.as_bytes().cmp(other.as_bytes())
}
}
impl Hash for String {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}
impl std::fmt::Debug for String {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_fmt(format_args!("{:?}", self.to_string_lossy()))
}
}
#[cfg(test)]
mod tests {
use super::String;
use crate::object::debug_print;
use crate::IsObjectRef;
use anyhow::{ensure, Result};
#[test]
fn test_string_debug() -> Result<()> {
let s = String::from("foo");
let object_ref = s.upcast();
println!("about to call");
let string = debug_print(object_ref)?;
println!("after call");
ensure!(
string.into_string().expect("is cstring").contains("foo"),
"string content is invalid"
);
Ok(())
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-rt/src/to_function.rs | /*
* 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.
*/
//! This module provides an idiomatic Rust API for creating and working with TVM functions.
//!
//! For calling an already registered TVM function use [`function::Builder`]
//! To register a TVM packed function from Rust side either
//! use [`function::register`] or the macro [`register_global_func`].
//!
//! See the tests and examples repository for more examples.
use std::convert::{TryFrom, TryInto};
use std::{
os::raw::{c_int, c_void},
ptr, slice,
};
use super::{function::Result, Function};
use crate::errors::Error;
pub use tvm_sys::{ffi, ArgValue, RetValue};
/// A trait representing whether the function arguments
/// and return type can be assigned to a TVM packed function.
///
/// By splitting the conversion to function into two traits
/// we are able to improve error reporting, by splitting the
/// conversion of inputs and outputs to this trait.
///
/// And the implementation of it to `ToFunction`.
pub type ArgList<'a> = Vec<ArgValue<'a>>;
pub enum Args<'a, I> {
Typed(I),
Raw(ArgList<'a>),
}
pub trait Typed<I, O> {
fn args<'arg>(i: Vec<ArgValue<'arg>>) -> Result<Args<'arg, I>>;
fn ret(o: O) -> Result<RetValue>;
}
pub trait ToFunction<I, O>: Sized {
type Handle;
fn into_raw(self) -> *mut Self::Handle;
fn call<'a>(handle: *mut Self::Handle, args: Vec<ArgValue<'a>>) -> Result<RetValue>
where
Self: Typed<I, O>;
fn drop(handle: *mut Self::Handle);
fn to_function(self) -> Function
where
Self: Typed<I, O>,
{
let mut fhandle = ptr::null_mut() as ffi::TVMFunctionHandle;
let resource_handle = self.into_raw();
check_call!(ffi::TVMFuncCreateFromCFunc(
Some(Self::tvm_callback),
resource_handle as *mut _,
Some(Self::tvm_finalizer),
&mut fhandle as *mut ffi::TVMFunctionHandle,
));
Function::from_raw(fhandle)
}
/// The callback function which is wrapped converted by TVM
/// into a packed function stored in fhandle.
unsafe extern "C" fn tvm_callback(
args: *mut ffi::TVMValue,
type_codes: *mut c_int,
num_args: c_int,
ret: ffi::TVMRetValueHandle,
resource_handle: *mut c_void,
) -> c_int
where
Self: Typed<I, O>,
{
#![allow(unused_assignments, unused_unsafe)]
let result = std::panic::catch_unwind(|| {
// turning off the incorrect linter complaints
let len = num_args as usize;
let args_list = slice::from_raw_parts_mut(args, len);
let type_codes_list = slice::from_raw_parts_mut(type_codes, len);
let mut local_args: Vec<ArgValue> = Vec::new();
let mut value = ffi::TVMValue { v_int64: 0 };
let mut tcode = 0;
let resource_handle = resource_handle as *mut Self::Handle;
for i in 0..len {
value = args_list[i];
tcode = type_codes_list[i];
// TODO(@jroesch): I believe it is sound to disable this specialized move rule.
//
// This is used in C++ to deal with moving an RValue or reference to a return value
// directly so you can skip copying.
//
// I believe this is not needed as the move directly occurs into the Rust function.
// if tcode == ffi::TVMArgTypeCode_kTVMObjectHandle as c_int
// || tcode == ffi::TVMArgTypeCode_kTVMObjectRValueRefArg as c_int
// || tcode == ffi::TVMArgTypeCode_kTVMPackedFuncHandle as c_int
// || tcode == ffi::TVMArgTypeCode_kTVMModuleHandle as c_int
// || tcode == ffi::TVMArgTypeCode_kTVMNDArrayHandle as c_int
// {
// check_call!(ffi::TVMCbArgToReturn(
// &mut value as *mut _,
// &mut tcode as *mut _
// ));
// }
let arg_value = ArgValue::from_tvm_value(value, tcode as u32);
local_args.push(arg_value);
}
let rv = match Self::call(resource_handle, local_args) {
Ok(v) => v,
Err(msg) => {
return Err(msg);
}
};
// TODO(@jroesch): clean up the handling of the is dec_ref
match rv.clone().try_into() as Result<crate::object::ObjectPtr<crate::object::Object>> {
Err(_) => {}
Ok(v) => drop(v),
};
let (mut ret_val, ret_tcode) = rv.to_tvm_value();
let mut ret_type_code = ret_tcode as c_int;
check_call!(ffi::TVMCFuncSetReturn(
ret,
&mut ret_val as *mut _,
&mut ret_type_code as *mut _,
1 as c_int
));
Ok(())
});
// Here we handle either a panic or true error to isolate
// the unwinding as it will cause issues if we allow Rust
// to unwind over C++ boundary without care.
match result {
Err(_) => {
// TODO(@jroesch): figure out how to improve error here.
crate::set_last_error(&Error::Panic);
return -1;
}
Ok(inner_res) => match inner_res {
Err(err) => {
crate::set_last_error(&err);
return -1;
}
Ok(()) => return 0,
},
}
}
/// The finalizer which is invoked when the packed function's
/// reference count is zero.
unsafe extern "C" fn tvm_finalizer(fhandle: *mut c_void) {
let handle = std::mem::transmute(fhandle);
Self::drop(handle)
}
}
pub struct RawArgs;
impl Typed<RawArgs, RetValue> for for<'a> fn(Vec<ArgValue<'a>>) -> Result<RetValue> {
fn args<'arg>(args: Vec<ArgValue<'arg>>) -> Result<Args<'arg, RawArgs>> {
Ok(Args::Raw(args))
}
fn ret(o: RetValue) -> Result<RetValue> {
Ok(o)
}
}
impl ToFunction<RawArgs, RetValue> for for<'arg> fn(Vec<ArgValue<'arg>>) -> Result<RetValue> {
type Handle = for<'arg> fn(Vec<ArgValue<'arg>>) -> Result<RetValue>;
fn into_raw(self) -> *mut Self::Handle {
let ptr: Box<Self::Handle> = Box::new(self);
Box::into_raw(ptr)
}
fn call<'arg>(handle: *mut Self::Handle, args: Vec<ArgValue<'arg>>) -> Result<RetValue> {
unsafe {
let func = *handle;
func(args)
}
}
fn drop(_: *mut Self::Handle) {}
}
/// A helper trait which correctly captures the complex conversion and lifetime semantics needed
/// to coerce an ordinary Rust value into `ArgValue`.
pub trait TryFromArgValue<F>: TryFrom<F> {
fn from_arg_value(f: F) -> std::result::Result<Self, Error>;
}
impl<'a, T> TryFromArgValue<ArgValue<'a>> for T
where
Self: TryFrom<ArgValue<'a>>,
Error: From<<Self as TryFrom<ArgValue<'a>>>::Error>,
{
fn from_arg_value(f: ArgValue<'a>) -> std::result::Result<T, Error> {
Ok(TryFrom::try_from(f)?)
}
}
macro_rules! impl_typed_and_to_function {
($len:literal; $($t:ident),*) => {
impl<Fun, Out, $($t),*> Typed<($($t,)*), Out> for Fun
where
Fun: Fn($($t),*) -> Out,
Out: TryInto<RetValue>,
Error: From<Out::Error>,
$( for<'a> $t: TryFromArgValue<ArgValue<'a>>, )*
{
#[allow(non_snake_case, unused_variables, unused_mut)]
fn args<'arg>(args: Vec<ArgValue<'arg>>) -> Result<Args<'arg, ($($t,)*)>> {
if args.len() != $len {
return Err(Error::CallFailed(format!("{} expected {} arguments, got {}.\n",
std::any::type_name::<Self>(),
$len, args.len())))
}
let mut args = args.into_iter();
$(let $t = TryFromArgValue::from_arg_value(args.next().unwrap())?;)*
Ok(Args::Typed(($($t,)*)))
}
fn ret(out: Out) -> Result<RetValue> {
out.try_into().map_err(|e| e.into())
}
}
impl<Fun, $($t,)* Out> ToFunction<($($t,)*), Out> for Fun
where
Fun: Fn($($t,)*) -> Out + 'static
{
type Handle = Box<dyn Fn($($t,)*) -> Out + 'static>;
fn into_raw(self) -> *mut Self::Handle {
let ptr: Box<Self::Handle> = Box::new(Box::new(self));
Box::into_raw(ptr)
}
#[allow(non_snake_case)]
fn call<'a>(handle: *mut Self::Handle, args: Vec<ArgValue<'a>>) -> Result<RetValue>
where
Fun: Typed<($($t,)*), Out>
{
let ($($t,)*) = match Fun::args(args)? {
Args::Raw(_) => panic!("impossible case"),
Args::Typed(typed) => typed,
};
let fn_ptr = unsafe { &*handle };
let out = fn_ptr($($t),*);
Fun::ret(out)
}
fn drop(ptr: *mut Self::Handle) {
let bx = unsafe { Box::from_raw(ptr) };
std::mem::drop(bx)
}
}
}
}
impl_typed_and_to_function!(0;);
impl_typed_and_to_function!(1; A);
impl_typed_and_to_function!(2; A, B);
impl_typed_and_to_function!(3; A, B, C);
impl_typed_and_to_function!(4; A, B, C, D);
impl_typed_and_to_function!(5; A, B, C, D, E);
impl_typed_and_to_function!(6; A, B, C, D, E, F);
impl_typed_and_to_function!(7; A, B, C, D, E, F, G);
impl_typed_and_to_function!(8; A, B, C, D, E, F, G, H);
#[cfg(test)]
mod tests {
use super::*;
fn call<'a, F, I, O>(f: F, args: Vec<ArgValue<'a>>) -> Result<RetValue>
where
F: ToFunction<I, O>,
F: Typed<I, O>,
{
F::call(f.into_raw(), args)
}
#[test]
fn test_to_function0() {
fn zero() -> i32 {
10
}
let _ = zero.to_function();
let good = call(zero, vec![]).unwrap();
assert_eq!(i32::try_from(good).unwrap(), 10);
let bad = call(zero, vec![1.into()]).unwrap_err();
assert!(matches!(bad, Error::CallFailed(..)));
}
#[test]
fn test_to_function2() {
fn two_arg(i: i32, j: i32) -> i32 {
i + j
}
let good = call(two_arg, vec![3.into(), 4.into()]).unwrap();
assert_eq!(i32::try_from(good).unwrap(), 7);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/build.rs | /*
* 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.
*/
extern crate bindgen;
use std::{
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::{Context, Result};
use tvm_build::{BuildConfig, CMakeSetting};
/// The necessary information for detecting a TVM installation.
struct TVMInstall {
source_path: PathBuf,
build_path: PathBuf,
}
/// Find the TVM install using the provided path.
fn find_using_tvm_path<P: AsRef<Path>>(tvm_path: P) -> Result<TVMInstall> {
Ok(TVMInstall {
source_path: tvm_path.as_ref().into(),
build_path: tvm_path.as_ref().into(),
})
}
#[allow(unused)]
fn if_unset<K: AsRef<std::ffi::OsStr>, V: AsRef<std::ffi::OsStr>>(k: K, v: V) -> Result<()> {
match std::env::var(k.as_ref()) {
Ok(other) if other != "" => {
println!(
"cargo:warning=Using existing environment variable setting {:?}={:?}",
k.as_ref(),
v.as_ref()
);
}
_ => std::env::set_var(k, v),
}
Ok(())
}
/// Find a TVM installation using TVM build by either first installing or detecting.
fn find_using_tvm_build() -> Result<TVMInstall> {
let mut build_config = BuildConfig::default();
build_config.repository = Some("https://github.com/apache/tvm".to_string());
build_config.branch = Some(option_env!("TVM_BRANCH").unwrap_or("main").into());
if cfg!(feature = "use-cuda") {
build_config.settings.use_cuda = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-opencl") {
build_config.settings.use_opencl = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-vulkan") {
build_config.settings.use_vulkan = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-rocm") {
build_config.settings.use_rocm = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-metal") {
build_config.settings.use_metal = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-hexagon-device") {
build_config.settings.use_hexagon_device = Some(true);
}
if cfg!(feature = "use-rpc") {
build_config.settings.use_rpc = Some(true);
}
if cfg!(feature = "use-threads") {
build_config.settings.use_threads = Some(true);
}
if cfg!(feature = "use-llvm") {
build_config.settings.use_llvm = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-stackvm-runtime") {
build_config.settings.use_stackvm_runtime = Some(true);
}
if cfg!(feature = "use-graph-runtime") {
build_config.settings.use_graph_runtime = Some(true);
}
if cfg!(feature = "use-graph-runtime-debug") {
build_config.settings.use_graph_runtime_debug = Some(true);
}
if cfg!(feature = "use-openmp") {
build_config.settings.use_openmp = Some(true);
}
if cfg!(feature = "use-relay-debug") {
build_config.settings.use_relay_debug = Some(true);
}
if cfg!(feature = "use-rtti") {
build_config.settings.use_rtti = Some(true);
}
if cfg!(feature = "use-mscv-mt") {
build_config.settings.use_mscv_mt = Some(true);
}
if cfg!(feature = "use-micro") {
build_config.settings.use_micro = Some(true);
}
if cfg!(feature = "use-install-dev") {
build_config.settings.use_install_dev = Some(true);
}
if cfg!(feature = "hide_private-symbols") {
build_config.settings.hide_private_symbols = Some(true);
}
if cfg!(feature = "use-fallback-stl-map") {
build_config.settings.use_fallback_stl_map = Some(true);
}
if cfg!(feature = "use-ethosn") {
build_config.settings.use_ethosn = Some(true);
}
if cfg!(feature = "use-index_default-i64") {
build_config.settings.use_index_default_i64 = Some(true);
}
if cfg!(feature = "use-tf-tvmdsoop") {
build_config.settings.use_tf_tvmdsoop = Some(true);
}
if cfg!(feature = "use-byodt-posit") {
build_config.settings.use_byodt_posit = Some(true);
}
if cfg!(feature = "use-mkl") {
build_config.settings.use_mkl = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-mkldnn") {
build_config.settings.use_mkldnn = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-dnnl-codegen") {
build_config.settings.use_dnnl_codegen = Some(true);
}
if cfg!(feature = "use-cudnn") {
build_config.settings.use_cudnn = Some(true);
}
if cfg!(feature = "use-cublas") {
build_config.settings.use_cublas = Some(true);
}
if cfg!(feature = "use-thrust") {
build_config.settings.use_thrust = Some(true);
}
if cfg!(feature = "use-miopen") {
build_config.settings.use_miopen = Some(true);
}
if cfg!(feature = "use-rocblas") {
build_config.settings.use_rocblas = Some(true);
}
if cfg!(feature = "use-sort") {
build_config.settings.use_sort = Some(true);
}
if cfg!(feature = "use-nnpack") {
build_config.settings.use_nnpack = Some(true);
}
if cfg!(feature = "use-random") {
build_config.settings.use_random = Some(true);
}
if cfg!(feature = "use-micro-standalone-runtime") {
build_config.settings.use_micro_standalone_runtime = Some(true);
}
if cfg!(feature = "use-cpp-rpc") {
build_config.settings.use_cpp_rpc = Some(true);
}
if cfg!(feature = "use-tflite") {
build_config.settings.use_tflite = Some(true);
}
if cfg!(feature = "use-coreml") {
build_config.settings.use_coreml = Some(true);
}
if cfg!(feature = "use-target-onnx") {
build_config.settings.use_target_onnx = Some(true);
}
if cfg!(feature = "use-arm-compute-lib") {
build_config.settings.use_arm_compute_lib = Some(true);
}
if cfg!(feature = "use-arm-compute-lib-graph-runtime") {
build_config.settings.use_arm_compute_lib_graph_runtime = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-tensorrt-codegen") {
build_config.settings.use_tensorrt_codegen = Some(true);
}
if cfg!(feature = "use-tensorrt-runtime") {
build_config.settings.use_tensorrt_runtime = CMakeSetting::from_str("on").ok();
}
if cfg!(feature = "use-vitis-ai") {
build_config.settings.use_vitis_ai = Some(true);
}
if cfg!(any(
feature = "static-linking",
feature = "build-static-runtime"
)) {
build_config.settings.build_static_runtime = Some(true);
}
let build_result = tvm_build::build(build_config)?;
let source_path = build_result.revision.source_path();
let build_path = build_result.revision.build_path();
Ok(TVMInstall {
source_path,
build_path,
})
}
fn main() -> Result<()> {
let TVMInstall {
source_path,
build_path,
} = match option_env!("TVM_HOME") {
Some(tvm_path) if tvm_path != "" => find_using_tvm_path(tvm_path),
_ => find_using_tvm_build(),
}?;
// If the TVM_HOME environment variable changed, the LLVM_CONFIG_PATH environment variable
// changed or the source headers have changed we need to rebuild the Rust bindings.
println!("cargo:rerun-if-env-changed=TVM_HOME");
println!("cargo:rerun-if-env-changed=LLVM_CONFIG_PATH");
println!("cargo:rerun-if-changed={}/include", source_path.display());
let library_name = if cfg!(feature = "runtime-only") {
"tvm_runtime"
} else {
"tvm"
};
match &std::env::var("CARGO_CFG_TARGET_ARCH")
.expect("CARGO_CFG_TARGET_ARCH must be set by CARGO")[..]
{
"wasm32" => {}
_ => {
if cfg!(feature = "static-linking") {
println!("cargo:rustc-link-lib=static={}", library_name);
// TODO(@jroesch): move this to tvm-build as library_path?
println!(
"cargo:rustc-link-search=native={}/build",
build_path.display()
);
}
if cfg!(feature = "dynamic-linking") {
println!("cargo:rustc-link-lib=dylib={}", library_name);
println!(
"cargo:rustc-link-search=native={}/build",
build_path.display()
);
}
}
};
let runtime_api = source_path.join("include/tvm/runtime/c_runtime_api.h");
let backend_api = source_path.join("include/tvm/runtime/c_backend_api.h");
let source_path = source_path.display().to_string();
let dlpack_include = format!("-I{}/3rdparty/dlpack/include/", source_path);
let tvm_include = format!("-I{}/include/", source_path);
let out_file = PathBuf::from(std::env::var("OUT_DIR")?).join("c_runtime_api.rs");
// @see rust-bindgen#550 for `blacklist_type`
bindgen::Builder::default()
.header(runtime_api.display().to_string())
.header(backend_api.display().to_string())
.clang_arg(dlpack_include)
.clang_arg(tvm_include)
.blacklist_type("max_align_t")
.layout_tests(false)
.derive_partialeq(true)
.derive_eq(true)
.derive_default(true)
.generate()
.map_err(|()| {
anyhow::anyhow!("bindgen failed to generate the Rust bindings for the C API")
})?
.write_to_file(out_file)
.context("failed to write the generated Rust binding to disk")?;
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/array.rs | /*
* 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.
*/
use std::{
mem,
os::raw::{c_int, c_void},
};
use crate::ffi::{
DLDataType, DLDataTypeCode_kDLFloat, DLDataTypeCode_kDLInt, DLDataTypeCode_kDLUInt, DLDevice,
DLDeviceType_kDLCPU, DLTensor,
};
/// `From` conversions to `DLTensor` for `ndarray::Array`.
/// Takes a reference to the `ndarray` since `DLTensor` is not owned.
macro_rules! impl_dltensor_from_ndarray {
($type:ty, $typecode:expr) => {
impl<'a, D: ndarray::Dimension> From<&'a mut ndarray::Array<$type, D>> for DLTensor {
fn from(arr: &'a mut ndarray::Array<$type, D>) -> Self {
DLTensor {
data: arr.as_mut_ptr() as *mut c_void,
device: DLDevice {
device_type: DLDeviceType_kDLCPU,
device_id: 0,
},
ndim: arr.ndim() as c_int,
dtype: DLDataType {
code: $typecode as u8,
bits: 8 * mem::size_of::<$type>() as u8,
lanes: 1,
},
shape: arr.shape().as_ptr() as *const i64 as *mut i64,
strides: arr.strides().as_ptr() as *const i64 as *mut i64,
byte_offset: 0,
..Default::default()
}
}
}
};
}
impl_dltensor_from_ndarray!(f32, DLDataTypeCode_kDLFloat);
impl_dltensor_from_ndarray!(f64, DLDataTypeCode_kDLFloat);
impl_dltensor_from_ndarray!(i32, DLDataTypeCode_kDLInt);
impl_dltensor_from_ndarray!(i64, DLDataTypeCode_kDLInt);
impl_dltensor_from_ndarray!(u32, DLDataTypeCode_kDLUInt);
impl_dltensor_from_ndarray!(u64, DLDataTypeCode_kDLUInt);
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/byte_array.rs | /*
* 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.
*/
use std::convert::TryFrom;
use crate::errors::ValueDowncastError;
use crate::ffi::{TVMByteArray, TVMByteArrayFree};
use crate::{ArgValue, RetValue};
/// A newtype wrapping a raw TVM byte-array.
///
/// ## Example
///
/// ```
/// let v = b"hello";
/// let barr = tvm_sys::ByteArray::from(&v);
/// assert_eq!(barr.len(), v.len());
/// assert_eq!(barr.data(), &[104u8, 101, 108, 108, 111]);
/// ```
pub enum ByteArray {
Rust(TVMByteArray),
External(TVMByteArray),
}
impl Drop for ByteArray {
fn drop(&mut self) {
match self {
ByteArray::Rust(bytes) => {
let ptr = bytes.data;
let len = bytes.size as _;
let cap = bytes.size as _;
let data: Vec<u8> = unsafe { Vec::from_raw_parts(ptr as _, len, cap) };
drop(data);
}
ByteArray::External(byte_array) => unsafe {
if TVMByteArrayFree(byte_array as _) != 0 {
panic!("error");
}
},
}
}
}
impl ByteArray {
/// Gets the underlying byte-array
pub fn data(&self) -> &[u8] {
match self {
ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => unsafe {
std::slice::from_raw_parts(byte_array.data as *const u8, byte_array.size as _)
},
}
}
/// Gets the length of the underlying byte-array
pub fn len(&self) -> usize {
match self {
ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => byte_array.size as _,
}
}
/// Converts the underlying byte-array to `Vec<u8>`
pub fn to_vec(&self) -> Vec<u8> {
self.data().to_vec()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<T: Into<Vec<u8>>> From<T> for ByteArray {
fn from(arg: T) -> Self {
let mut incoming_bytes: Vec<u8> = arg.into();
let mut bytes = Vec::with_capacity(incoming_bytes.len());
bytes.append(&mut incoming_bytes);
let mut bytes = std::mem::ManuallyDrop::new(bytes);
let ptr = bytes.as_mut_ptr();
assert_eq!(bytes.len(), bytes.capacity());
ByteArray::Rust(TVMByteArray {
data: ptr as _,
size: bytes.len() as _,
})
}
}
impl<'a> From<&'a ByteArray> for ArgValue<'a> {
fn from(val: &'a ByteArray) -> ArgValue<'a> {
match val {
ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => {
ArgValue::Bytes(byte_array)
}
}
}
}
// todo(@jroesch): #8800 Follow up with ByteArray RetValue ownership.
// impl From<ByteArray> for RetValue {
// fn from(val: ByteArray) -> RetValue {
// match val {
// ByteArray::Rust(byte_array) | ByteArray::External(byte_array) => {
// // TODO(@jroesch): This requires a little more work, going to land narratives
// RetValue::Bytes(byte_array)
// }
// }
// }
// }
impl TryFrom<RetValue> for ByteArray {
type Error = ValueDowncastError;
fn try_from(val: RetValue) -> Result<ByteArray, Self::Error> {
match val {
RetValue::Bytes(array) => Ok(ByteArray::External(array)),
_ => Err(ValueDowncastError {
expected_type: "ByteArray",
actual_type: format!("{:?}", val),
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn convert() {
let v = vec![1u8, 2, 3];
let barr = ByteArray::from(v.to_vec());
assert_eq!(barr.len(), v.len());
assert_eq!(barr.to_vec(), vec![1u8, 2, 3]);
let v = b"hello";
let barr = ByteArray::from(v.to_vec());
assert_eq!(barr.len(), v.len());
assert_eq!(barr.data(), &[104u8, 101, 108, 108, 111]);
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/datatype.rs | /*
* 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.
*/
use std::any::TypeId;
use std::convert::TryFrom;
use std::str::FromStr;
use crate::ffi::DLDataType;
use crate::packed_func::RetValue;
use thiserror::Error;
const DL_INT_CODE: u8 = 0;
const DL_UINT_CODE: u8 = 1;
const DL_FLOAT_CODE: u8 = 2;
const DL_HANDLE: u8 = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct DataType {
code: u8,
bits: u8,
lanes: u16,
}
impl DataType {
pub const fn new(code: u8, bits: u8, lanes: u16) -> DataType {
DataType { code, bits, lanes }
}
/// Returns the number of bytes occupied by an element of this `DataType`.
pub fn itemsize(&self) -> usize {
(self.bits as usize * self.lanes as usize) >> 3
}
/// Returns whether this `DataType` represents primitive type `T`.
pub fn is_type<T: 'static>(&self) -> bool {
if self.lanes != 1 {
return false;
}
let typ = TypeId::of::<T>();
(typ == TypeId::of::<i32>() && self.code == DL_INT_CODE && self.bits == 32)
|| (typ == TypeId::of::<i64>() && self.code == DL_INT_CODE && self.bits == 64)
|| (typ == TypeId::of::<u32>() && self.code == DL_UINT_CODE && self.bits == 32)
|| (typ == TypeId::of::<u64>() && self.code == DL_UINT_CODE && self.bits == 64)
|| (typ == TypeId::of::<f32>() && self.code == DL_FLOAT_CODE && self.bits == 32)
|| (typ == TypeId::of::<f64>() && self.code == DL_FLOAT_CODE && self.bits == 64)
}
pub fn code(&self) -> usize {
self.code as usize
}
pub fn bits(&self) -> usize {
self.bits as usize
}
pub fn lanes(&self) -> usize {
self.lanes as usize
}
pub const fn int(bits: u8, lanes: u16) -> DataType {
DataType::new(DL_INT_CODE, bits, lanes)
}
pub const fn float(bits: u8, lanes: u16) -> DataType {
DataType::new(DL_FLOAT_CODE, bits, lanes)
}
pub const fn float32() -> DataType {
Self::float(32, 1)
}
pub const fn uint(bits: u8, lanes: u16) -> DataType {
DataType::new(DL_UINT_CODE, bits, lanes)
}
}
impl<'a> From<&'a DataType> for DLDataType {
fn from(dtype: &'a DataType) -> Self {
Self {
code: dtype.code as u8,
bits: dtype.bits as u8,
lanes: dtype.lanes as u16,
}
}
}
impl From<DLDataType> for DataType {
fn from(dtype: DLDataType) -> Self {
Self {
code: dtype.code,
bits: dtype.bits,
lanes: dtype.lanes,
}
}
}
impl From<DataType> for DLDataType {
fn from(dtype: DataType) -> Self {
Self {
code: dtype.code,
bits: dtype.bits,
lanes: dtype.lanes,
}
}
}
#[derive(Debug, Error)]
pub enum ParseDataTypeError {
#[error("invalid number: {0}")]
InvalidNumber(std::num::ParseIntError),
#[error("missing data type specifier (e.g., int32, float64)")]
MissingDataType,
#[error("unknown type: {0}")]
UnknownType(String),
}
/// Implements TVMType conversion from `&str` of general format `{dtype}{bits}x{lanes}`
/// such as "int32", "float32" or with lane "float32x1".
impl FromStr for DataType {
type Err = ParseDataTypeError;
fn from_str(type_str: &str) -> Result<Self, Self::Err> {
use ParseDataTypeError::*;
if type_str == "bool" {
return Ok(DataType::new(1, 1, 1));
}
let mut type_lanes = type_str.split('x');
let typ = type_lanes.next().ok_or(MissingDataType)?;
let lanes = type_lanes
.next()
.map(|l| <u16>::from_str_radix(l, 10))
.unwrap_or(Ok(1))
.map_err(InvalidNumber)?;
let (type_name, bits) = match typ.find(char::is_numeric) {
Some(idx) => {
let (name, bits_str) = typ.split_at(idx);
(
name,
u8::from_str_radix(bits_str, 10).map_err(InvalidNumber)?,
)
}
None => (typ, 32),
};
let type_code = match type_name {
"int" => DL_INT_CODE,
"uint" => DL_UINT_CODE,
"float" => DL_FLOAT_CODE,
"handle" => DL_HANDLE,
_ => return Err(UnknownType(type_name.to_string())),
};
Ok(DataType::new(type_code, bits, lanes))
}
}
impl std::fmt::Display for DataType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.bits == 1 && self.lanes == 1 {
return write!(f, "bool");
}
let mut type_str = match self.code {
DL_INT_CODE => "int",
DL_UINT_CODE => "uint",
DL_FLOAT_CODE => "float",
DL_HANDLE => "handle",
_ => "unknown",
}
.to_string();
type_str += &self.bits.to_string();
if self.lanes > 1 {
type_str += &format!("x{}", self.lanes);
}
f.write_str(&type_str)
}
}
impl From<DataType> for RetValue {
fn from(dt: DataType) -> RetValue {
RetValue::DataType((&dt).into())
}
}
impl TryFrom<RetValue> for DataType {
type Error = anyhow::Error;
fn try_from(ret_value: RetValue) -> anyhow::Result<DataType> {
match ret_value {
RetValue::DataType(dt) => Ok(dt.into()),
// TODO(@jroesch): improve
_ => Err(anyhow::anyhow!("unable to convert datatype from ...")),
}
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/device.rs | /*
* 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.
*/
//! Provides [`Device`] and related device queries.
//!
//! Create a new device for device type and device id.
//!
//! # Example
//!
//! ```
//! # use tvm_sys::{DeviceType, Device};
//! let cpu = DeviceType::from("cpu");
//! let dev = Device::new(cpu , 0);
//! let cpu0 = Device::cpu(0);
//! assert_eq!(dev, cpu0);
//! ```
//!
//! Or from a supported device name.
//!
//! ```
//! use tvm_sys::Device;
//! let cpu0 = Device::from("cpu");
//! println!("{}", cpu0);
//! ```
use std::convert::TryFrom;
use std::fmt::{self, Display, Formatter};
use std::str::FromStr;
use crate::ffi::{self, *};
use crate::packed_func::{ArgValue, RetValue};
use anyhow::Result;
use enumn::N;
use thiserror::Error;
/// Device type represents the set of devices supported by
/// [TVM](https://github.com/apache/tvm).
///
/// ## Example
///
/// ```
/// use tvm_sys::DeviceType;
/// let cpu = DeviceType::from("cpu");
/// println!("device is: {}", cpu);
///```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, N)]
#[repr(i64)]
pub enum DeviceType {
CPU = 1,
CUDA = 2,
CUDAHost = 3,
OpenCL = 4,
Vulkan = 7,
Metal = 8,
VPI = 9,
ROCM = 10,
ExtDev = 12,
}
impl Default for DeviceType {
/// default device is cpu.
fn default() -> Self {
DeviceType::CPU
}
}
impl From<DeviceType> for ffi::DLDeviceType {
fn from(device_type: DeviceType) -> Self {
device_type as Self
}
}
impl From<ffi::DLDeviceType> for DeviceType {
fn from(device_type: ffi::DLDeviceType) -> Self {
Self::n(device_type as _).expect("invalid enumeration value for ffi::DLDeviceType")
}
}
impl Display for DeviceType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
DeviceType::CPU => "cpu",
DeviceType::CUDA => "cuda",
DeviceType::CUDAHost => "cuda_host",
DeviceType::OpenCL => "opencl",
DeviceType::Vulkan => "vulkan",
DeviceType::Metal => "metal",
DeviceType::VPI => "vpi",
DeviceType::ROCM => "rocm",
DeviceType::ExtDev => "ext_device",
// DeviceType(_) => "rpc",
}
)
}
}
impl<'a> From<&'a str> for DeviceType {
fn from(type_str: &'a str) -> Self {
match type_str {
"cpu" => DeviceType::CPU,
"llvm" => DeviceType::CPU,
"stackvm" => DeviceType::CPU,
"cuda" => DeviceType::CUDA,
"nvptx" => DeviceType::CUDA,
"cl" => DeviceType::OpenCL,
"opencl" => DeviceType::OpenCL,
"metal" => DeviceType::Metal,
"vpi" => DeviceType::VPI,
"rocm" => DeviceType::ROCM,
_ => panic!("{:?} not supported!", type_str),
}
}
}
impl<'a> From<&DeviceType> for ArgValue<'a> {
fn from(dev: &DeviceType) -> Self {
Self::Int(*dev as _)
}
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct Device {
pub device_type: DeviceType,
pub device_id: usize,
}
impl Device {
pub fn new(device_type: DeviceType, device_id: usize) -> Device {
Device {
device_type,
device_id,
}
}
}
impl<'a> From<&'a Device> for DLDevice {
fn from(dev: &'a Device) -> Self {
Self {
device_type: dev.device_type.into(),
device_id: dev.device_id as i32,
}
}
}
impl Default for Device {
fn default() -> Self {
Self {
device_type: DLDeviceType_kDLCPU.into(),
device_id: 0,
}
}
}
#[derive(Debug, Error)]
#[error("unsupported device: {0}")]
pub struct UnsupportedDeviceError(String);
macro_rules! impl_tvm_device {
( $( $dev_type:ident : [ $( $dev_name:ident ),+ ] ),+ ) => {
/// Creates a Device from a string (e.g., "cpu", "cuda", "ext_dev")
impl FromStr for Device {
type Err = UnsupportedDeviceError;
fn from_str(type_str: &str) -> Result<Self, Self::Err> {
Ok(Self {
device_type: match type_str {
$( $( stringify!($dev_name) )|+ => $dev_type.into()),+,
_ => return Err(UnsupportedDeviceError(type_str.to_string())),
},
device_id: 0,
})
}
}
impl Device {
$(
$(
pub fn $dev_name(device_id: usize) -> Self {
Self {
device_type: $dev_type.into(),
device_id: device_id,
}
}
)+
)+
}
};
}
impl_tvm_device!(
DLDeviceType_kDLCPU: [cpu, llvm, stackvm],
DLDeviceType_kDLCUDA: [cuda, nvptx],
DLDeviceType_kDLOpenCL: [cl],
DLDeviceType_kDLMetal: [metal],
DLDeviceType_kDLVPI: [vpi],
DLDeviceType_kDLROCM: [rocm],
DLDeviceType_kDLExtDev: [ext_dev]
);
impl<'a> From<&'a str> for Device {
fn from(target: &str) -> Self {
Device::new(DeviceType::from(target), 0)
}
}
impl From<ffi::DLDevice> for Device {
fn from(dev: ffi::DLDevice) -> Self {
Device {
device_type: DeviceType::from(dev.device_type),
device_id: dev.device_id as usize,
}
}
}
impl From<Device> for ffi::DLDevice {
fn from(dev: Device) -> Self {
ffi::DLDevice {
device_type: dev.device_type.into(),
device_id: dev.device_id as i32,
}
}
}
impl Display for Device {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}({})", self.device_type, self.device_id)
}
}
impl<'a> From<&'a Device> for ArgValue<'a> {
fn from(dev: &'a Device) -> Self {
DLDevice::from(dev).into()
}
}
impl<'a> From<Device> for ArgValue<'a> {
fn from(dev: Device) -> Self {
DLDevice::from(dev).into()
}
}
impl From<Device> for RetValue {
fn from(ret_value: Device) -> RetValue {
RetValue::Device(ret_value.into())
}
}
impl TryFrom<RetValue> for Device {
type Error = anyhow::Error;
fn try_from(ret_value: RetValue) -> anyhow::Result<Device> {
match ret_value {
RetValue::Device(dt) => Ok(dt.into()),
// TODO(@jroesch): improve
_ => Err(anyhow::anyhow!("unable to convert datatype from ...")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn device() {
let dev = Device::cpu(0);
println!("device: {}", dev);
let default_dev = Device::new(DeviceType::CPU, 0);
assert_eq!(dev.clone(), default_dev);
assert_ne!(dev, Device::cuda(0));
let str_dev = Device::new(DeviceType::CUDA, 0);
assert_eq!(str_dev.clone(), str_dev);
assert_ne!(str_dev, Device::new(DeviceType::CPU, 0));
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/errors.rs | /*
* 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.
*/
use thiserror::Error;
#[derive(Error, Debug)]
#[error("invalid header (expected {expected_type:?}, found {actual_type:?})")]
pub struct ValueDowncastError {
pub actual_type: String,
pub expected_type: &'static str,
}
#[derive(Error, Debug)]
#[error("Function call `{context:?}` returned error: {message:?}")]
pub struct FuncCallError {
context: String,
message: String,
}
impl FuncCallError {
pub fn get_with_context(context: String) -> Self {
Self {
context,
message: unsafe { std::ffi::CStr::from_ptr(crate::ffi::TVMGetLastError()) }
.to_str()
.expect("failed while attempting to retrieve the TVM error message")
.to_owned(),
}
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/lib.rs | /*
* 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.
*/
//! This crate contains the minimal interface over TVM's
//! C runtime API.
//!
//! These common bindings are useful to both runtimes
//! written in Rust, as well as higher level API bindings.
//!
//! See the `tvm-rt` or `tvm` crates for full bindings to
//! the TVM API.
/// The low-level C runtime FFI API for TVM.
pub mod ffi {
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused)]
use std::os::raw::{c_char, c_int, c_void};
include!(concat!(env!("OUT_DIR"), "/c_runtime_api.rs"));
pub type BackendPackedCFunc = extern "C" fn(
args: *const TVMValue,
type_codes: *const c_int,
num_args: c_int,
out_ret_value: *mut TVMValue,
out_ret_tcode: *mut u32,
resource_handle: *mut c_void,
) -> c_int;
}
pub mod array;
pub mod byte_array;
pub mod datatype;
pub mod device;
pub mod errors;
#[macro_use]
pub mod packed_func;
pub mod value;
pub use byte_array::ByteArray;
pub use datatype::DataType;
pub use device::{Device, DeviceType};
pub use errors::*;
pub use packed_func::{ArgValue, RetValue};
impl<T, E> std::convert::TryFrom<Result<T, E>> for RetValue
where
RetValue: std::convert::TryFrom<T>,
E: From<<RetValue as std::convert::TryFrom<T>>::Error>,
{
type Error = E;
fn try_from(val: Result<T, E>) -> Result<RetValue, Self::Error> {
val.and_then(|t| RetValue::try_from(t).map_err(|e| e.into()))
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/packed_func.rs | /*
* 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.
*/
use std::{
convert::TryFrom,
ffi::{CStr, CString},
os::raw::{c_char, c_void},
};
use crate::{errors::ValueDowncastError, ffi::*};
pub use crate::ffi::TVMValue;
pub trait PackedFunc:
Fn(&[ArgValue]) -> Result<RetValue, crate::errors::FuncCallError> + Send + Sync
{
}
impl<T> PackedFunc for T where
T: Fn(&[ArgValue]) -> Result<RetValue, crate::errors::FuncCallError> + Send + Sync
{
}
/// Calls a packed function and returns a `RetValue`.
///
/// # Example
///
/// `call_packed!(my_tvm_func, &mut arg1, &mut arg2)`
#[macro_export]
macro_rules! call_packed {
($fn:expr, $($args:expr),+) => {
$fn(&[$($args.into(),)+])
};
($fn:expr) => {
$fn(&Vec::new())
};
}
/// Constructs a derivative of a TVMPodValue.
macro_rules! TVMPODValue {
{
$(#[$m:meta])+
$name:ident $(<$a:lifetime>)? {
$($extra_variant:ident ( $variant_type:ty ) ),+ $(,)?
},
match $value:ident {
$($tvm_type:ident => { $from_tvm_type:expr })+
},
match &self {
$($self_type:ident ( $val:ident ) => { $from_self_type:expr })+
}
$(,)?
} => {
$(#[$m])+
#[derive(Clone, Debug)]
pub enum $name $(<$a>)? {
Int(i64),
UInt(i64),
Float(f64),
Null,
DataType(DLDataType),
String(*mut c_char),
Device(DLDevice),
Handle(*mut c_void),
ArrayHandle(TVMArrayHandle),
ObjectHandle(*mut c_void),
ModuleHandle(TVMModuleHandle),
FuncHandle(TVMFunctionHandle),
NDArrayHandle(*mut c_void),
$($extra_variant($variant_type)),+
}
impl $(<$a>)? $name $(<$a>)? {
pub fn from_tvm_value($value: TVMValue, type_code: u32) -> Self {
use $name::*;
#[allow(non_upper_case_globals)]
unsafe {
match type_code as _ {
DLDataTypeCode_kDLInt => Int($value.v_int64),
DLDataTypeCode_kDLUInt => UInt($value.v_int64),
DLDataTypeCode_kDLFloat => Float($value.v_float64),
TVMArgTypeCode_kTVMNullptr => Null,
TVMArgTypeCode_kTVMDataType => DataType($value.v_type),
TVMArgTypeCode_kDLDevice => Device($value.v_device),
TVMArgTypeCode_kTVMOpaqueHandle => Handle($value.v_handle),
TVMArgTypeCode_kTVMDLTensorHandle => ArrayHandle($value.v_handle as TVMArrayHandle),
TVMArgTypeCode_kTVMObjectHandle => ObjectHandle($value.v_handle),
TVMArgTypeCode_kTVMObjectRValueRefArg => ObjectHandle(*($value.v_handle as *mut *mut c_void)),
TVMArgTypeCode_kTVMModuleHandle => ModuleHandle($value.v_handle),
TVMArgTypeCode_kTVMPackedFuncHandle => FuncHandle($value.v_handle),
TVMArgTypeCode_kTVMNDArrayHandle => NDArrayHandle($value.v_handle),
$( $tvm_type => { $from_tvm_type } ),+
_ => unimplemented!("{}", type_code),
}
}
}
pub fn to_tvm_value(&self) -> (TVMValue, TVMArgTypeCode) {
use $name::*;
match self {
Int(val) => (TVMValue { v_int64: *val }, DLDataTypeCode_kDLInt),
UInt(val) => (TVMValue { v_int64: *val as i64 }, DLDataTypeCode_kDLUInt),
Float(val) => (TVMValue { v_float64: *val }, DLDataTypeCode_kDLFloat),
Null => (TVMValue{ v_int64: 0 },TVMArgTypeCode_kTVMNullptr),
DataType(val) => (TVMValue { v_type: *val }, TVMArgTypeCode_kTVMDataType),
Device(val) => (TVMValue { v_device: val.clone() }, TVMArgTypeCode_kDLDevice),
String(val) => {
(
TVMValue { v_handle: *val as *mut c_void },
TVMArgTypeCode_kTVMStr,
)
}
Handle(val) => (TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMOpaqueHandle),
ArrayHandle(val) => {
(
TVMValue { v_handle: *val as *const _ as *mut c_void },
TVMArgTypeCode_kTVMNDArrayHandle,
)
},
ObjectHandle(val) => (TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMObjectHandle),
ModuleHandle(val) =>
(TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMModuleHandle),
FuncHandle(val) => (
TVMValue { v_handle: *val },
TVMArgTypeCode_kTVMPackedFuncHandle
),
NDArrayHandle(val) =>
(TVMValue { v_handle: *val }, TVMArgTypeCode_kTVMNDArrayHandle),
$( $self_type($val) => { $from_self_type } ),+
}
}
}
}
}
TVMPODValue! {
/// A borrowed TVMPODValue. Can be constructed using `into()` but the preferred way
/// to obtain a `ArgValue` is automatically via `call_packed!`.
ArgValue<'a> {
Bytes(&'a TVMByteArray),
Str(&'a CStr),
},
match value {
TVMArgTypeCode_kTVMBytes => { Bytes(&*(value.v_handle as *const TVMByteArray)) }
TVMArgTypeCode_kTVMStr => { Str(CStr::from_ptr(value.v_handle as *const i8)) }
},
match &self {
Bytes(val) => {
(TVMValue { v_handle: *val as *const _ as *mut c_void }, TVMArgTypeCode_kTVMBytes)
}
Str(val) => { (TVMValue { v_handle: val.as_ptr() as *mut c_void }, TVMArgTypeCode_kTVMStr) }
}
}
TVMPODValue! {
/// An owned TVMPODValue. Can be converted from a variety of primitive and object types.
/// Can be downcasted using `try_from` if it contains the desired type.
///
/// # Example
///
/// ```
/// use std::convert::{TryFrom, TryInto};
/// use tvm_sys::RetValue;
///
/// let a = 42u32;
/// let b: u32 = tvm_sys::RetValue::from(a).try_into().unwrap();
///
/// let s = "hello, world!";
/// let t: RetValue = s.to_string().into();
/// assert_eq!(String::try_from(t).unwrap(), s);
/// ```
RetValue {
Bytes(TVMByteArray),
Str(&'static CStr),
},
match value {
TVMArgTypeCode_kTVMBytes => { Bytes(*(value.v_handle as *const TVMByteArray)) }
TVMArgTypeCode_kTVMStr => { Str(CStr::from_ptr(value.v_handle as *mut i8)) }
},
match &self {
Bytes(val) =>
{ (TVMValue { v_handle: val as *const _ as *mut c_void }, TVMArgTypeCode_kTVMBytes ) }
Str(val) =>
{ (TVMValue { v_str: val.as_ptr() }, TVMArgTypeCode_kTVMStr ) }
}
}
#[macro_export]
macro_rules! try_downcast {
($val:ident -> $into:ty, $( |$pat:pat| { $converter:expr } ),+ ) => {
match $val {
$( $pat => { Ok($converter) } )+
_ => Err($crate::errors::ValueDowncastError {
actual_type: format!("{:?}", $val),
expected_type: stringify!($into),
}),
}
};
}
/// Creates a conversion to a `ArgValue` for a primitive type and DLDataTypeCode.
macro_rules! impl_pod_value {
($variant:ident, $inner_ty:ty, [ $( $type:ty ),+ ] ) => {
$(
impl<'a> From<$type> for ArgValue<'a> {
fn from(val: $type) -> Self {
Self::$variant(val as $inner_ty)
}
}
impl<'a> From<&'a $type> for ArgValue<'a> {
fn from(val: &'a $type) -> Self {
Self::$variant(*val as $inner_ty)
}
}
impl<'a> TryFrom<ArgValue<'a>> for $type {
type Error = $crate::errors::ValueDowncastError;
fn try_from(val: ArgValue<'a>) -> Result<Self, Self::Error> {
try_downcast!(val -> $type, |ArgValue::$variant(val)| { val as $type })
}
}
impl<'a, 'v> TryFrom<&'a ArgValue<'v>> for $type {
type Error = $crate::errors::ValueDowncastError;
fn try_from(val: &'a ArgValue<'v>) -> Result<Self, Self::Error> {
try_downcast!(val -> $type, |ArgValue::$variant(val)| { *val as $type })
}
}
impl From<$type> for RetValue {
fn from(val: $type) -> Self {
Self::$variant(val as $inner_ty)
}
}
impl TryFrom<RetValue> for $type {
type Error = $crate::errors::ValueDowncastError;
fn try_from(val: RetValue) -> Result<Self, Self::Error> {
try_downcast!(val -> $type, |RetValue::$variant(val)| { val as $type })
}
}
)+
};
}
impl_pod_value!(Int, i64, [i8, i16, i32, i64, isize]);
impl_pod_value!(UInt, i64, [u8, u16, u32, u64, usize]);
impl_pod_value!(Float, f64, [f32, f64]);
impl_pod_value!(DataType, DLDataType, [DLDataType]);
impl_pod_value!(Device, DLDevice, [DLDevice]);
impl<'a> From<&'a str> for ArgValue<'a> {
fn from(s: &'a str) -> Self {
Self::String(CString::new(s).unwrap().into_raw())
}
}
impl<'a> From<String> for ArgValue<'a> {
fn from(s: String) -> Self {
Self::String(CString::new(s).unwrap().into_raw())
}
}
impl<'a> From<&'a CStr> for ArgValue<'a> {
fn from(s: &'a CStr) -> Self {
Self::Str(s)
}
}
impl<'a> From<&'a CString> for ArgValue<'a> {
fn from(s: &'a CString) -> Self {
Self::String(s.as_ptr() as _)
}
}
impl<'a> From<&'a TVMByteArray> for ArgValue<'a> {
fn from(s: &'a TVMByteArray) -> Self {
Self::Bytes(s)
}
}
impl<'a> TryFrom<ArgValue<'a>> for &'a str {
type Error = ValueDowncastError;
fn try_from(val: ArgValue<'a>) -> Result<Self, Self::Error> {
try_downcast!(val -> &str, |ArgValue::Str(s)| { s.to_str().unwrap() })
}
}
impl<'a, 'v> TryFrom<&'a ArgValue<'v>> for &'v str {
type Error = ValueDowncastError;
fn try_from(val: &'a ArgValue<'v>) -> Result<Self, Self::Error> {
try_downcast!(val -> &str, |ArgValue::Str(s)| { s.to_str().unwrap() })
}
}
/// Converts an unspecialized handle to a ArgValue.
impl<'a, T> From<*const T> for ArgValue<'a> {
fn from(ptr: *const T) -> Self {
Self::Handle(ptr as *mut c_void)
}
}
/// Converts an unspecialized mutable handle to a ArgValue.
impl<'a, T> From<*mut T> for ArgValue<'a> {
fn from(ptr: *mut T) -> Self {
Self::Handle(ptr as *mut c_void)
}
}
impl<'a> From<&'a mut DLTensor> for ArgValue<'a> {
fn from(arr: &'a mut DLTensor) -> Self {
Self::ArrayHandle(arr as *mut DLTensor)
}
}
impl<'a> From<&'a DLTensor> for ArgValue<'a> {
fn from(arr: &'a DLTensor) -> Self {
Self::ArrayHandle(arr as *const _ as *mut DLTensor)
}
}
impl TryFrom<RetValue> for String {
type Error = ValueDowncastError;
fn try_from(val: RetValue) -> Result<String, Self::Error> {
try_downcast!(
val -> String,
|RetValue::String(s)| { unsafe { CString::from_raw(s).into_string().unwrap() }},
|RetValue::Str(s)| { s.to_str().unwrap().to_string() }
)
}
}
impl From<String> for RetValue {
fn from(s: String) -> Self {
Self::String(std::ffi::CString::new(s).unwrap().into_raw())
}
}
impl From<TVMByteArray> for RetValue {
fn from(arr: TVMByteArray) -> Self {
Self::Bytes(arr)
}
}
impl TryFrom<RetValue> for TVMByteArray {
type Error = ValueDowncastError;
fn try_from(val: RetValue) -> Result<Self, Self::Error> {
try_downcast!(val -> TVMByteArray, |RetValue::Bytes(val)| { val })
}
}
impl Default for RetValue {
fn default() -> Self {
Self::Int(0)
}
}
impl TryFrom<RetValue> for std::ffi::CString {
type Error = ValueDowncastError;
fn try_from(val: RetValue) -> Result<CString, Self::Error> {
try_downcast!(val -> std::ffi::CString,
|RetValue::Str(val)| { val.into() })
}
}
// Implementations for bool.
impl<'a> From<&bool> for ArgValue<'a> {
fn from(s: &bool) -> Self {
(*s as i64).into()
}
}
impl From<bool> for RetValue {
fn from(s: bool) -> Self {
(s as i64).into()
}
}
impl TryFrom<RetValue> for bool {
type Error = ValueDowncastError;
fn try_from(val: RetValue) -> Result<bool, Self::Error> {
try_downcast!(val -> bool,
|RetValue::Int(val)| { !(val == 0) })
}
}
impl<'a> TryFrom<ArgValue<'a>> for bool {
type Error = ValueDowncastError;
fn try_from(val: ArgValue<'a>) -> Result<bool, Self::Error> {
try_downcast!(val -> bool, |ArgValue::Int(val)| { !(val == 0) })
}
}
impl From<()> for RetValue {
fn from(_: ()) -> Self {
RetValue::Null
}
}
impl TryFrom<RetValue> for () {
type Error = ValueDowncastError;
fn try_from(val: RetValue) -> Result<(), Self::Error> {
try_downcast!(val -> bool,
|RetValue::Null| { () })
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm-sys/src/value.rs | /*
* 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.
*/
use std::str::FromStr;
use crate::ffi::*;
use thiserror::Error;
macro_rules! impl_pod_tvm_value {
($field:ident, $field_ty:ty, $( $ty:ty ),+) => {
$(
impl From<$ty> for TVMValue {
fn from(val: $ty) -> Self {
TVMValue { $field: val as $field_ty }
}
}
impl From<TVMValue> for $ty {
fn from(val: TVMValue) -> Self {
unsafe { val.$field as $ty }
}
}
)+
};
($field:ident, $ty:ty) => {
impl_pod_tvm_value!($field, $ty, $ty);
}
}
impl_pod_tvm_value!(v_int64, i64, i8, u8, i16, u16, i32, u32, i64, u64, isize, usize);
impl_pod_tvm_value!(v_float64, f64, f32, f64);
impl_pod_tvm_value!(v_type, DLDataType);
impl_pod_tvm_value!(v_device, DLDevice);
#[derive(Debug, Error)]
#[error("unsupported device: {0}")]
pub struct UnsupportedDeviceError(String);
macro_rules! impl_tvm_device {
( $( $dev_type:ident : [ $( $dev_name:ident ),+ ] ),+ ) => {
/// Creates a DLDevice from a string (e.g., "cpu", "cuda", "ext_dev")
impl FromStr for DLDevice {
type Err = UnsupportedDeviceError;
fn from_str(type_str: &str) -> Result<Self, Self::Err> {
Ok(Self {
device_type: match type_str {
$( $( stringify!($dev_name) )|+ => $dev_type ),+,
_ => return Err(UnsupportedDeviceError(type_str.to_string())),
},
device_id: 0,
})
}
}
impl DLDevice {
$(
$(
pub fn $dev_name(device_id: usize) -> Self {
Self {
device_type: $dev_type,
device_id: device_id as i32,
}
}
)+
)+
}
};
}
impl_tvm_device!(
DLDeviceType_kDLCPU: [cpu, llvm, stackvm],
DLDeviceType_kDLCUDA: [cuda, nvptx],
DLDeviceType_kDLOpenCL: [cl],
DLDeviceType_kDLMetal: [metal],
DLDeviceType_kDLVPI: [vpi],
DLDeviceType_kDLROCM: [rocm],
DLDeviceType_kDLExtDev: [ext_dev]
);
| https://github.com/zk-ml/tachikoma |
rust/tvm/examples/resnet/build.rs | /*
* 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.
*/
use anyhow::{Context, Result};
use std::{io::Write, path::Path, process::Command};
fn main() -> Result<()> {
let out_dir = std::env::var("CARGO_MANIFEST_DIR")?;
let python_script = concat!(env!("CARGO_MANIFEST_DIR"), "/src/build_resnet.py");
let synset_txt = concat!(env!("CARGO_MANIFEST_DIR"), "/synset.txt");
println!("cargo:rerun-if-changed={}", python_script);
println!("cargo:rerun-if-changed={}", synset_txt);
let output = Command::new("python3")
.arg(python_script)
.arg(&format!("--build-dir={}", out_dir))
.output()
.with_context(|| anyhow::anyhow!("failed to run python3"))?;
if !output.status.success() {
std::io::stdout()
.write_all(&output.stderr)
.context("Failed to write error")?;
panic!("Failed to execute build script");
}
assert!(
Path::new(&format!("{}/deploy_lib.o", out_dir)).exists(),
"Could not prepare demo: {}",
String::from_utf8(output.stderr)
.unwrap()
.trim()
.split("\n")
.last()
.unwrap_or("")
);
println!("cargo:rustc-link-search=native={}", out_dir);
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/examples/resnet/src/build_resnet.py | #!/usr/bin/env python3
# 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.
import argparse
import csv
import logging
from os import path as osp
import sys
import shutil
import numpy as np
import tvm
from tvm import te
from tvm import relay, runtime
from tvm.relay import testing
from tvm.contrib import graph_executor, cc
from PIL import Image
from tvm.contrib.download import download_testdata
from mxnet.gluon.model_zoo.vision import get_model
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description="Resnet build example")
aa = parser.add_argument
aa("--build-dir", type=str, required=True, help="directory to put the build artifacts")
aa("--batch-size", type=int, default=1, help="input image batch size")
aa(
"--opt-level",
type=int,
default=3,
help="level of optimization. 0 is unoptimized and 3 is the highest level",
)
aa("--target", type=str, default="llvm", help="target for compilation")
aa("--image-shape", type=str, default="3,224,224", help="input image dimensions")
aa("--image-name", type=str, default="cat.png", help="name of input image to download")
args = parser.parse_args()
build_dir = args.build_dir
batch_size = args.batch_size
opt_level = args.opt_level
target = tvm.target.create(args.target)
image_shape = tuple(map(int, args.image_shape.split(",")))
data_shape = (batch_size,) + image_shape
def build(target_dir):
"""Compiles resnet18 with TVM"""
# Download the pretrained model in MxNet's format.
block = get_model("resnet18_v1", pretrained=True)
shape_dict = {"data": (1, 3, 224, 224)}
mod, params = relay.frontend.from_mxnet(block, shape_dict)
# Add softmax to do classification in last layer.
func = mod["main"]
func = relay.Function(
func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs
)
target = "llvm"
with tvm.transform.PassContext(opt_level=3):
graph, lib, params = relay.build(func, target, params=params)
# save the model artifacts
deploy_lib = osp.join(target_dir, "deploy_lib.o")
lib.save(deploy_lib)
cc.create_shared(osp.join(target_dir, "deploy_lib.so"), [osp.join(target_dir, "deploy_lib.o")])
with open(osp.join(target_dir, "deploy_graph.json"), "w") as fo:
fo.write(graph)
with open(osp.join(target_dir, "deploy_param.params"), "wb") as fo:
fo.write(runtime.save_param_dict(params))
def download_img_labels():
"""Download an image and imagenet1k class labels for test"""
from mxnet.gluon.utils import download
synset_url = "".join(
[
"https://gist.githubusercontent.com/zhreshold/",
"4d0b62f3d01426887599d4f7ede23ee5/raw/",
"596b27d23537e5a1b5751d2b0481ef172f58b539/",
"imagenet1000_clsid_to_human.txt",
]
)
synset_name = "synset.txt"
synset_path = download_testdata(synset_url, synset_name + ".raw", module="data", overwrite=True)
with open(synset_path) as fin:
data = fin.read()
synset = eval(data)
with open(synset_name, "w") as f:
for key in synset:
f.write(synset[key])
f.write("\n")
print(synset_path)
print(synset_name)
return synset
def transform_image(image):
image = np.array(image) - np.array([123.0, 117.0, 104.0])
image /= np.array([58.395, 57.12, 57.375])
image = image.transpose((2, 0, 1))
image = image[np.newaxis, :]
return image
def get_cat_image():
img_url = "https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true"
img_path = download_testdata(img_url, "cat.png", module="data")
shutil.copyfile(img_path, "cat.png")
img = Image.open(img_path).resize((224, 224))
return transform_image(img)
def test_build(build_dir):
"""Sanity check with the cat image we download."""
graph = open(osp.join(build_dir, "deploy_graph.json")).read()
lib = tvm.runtime.load_module(osp.join(build_dir, "deploy_lib.so"))
params = bytearray(open(osp.join(build_dir, "deploy_param.params"), "rb").read())
input_data = get_cat_image()
dev = tvm.cpu()
module = graph_executor.create(graph, lib, dev)
module.load_params(params)
module.run(data=input_data)
out = module.get_output(0).numpy()
top1 = np.argmax(out[0])
synset = download_img_labels()
print("TVM prediction top-1:", top1, synset[top1])
if __name__ == "__main__":
logger.info("Compiling the model to graph executor.")
build(build_dir)
logger.info("Testing the model's predication on test data.")
test_build(build_dir)
| https://github.com/zk-ml/tachikoma |
rust/tvm/examples/resnet/src/main.rs | /*
* 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.
*/
use std::{
fs::{self, File},
io::{BufRead, BufReader},
path::Path,
};
use ::ndarray::{Array, ArrayD, Axis};
use image::{FilterType, GenericImageView};
use anyhow::Context as _;
use tvm_rt::graph_rt::GraphRt;
use tvm_rt::*;
fn main() -> anyhow::Result<()> {
let dev = Device::cpu(0);
println!("{}", concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"));
let img = image::open(concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png"))
.context("Failed to open cat.png")?;
println!("original image dimensions: {:?}", img.dimensions());
// for bigger size images, one needs to first resize to 256x256
// with `img.resize_exact` method and then `image.crop` to 224x224
let img = img.resize(224, 224, FilterType::Nearest).to_rgb();
println!("resized image dimensions: {:?}", img.dimensions());
let mut pixels: Vec<f32> = vec![];
for pixel in img.pixels() {
let tmp = pixel.data;
// normalize the RGB channels using mean, std of imagenet1k
let tmp = [
(tmp[0] as f32 - 123.0) / 58.395, // R
(tmp[1] as f32 - 117.0) / 57.12, // G
(tmp[2] as f32 - 104.0) / 57.375, // B
];
for e in &tmp {
pixels.push(*e);
}
}
let arr = Array::from_shape_vec((224, 224, 3), pixels)?;
let arr: ArrayD<f32> = arr.permuted_axes([2, 0, 1]).into_dyn();
// make arr shape as [1, 3, 224, 224] acceptable to resnet
let arr = arr.insert_axis(Axis(0));
// create input tensor from rust's ndarray
let input = NDArray::from_rust_ndarray(&arr, Device::cpu(0), DataType::float(32, 1))?;
println!(
"input shape is {:?}, len: {}, size: {}",
input.shape(),
input.len(),
input.size(),
);
let graph = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_graph.json"))
.context("Failed to open graph")?;
// load the built module
let lib = Module::load(&Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/deploy_lib.so"
)))?;
// parse parameters and convert to TVMByteArray
let params: Vec<u8> = fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/deploy_param.params"))?;
println!("param bytes: {}", params.len());
// If you want an easy way to test a memory leak simply replace the program below with:
// let mut output: Vec<f32>;
// loop {
// let mut graph_rt = GraphRt::create_from_parts(&graph, lib.clone(), dev)?;
// graph_rt.load_params(params.clone())?;
// graph_rt.set_input("data", input.clone())?;
// graph_rt.run()?;
// // prepare to get the output
// let output_shape = &[1, 1000];
// let output_nd = NDArray::empty(output_shape, Device::cpu(0), DataType::float(32, 1));
// graph_rt.get_output_into(0, output_nd.clone())?;
// // flatten the output as Vec<f32>
// output = output_nd.to_vec::<f32>()?;
// }
let mut graph_rt = GraphRt::create_from_parts(&graph, lib, dev)?;
graph_rt.load_params(params)?;
graph_rt.set_input("data", input)?;
graph_rt.run()?;
// prepare to get the output
let output_shape = &[1, 1000];
let output_nd = NDArray::empty(output_shape, Device::cpu(0), DataType::float(32, 1));
graph_rt.get_output_into(0, output_nd.clone())?;
// flatten the output as Vec<f32>
let output: Vec<f32> = output_nd.to_vec::<f32>()?;
// find the maximum entry in the output and its index
let (argmax, max_prob) = output
.iter()
.copied()
.enumerate()
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.unwrap();
// create a hash map of (class id, class name)
let file = File::open("synset.txt").context("failed to open synset")?;
let synset: Vec<std::string::String> = BufReader::new(file)
.lines()
.into_iter()
.map(|x| x.expect("readline failed"))
.collect();
let label = &synset[argmax];
println!(
"input image belongs to the class `{}` with probability {}",
label, max_prob
);
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/bin/tyck.rs | /*
* 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.
*/
use std::path::PathBuf;
use anyhow::Result;
use structopt::StructOpt;
use tvm::ir::diagnostics::codespan;
use tvm::ir::{self, IRModule};
use tvm::runtime::Error;
#[derive(Debug, StructOpt)]
#[structopt(name = "tyck", about = "Parse and type check a Relay program.")]
struct Opt {
/// Input file
#[structopt(parse(from_os_str))]
input: PathBuf,
}
fn main() -> Result<()> {
codespan::init().expect("Failed to initialize Rust based diagnostics.");
let opt = Opt::from_args();
let _module = match IRModule::parse_file(opt.input) {
Err(ir::module::Error::TVM(Error::DiagnosticError(_))) => return Ok(()),
Err(e) => {
return Err(e.into());
}
Ok(module) => module,
};
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/compiler/graph_rt.rs | /*
* 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.
*/
use std::convert::TryInto;
use std::io::Read;
use std::path::Path;
use once_cell::sync::Lazy;
use thiserror::Error;
use crate::ir::IRModule;
use crate::python;
use crate::runtime::{map::Map, Function, Module as RtModule, NDArray, String};
#[derive(Error, Debug)]
pub enum Error {
#[error("{0}")]
IO(#[from] std::io::Error),
#[error("{0}")]
TVM(#[from] crate::errors::Error),
}
static TVM_BUILD: Lazy<Function> = Lazy::new(|| {
python::import("tvm").unwrap();
python::import("tvm.relay").unwrap();
Function::get("tvm.relay.build").unwrap()
});
fn _compile_module(
module: IRModule,
target: String,
target_host: String,
params: Map<String, NDArray>,
module_name: String,
) -> Result<RtModule, Error> {
// The RAW API is Fn(IRModule, String, String, Map<String, NDArray>, String);
let module = TVM_BUILD.invoke(vec![
(&module).into(),
(&target).into(),
(&target_host).into(),
(¶ms).into(),
(&module_name).into(),
])?;
let module: RtModule = module.try_into().unwrap();
Ok(module)
}
#[derive(Debug)]
pub struct CompilerConfig {
target: Option<String>,
target_host: Option<String>,
params: Map<String, NDArray>,
module_name: Option<String>,
}
impl Default for CompilerConfig {
fn default() -> Self {
CompilerConfig {
target: None,
target_host: None,
params: Map::empty(),
module_name: None,
}
}
}
/// Compile a module from a configuration and IRModule.
///
/// # Arguments
///
/// * `config` - The configuration for the compiler.
/// * `module` - The IRModule to compile.
pub fn compile_module(config: CompilerConfig, module: IRModule) -> Result<RtModule, Error> {
let target = config.target.unwrap_or("llvm".into());
_compile_module(
module,
target,
"llvm".into(),
Map::<String, NDArray>::empty(),
"default".into(),
)
}
/// Compile an IRModule on disk and output a runtime module to disk.
///
/// # Arguments
/// * `config` - The configuration for the compiler.
/// * `ir_mod_path` - The path the serialized IRModule.
//
/// * `output_rt_mod_path` - The path to the output runtime module.
pub fn compile_from_disk<P1, P2>(
config: CompilerConfig,
ir_mod_path: P1,
output_rt_mod_path: P2,
) -> Result<(), Error>
where
P1: AsRef<Path>,
P2: AsRef<Path>,
{
let mut input_file = std::fs::File::open(ir_mod_path.as_ref())?;
let mut input_module_text = std::string::String::new();
input_file.read_to_string(&mut input_module_text)?;
let input_module = IRModule::parse("name", input_module_text)?;
let rt_module = compile_module(config, input_module)?;
let output_path_str = output_rt_mod_path.as_ref().display().to_string();
rt_module.export_library(output_path_str)?;
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/compiler/mod.rs | /*
* 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.
*/
pub mod graph_rt;
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/arith.rs | /*
* 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.
*/
use crate::runtime::{Object, ObjectPtr};
use tvm_macros::Object;
macro_rules! define_node {
($name:ident, $ref:expr, $typekey:expr; $node:ident { $($id:ident : $t:ty),*}) => {
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = $ref]
#[type_key = $typekey]
pub struct $node {
base: Object,
$(pub $id : $t),*
}
impl $name {
pub fn new($($id : $t,)*) -> $name {
let base = Object::base::<$node>();
let node = $node { base, $($id),* };
$name(Some(ObjectPtr::new(node)))
}
}
}
}
define_node!(ConstIntBound, "ConstIntBound", "arith.ConstIntBound";
ConstIntBoundNode { min_value: i64, max_value: i64 });
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/attrs.rs | /*
* 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.
*/
use crate::runtime::Object;
use tvm_macros::Object;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Attrs"]
#[type_key = "Attrs"]
pub struct BaseAttrsNode {
pub base: Object,
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/diagnostics/codespan.rs | /*
* 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.
*/
//! A TVM diagnostics renderer which uses the Rust `codespan` library
//! to produce error messages.
//!
//! This is an example of using the exposed API surface of TVM to
//! customize the compiler behavior.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use codespan_reporting::diagnostic::{Diagnostic as CDiagnostic, Label, Severity};
use codespan_reporting::files::SimpleFiles;
use codespan_reporting::term::termcolor::{ColorChoice, StandardStream};
use codespan_reporting::term::{self};
use super::*;
use crate::ir::source_map::*;
/// A representation of a TVM Span as a range of bytes in a file.
struct ByteRange<FileId> {
/// The file in which the range occurs.
#[allow(dead_code)]
file_id: FileId,
/// The range start.
start_pos: usize,
/// The range end.
end_pos: usize,
}
/// A mapping from Span to ByteRange for a single file.
enum FileSpanToByteRange {
AsciiSource(Vec<usize>),
#[allow(dead_code)]
Utf8 {
/// Map character regions which are larger then 1-byte to length.
lengths: HashMap<isize, isize>,
/// The source of the program.
source: String,
},
}
impl FileSpanToByteRange {
/// Construct a span to byte range mapping from the program source.
fn new(source: String) -> FileSpanToByteRange {
if source.is_ascii() {
let line_lengths = source.lines().map(|line| line.len()).collect();
FileSpanToByteRange::AsciiSource(line_lengths)
} else {
panic!()
}
}
/// Lookup the corresponding ByteRange for a given Span.
fn lookup(&self, span: &Span) -> ByteRange<String> {
use FileSpanToByteRange::*;
let source_name: String = span.source_name.name.as_str().unwrap().into();
match self {
AsciiSource(ref line_lengths) => {
let start_pos = (&line_lengths[0..(span.line - 1) as usize])
.into_iter()
.sum::<usize>()
+ (span.column) as usize;
let end_pos = (&line_lengths[0..(span.end_line - 1) as usize])
.into_iter()
.sum::<usize>()
+ (span.end_column) as usize;
ByteRange {
file_id: source_name,
start_pos,
end_pos,
}
}
_ => panic!(),
}
}
}
/// A mapping for all files in a source map to byte ranges.
struct SpanToByteRange {
map: HashMap<String, FileSpanToByteRange>,
}
impl SpanToByteRange {
fn new() -> SpanToByteRange {
SpanToByteRange {
map: HashMap::new(),
}
}
/// Add a source file to the span mapping.
pub fn add_source(&mut self, source: Source) {
let source_name: String = source.source_name.name.as_str().expect("foo").into();
if self.map.contains_key(&source_name) {
panic!()
} else {
let source = source.source.as_str().expect("fpp").into();
self.map
.insert(source_name, FileSpanToByteRange::new(source));
}
}
/// Lookup a span to byte range mapping.
///
/// First resolves the Span to a file, and then maps the span to a byte range in the file.
pub fn lookup(&self, span: &Span) -> ByteRange<String> {
let source_name: String = span.source_name.name.as_str().expect("foo").into();
match self.map.get(&source_name) {
Some(file_span_to_bytes) => file_span_to_bytes.lookup(span),
None => panic!(),
}
}
}
/// The state of the `codespan` based diagnostics.
struct DiagnosticState {
files: SimpleFiles<String, String>,
span_map: SpanToByteRange,
// todo unify wih source name
source_to_id: HashMap<String, usize>,
}
impl DiagnosticState {
fn new() -> DiagnosticState {
DiagnosticState {
files: SimpleFiles::new(),
span_map: SpanToByteRange::new(),
source_to_id: HashMap::new(),
}
}
fn add_source(&mut self, source: Source) {
let source_str: String = source.source.as_str().unwrap().into();
let source_name: String = source.source_name.name.as_str().unwrap().into();
self.span_map.add_source(source);
let file_id = self.files.add(source_name.clone(), source_str);
self.source_to_id.insert(source_name, file_id);
}
fn to_diagnostic(&self, diag: super::Diagnostic) -> CDiagnostic<usize> {
let severity = match diag.level {
DiagnosticLevel::Error => Severity::Error,
DiagnosticLevel::Warning => Severity::Warning,
DiagnosticLevel::Note => Severity::Note,
DiagnosticLevel::Help => Severity::Help,
DiagnosticLevel::Bug => Severity::Bug,
};
let source_name: String = diag.span.source_name.name.as_str().unwrap().into();
let file_id = *self.source_to_id.get(&source_name).unwrap();
let message: String = diag.message.as_str().unwrap().into();
let byte_range = self.span_map.lookup(&diag.span);
let diagnostic = CDiagnostic::new(severity)
.with_message(message)
.with_code("EXXX")
.with_labels(vec![Label::primary(
file_id,
byte_range.start_pos..byte_range.end_pos,
)]);
diagnostic
}
}
fn renderer(state: &mut DiagnosticState, diag_ctx: DiagnosticContext) {
let source_map = diag_ctx.module.source_map.clone();
let writer = StandardStream::stderr(ColorChoice::Always);
let config = codespan_reporting::term::Config::default();
for diagnostic in diag_ctx.diagnostics.clone() {
match source_map.source_map.get(&diagnostic.span.source_name) {
Err(err) => panic!("{}", err),
Ok(source) => {
state.add_source(source);
let diagnostic = state.to_diagnostic(diagnostic);
term::emit(&mut writer.lock(), &config, &state.files, &diagnostic).unwrap();
}
}
}
}
/// Initialize the `codespan` based diagnostics.
///
/// Calling this function will globally override the TVM diagnostics renderer.
pub fn init() -> Result<()> {
let diag_state = Arc::new(Mutex::new(DiagnosticState::new()));
let render_fn = move |diag_ctx: DiagnosticContext| {
let mut guard = diag_state.lock().unwrap();
renderer(&mut *guard, diag_ctx);
};
override_renderer(Some(render_fn))?;
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/diagnostics/mod.rs | /*
* 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.
*/
use super::module::IRModule;
use super::span::*;
use crate::runtime::function::Result;
use crate::runtime::object::{Object, ObjectPtr};
use crate::runtime::{
array::Array,
function::{self, Function, ToFunction},
string::String as TString,
};
/// The diagnostic interface to TVM, used for reporting and rendering
/// diagnostic information by the compiler. This module exposes
/// three key abstractions: a Diagnostic, the DiagnosticContext,
/// and the DiagnosticRenderer.
use tvm_macros::{external, Object};
pub mod codespan;
external! {
#[name("runtime.ArrayGetItem")]
fn get_renderer() -> DiagnosticRenderer;
#[name("diagnostics.DiagnosticRenderer")]
fn diagnostic_renderer(func: Function) -> DiagnosticRenderer;
#[name("diagnostics.Emit")]
fn emit(ctx: DiagnosticContext, diagnostic: Diagnostic) -> ();
#[name("diagnostics.DiagnosticContextDefault")]
fn diagnostic_context_default(module: IRModule) -> DiagnosticContext;
#[name("diagnostics.DiagnosticContextRender")]
fn diagnostic_context_render(ctx: DiagnosticContext) -> ();
#[name("diagnostics.DiagnosticRendererRender")]
fn diagnositc_renderer_render(renderer: DiagnosticRenderer, ctx: DiagnosticContext) -> ();
#[name("diagnostics.ClearRenderer")]
fn clear_renderer() -> ();
}
/// The diagnostic level, controls the printing of the message.
#[repr(C)]
#[derive(PartialEq, Eq, Debug)]
pub enum DiagnosticLevel {
Bug = 10,
Error = 20,
Warning = 30,
Note = 40,
Help = 50,
}
/// A compiler diagnostic.
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Diagnostic"]
#[type_key = "Diagnostic"]
pub struct DiagnosticNode {
pub base: Object,
/// The level.
pub level: DiagnosticLevel,
/// The span at which to report an error.
pub span: Span,
/// The diagnostic message.
pub message: TString,
}
impl Diagnostic {
pub fn new(level: DiagnosticLevel, span: Span, message: TString) -> Diagnostic {
let node = DiagnosticNode {
base: Object::base::<DiagnosticNode>(),
level,
span,
message,
};
ObjectPtr::new(node).into()
}
pub fn bug(span: Span) -> DiagnosticBuilder {
DiagnosticBuilder::new(DiagnosticLevel::Bug, span)
}
pub fn error(span: Span) -> DiagnosticBuilder {
DiagnosticBuilder::new(DiagnosticLevel::Error, span)
}
pub fn warning(span: Span) -> DiagnosticBuilder {
DiagnosticBuilder::new(DiagnosticLevel::Warning, span)
}
pub fn note(span: Span) -> DiagnosticBuilder {
DiagnosticBuilder::new(DiagnosticLevel::Note, span)
}
pub fn help(span: Span) -> DiagnosticBuilder {
DiagnosticBuilder::new(DiagnosticLevel::Help, span)
}
}
/// A wrapper around std::stringstream to build a diagnostic.
pub struct DiagnosticBuilder {
/// The level.
pub level: DiagnosticLevel,
/// The span of the diagnostic.
pub span: Span,
/// The in progress message.
pub message: String,
}
impl DiagnosticBuilder {
pub fn new(level: DiagnosticLevel, span: Span) -> DiagnosticBuilder {
DiagnosticBuilder {
level,
span,
message: "".into(),
}
}
}
/// Display diagnostics in a given display format.
///
/// A diagnostic renderer is responsible for converting the
/// raw diagnostics into consumable output.
///
/// For example the terminal renderer will render a sequence
/// of compiler diagnostics to std::out and std::err in
/// a human readable form.
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "DiagnosticRenderer"]
#[type_key = "DiagnosticRenderer"]
/// A diagnostic renderer, which given a diagnostic context produces a "rendered"
/// form of the diagnostics for either human or computer consumption.
pub struct DiagnosticRendererNode {
/// The base type.
pub base: Object,
// TODO(@jroesch): we can't easily exposed packed functions due to
// memory layout
// missing field here
}
impl DiagnosticRenderer {
/// Render the provided context.
pub fn render(&self, ctx: DiagnosticContext) -> Result<()> {
diagnositc_renderer_render(self.clone(), ctx)
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "DiagnosticContext"]
#[type_key = "DiagnosticContext"]
/// A diagnostic context for recording errors against a source file.
pub struct DiagnosticContextNode {
// The base type.
pub base: Object,
/// The Module to report against.
pub module: IRModule,
/// The set of diagnostics to report.
pub diagnostics: Array<Diagnostic>,
/// The renderer set for the context.
pub renderer: DiagnosticRenderer,
}
/// A diagnostic context which records active errors
/// and contains a renderer.
impl DiagnosticContext {
pub fn new<F>(module: IRModule, render_func: F) -> DiagnosticContext
where
F: Fn(DiagnosticContext) -> () + 'static,
{
let renderer = diagnostic_renderer(render_func.to_function()).unwrap();
let node = DiagnosticContextNode {
base: Object::base::<DiagnosticContextNode>(),
module,
diagnostics: Array::from_vec(vec![]).unwrap(),
renderer,
};
DiagnosticContext(Some(ObjectPtr::new(node)))
}
pub fn default(module: IRModule) -> DiagnosticContext {
diagnostic_context_default(module).unwrap()
}
/// Emit a diagnostic.
pub fn emit(&mut self, diagnostic: Diagnostic) -> Result<()> {
emit(self.clone(), diagnostic)
}
/// Render the errors and raise a DiagnosticError exception.
pub fn render(&mut self) -> Result<()> {
diagnostic_context_render(self.clone())
}
/// Emit a diagnostic and then immediately attempt to render all errors.
pub fn emit_fatal(&mut self, diagnostic: Diagnostic) -> Result<()> {
self.emit(diagnostic)?;
self.render()?;
Ok(())
}
}
/// Override the global diagnostics renderer.
// render_func: Option[Callable[[DiagnosticContext], None]]
// If the render_func is None it will remove the current custom renderer
// and return to default behavior.
fn override_renderer<F>(opt_func: Option<F>) -> Result<()>
where
F: Fn(DiagnosticContext) -> () + 'static,
{
match opt_func {
None => clear_renderer(),
Some(func) => {
let func = func.to_function();
let render_factory = move || diagnostic_renderer(func.clone()).unwrap();
function::register_override(render_factory, "diagnostics.OverrideRenderer", true)?;
Ok(())
}
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/expr.rs | /*
* 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.
*/
use tvm_macros::Object;
use crate::runtime::String as TString;
use crate::runtime::{self, external, IsObject, IsObjectRef, Object, ObjectPtr, ObjectRef};
use crate::DataType;
use super::relay;
use super::span::Span;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "BaseExpr"]
#[type_key = "Expr"]
pub struct BaseExprNode {
pub base: Object,
pub span: Span,
}
impl BaseExprNode {
pub fn base<T: IsObject>(span: Span) -> BaseExprNode {
BaseExprNode {
base: Object::base::<T>(),
span,
}
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PrimExpr"]
#[type_key = "PrimExpr"]
pub struct PrimExprNode {
pub base: BaseExprNode,
pub datatype: DataType,
}
impl PrimExprNode {
pub fn base<T: IsObject>(datatype: DataType, span: Span) -> PrimExprNode {
PrimExprNode {
base: BaseExprNode::base::<T>(span),
datatype,
}
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "GlobalVar"]
#[type_key = "GlobalVar"]
pub struct GlobalVarNode {
pub base: relay::ExprNode,
pub name_hint: TString,
}
impl GlobalVar {
pub fn new(name_hint: String, span: Span) -> GlobalVar {
let node = GlobalVarNode {
base: relay::ExprNode::base::<GlobalVarNode>(span),
name_hint: name_hint.into(),
};
GlobalVar(Some(ObjectPtr::new(node)))
}
}
// TODO(@jroesch): update to match TVM
// Move IntImm
// Define FloatImm
// Define Bool
// Define tvm::Integer?
// Define RangeNode
// TODO: figure out how to type the last argument runtime::TypedPackedFunc<String(ObjectRef)> annotate)
external! {
#[name("ir.AsText")]
fn _as_text(object: ObjectRef, show_meta_data: i32, annotate: runtime::Function) -> TString;
}
pub fn as_text<T: IsObjectRef>(object: T) -> String {
let no_func = unsafe { runtime::Function::null() };
_as_text(object.upcast(), 0, no_func)
.unwrap()
.as_str()
.unwrap()
.into()
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/function.rs | /*
* 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.
*/
use tvm_macros::Object;
use super::span::Span;
use crate::ir::relay::ExprNode;
use crate::runtime::{IsObject, IsObjectRef, ObjectRef};
// TODO(@jroesch): define DictAttrs
pub type DictAttrs = ObjectRef;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "BaseFunc"]
#[type_key = "BaseFunc"]
pub struct BaseFuncNode {
pub base: ExprNode,
pub attrs: DictAttrs,
}
impl BaseFuncNode {
pub fn base<T: IsObject>() -> BaseFuncNode {
BaseFuncNode {
base: ExprNode::base::<T>(Span::null()),
attrs: <ObjectRef as IsObjectRef>::null(),
}
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/mod.rs | /*
* 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.
*/
pub mod arith;
pub mod attrs;
pub mod diagnostics;
pub mod expr;
pub mod function;
pub mod module;
pub mod op;
pub mod relay;
pub mod source_map;
pub mod span;
pub mod tir;
pub mod ty;
pub use expr::*;
pub use module::IRModule;
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/module.rs | /*
* 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.
*/
use std::collections::HashMap;
use std::iter::FromIterator;
use std::path::Path;
use thiserror::Error;
use tvm_macros::Object;
use crate::runtime::array::Array;
use crate::runtime::function::Result;
use crate::runtime::map::Map;
use crate::runtime::string::String as TVMString;
use crate::runtime::{external, IsObjectRef, Object};
use super::expr::GlobalVar;
use super::function::BaseFunc;
use super::source_map::SourceMap;
use super::{relay, ty::GlobalTypeVar, ty::TypeData};
#[derive(Error, Debug)]
pub enum Error {
#[error("{0}")]
IO(#[from] std::io::Error),
#[error("{0}")]
TVM(#[from] crate::runtime::Error),
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "IRModule"]
#[type_key = "IRModule"]
pub struct IRModuleNode {
pub base: Object,
pub functions: Map<GlobalVar, BaseFunc>,
pub type_definitions: Map<GlobalTypeVar, TypeData>,
pub source_map: SourceMap,
// TODO(@jroesch): this is missing some fields
}
external! {
// Parser functions
#[name("parser.ParseModule")]
fn parse_module(file_name: TVMString, source: TVMString) -> IRModule;
#[name("parser.ParseExpr")]
fn parse_expression(file_name: TVMString, source: TVMString) -> IRModule;
#[name("ir.IRModule")]
fn module_new(funcs: Map<GlobalVar, BaseFunc>, types: Map<GlobalTypeVar, TypeData>) -> IRModule;
// Module methods
#[name("ir.Module_Add")]
fn module_add(module: IRModule, type_name: GlobalVar, expr: BaseFunc, update: bool) -> IRModule;
#[name("ir.Module_AddDef")]
fn module_add_def(module: IRModule, type_name: GlobalTypeVar, type_data: TypeData, update: bool) -> ();
#[name("ir.Module_GetGlobalVar")]
fn module_get_global_var(module: IRModule, name: TVMString) -> GlobalVar;
#[name("ir.Module_GetGlobalVars")]
fn module_get_global_vars(module: IRModule) -> Array<GlobalVar>;
#[name("ir.Module_Lookup")]
fn module_lookup(module: IRModule, var: GlobalVar) -> BaseFunc;
#[name("ir.Module_Lookup_str")]
fn module_lookup_str(module: IRModule, name: TVMString) -> BaseFunc;
#[name("ir.Module_GetGlobalTypeVars")]
fn module_get_global_type_vars(module: IRModule) -> Array<GlobalTypeVar>;
#[name("ir.Module_ContainGlobalVar")]
fn module_contains_global_var(module: IRModule, name: TVMString) -> bool;
#[name("ir.Module_ContainGlobalTypeVar")]
fn module_contains_global_type_var(module: IRModule, name: TVMString) -> bool;
#[name("ir.Module_LookupDef")]
fn module_lookup_def(module: IRModule, global: GlobalTypeVar) -> TypeData;
#[name("ir.Module_LookupDef_str")]
fn module_lookup_def_str(module: IRModule, global: TVMString) -> TypeData;
#[name("ir.Module_LookupTag")]
fn module_lookup_tag(module: IRModule, tag: i32) -> relay::Constructor;
#[name("ir.Module_FromExpr")]
fn module_from_expr(expr: relay::Expr, funcs: Map<GlobalVar, BaseFunc>, types: Map<GlobalTypeVar, TypeData>) -> IRModule;
#[name("ir.Module_Import")]
fn module_import(module: IRModule, path: TVMString);
#[name("ir.Module_ImportFromStd")]
fn module_import_from_std(module: IRModule, path: TVMString);
}
// Note: we don't expose update here as update is going to be removed.
impl IRModule {
pub fn new<'a, F, T>(funcs: F, types: T) -> Result<IRModule>
where
F: IntoIterator<Item = (&'a GlobalVar, &'a BaseFunc)>,
T: IntoIterator<Item = (&'a GlobalTypeVar, &'a TypeData)>,
{
module_new(Map::from_iter(funcs), Map::from_iter(types))
}
pub fn empty() -> Result<IRModule> {
let funcs = HashMap::<GlobalVar, BaseFunc>::new();
let types = HashMap::<GlobalTypeVar, TypeData>::new();
IRModule::new(funcs.iter(), types.iter())
}
pub fn parse<N, S>(file_name: N, source: S) -> Result<IRModule>
where
N: Into<TVMString>,
S: Into<TVMString>,
{
parse_module(file_name.into(), source.into())
}
pub fn parse_file<P: 'static + AsRef<Path>>(
file_path: P,
) -> std::result::Result<IRModule, Error> {
let file_path = file_path.as_ref();
let file_path_as_str = file_path.to_str().unwrap().to_string();
let source = std::fs::read_to_string(file_path)?;
let module = IRModule::parse(file_path_as_str, source)?;
Ok(module)
}
pub fn add<F>(&mut self, var: GlobalVar, func: F) -> Result<IRModule>
// todo(@jroesch): can we do better here? why doesn't BaseFunc::Object work?
where
F: IsObjectRef,
F::Object: AsRef<<BaseFunc as IsObjectRef>::Object>,
{
module_add(self.clone(), var, func.upcast(), true)
}
pub fn add_def(
&mut self,
type_name: GlobalTypeVar,
type_data: TypeData,
update: bool,
) -> Result<()> {
module_add_def(self.clone(), type_name, type_data, update)
}
pub fn get_global_var<S>(&self, name: S) -> Result<GlobalVar>
where
S: Into<TVMString>,
{
module_get_global_var(self.clone(), name.into())
}
pub fn get_global_vars(&self) -> Result<Array<GlobalVar>> {
module_get_global_vars(self.clone())
}
pub fn lookup(&self, var: GlobalVar) -> Result<BaseFunc> {
module_lookup(self.clone(), var)
}
pub fn lookup_str<S>(&self, name: S) -> Result<BaseFunc>
where
S: Into<TVMString>,
{
module_lookup_str(self.clone(), name.into())
}
pub fn get_global_type_vars(&self) -> Result<Array<GlobalTypeVar>> {
module_get_global_type_vars(self.clone())
}
pub fn contains_global_var<S: Into<TVMString>>(&self, name: S) -> Result<bool> {
module_contains_global_var(self.clone(), name.into())
}
pub fn contains_global_type_var<S: Into<TVMString>>(&self, name: S) -> Result<bool> {
module_contains_global_type_var(self.clone(), name.into())
}
pub fn lookup_def(&self, global: GlobalTypeVar) -> Result<TypeData> {
module_lookup_def(self.clone(), global)
}
pub fn lookup_def_str<S>(&self, global: S) -> Result<TypeData>
where
S: Into<TVMString>,
{
module_lookup_def_str(self.clone(), global.into())
}
pub fn lookup_tag(&self, tag: i32) -> Result<relay::Constructor> {
module_lookup_tag(self.clone(), tag)
}
pub fn from_expr<E>(expr: E) -> Result<IRModule>
where
E: IsObjectRef,
E::Object: AsRef<<relay::Expr as IsObjectRef>::Object>,
{
Self::from_expr_with_items(expr, HashMap::new(), HashMap::new())
}
pub fn from_expr_with_items<'a, E, F, T>(expr: E, funcs: F, types: T) -> Result<IRModule>
where
F: IntoIterator<Item = (&'a GlobalVar, &'a BaseFunc)>,
T: IntoIterator<Item = (&'a GlobalTypeVar, &'a TypeData)>,
E: IsObjectRef,
E::Object: AsRef<<relay::Expr as IsObjectRef>::Object>,
{
module_from_expr(expr.upcast(), Map::from_iter(funcs), Map::from_iter(types))
}
pub fn import<S: Into<TVMString>>(&mut self, path: S) -> Result<()> {
module_import(self.clone(), path.into())
}
pub fn import_from_std<S: Into<TVMString>>(&mut self, path: S) -> Result<()> {
module_import_from_std(self.clone(), path.into())
}
}
#[cfg(test)]
mod tests {
use super::relay::*;
use super::*;
use crate::ir::span::Span;
use crate::ir::ty::{GlobalTypeVar, TypeData, TypeKind};
use tvm_rt::IsObjectRef;
fn add_dummy_functions(names: Vec<&str>) -> Result<IRModule> {
let mut module = IRModule::empty()?;
let x = Var::static_tensor("x".into(), vec![1, 1], DataType::float32());
let params = vec![x.clone()];
let func = relay::Function::simple(params, x);
for name in names {
let gv = GlobalVar::new(name.into(), Span::null());
module = module.add(gv, func.clone())?;
}
Ok(module)
}
fn add_dummy_types(names: Vec<&str>) -> Result<IRModule> {
let mut module = IRModule::empty()?;
for name in names {
let name: String = name.into();
let name = GlobalTypeVar::new(name, TypeKind::Type, Span::null());
let type_data = TypeData::new(name.clone(), vec![], vec![], Span::null());
module.add_def(name, type_data, true)?;
}
Ok(module)
}
#[test]
fn test_module_add() -> anyhow::Result<()> {
let mut module = IRModule::empty()?;
let x = Var::static_tensor("x".into(), vec![1, 1], DataType::float32());
let params = vec![x.clone()];
let func = relay::Function::simple(params, x);
let module = module.add(GlobalVar::new("foo".into(), Span::null()), func)?;
let lfunc = module.lookup_str("foo")?;
let lfunc = lfunc.downcast::<relay::Function>()?;
assert_eq!(lfunc.params.len(), 1);
Ok(())
}
#[test]
fn test_module_add_def() -> Result<()> {
let mut module = IRModule::empty()?;
let name = GlobalTypeVar::new("my_type", TypeKind::Type, Span::null());
let type_data = TypeData::new(name.clone(), vec![], vec![], Span::null());
module.add_def(name.clone(), type_data, true)?;
let _by_gtv = module.lookup_def(name)?;
let _by_gv = module.lookup_def_str("my_type")?;
Ok(())
}
#[test]
fn test_get_global_var() -> Result<()> {
let mut module = IRModule::empty()?;
let x = Var::static_tensor("x".into(), vec![1, 1], DataType::float32());
let params = vec![x.clone()];
let func = relay::Function::simple(params, x);
let gv_foo = GlobalVar::new("foo".into(), Span::null());
let module = module.add(gv_foo.clone(), func)?;
let gv = module.get_global_var("foo")?;
assert_eq!(gv_foo, gv);
Ok(())
}
#[test]
fn test_get_global_vars() -> Result<()> {
let names = vec!["foo", "bar", "baz"];
let module = add_dummy_functions(names.clone())?;
let gvars: Vec<String> = module
.get_global_vars()?
.into_iter()
.map(|gv| gv.name_hint.as_str().unwrap().to_string())
.collect();
for name in names {
assert!(gvars.contains(&name.to_string()));
}
Ok(())
}
#[test]
fn test_get_global_type_vars() -> Result<()> {
let names = vec!["foo", "bar", "baz"];
let module = add_dummy_types(names.clone())?;
let gvars: Vec<String> = module
.get_global_type_vars()?
.into_iter()
.map(|gv| gv.name_hint.as_str().unwrap().to_string())
.collect();
for name in names {
assert!(gvars.contains(&name.to_string()));
}
Ok(())
}
#[test]
fn test_contains_global_var() -> Result<()> {
let module = add_dummy_functions(vec!["foo"])?;
assert!(module.contains_global_var("foo")?);
Ok(())
}
#[test]
fn test_contains_global_type_var() -> Result<()> {
let module = add_dummy_types(vec!["foo"])?;
assert!(module.contains_global_type_var("foo")?);
Ok(())
}
// TODO(@jroesch): not really sure about this API at all.
// pub fn lookup_tag(&self, tag: i32) -> Result<relay::Constructor> {
// module_lookup_tag(self.clone(), tag)
// }
#[test]
fn test_from_expr() -> Result<()> {
let x = Var::static_tensor("x".into(), vec![1, 1], DataType::float32());
let params = vec![x.clone()];
let func = relay::Function::simple(params, x);
let module = IRModule::from_expr(func.clone())?;
let main_fn = module.lookup_str("main")?;
let main_fn = main_fn.downcast::<relay::Function>()?;
assert_eq!(main_fn, func);
Ok(())
}
#[test]
fn test_import() -> Result<()> {
let mut std_path: String = env!("CARGO_MANIFEST_DIR").into();
std_path += "/../../python/tvm/relay/std/prelude.rly";
let mut mod1 = IRModule::empty()?;
mod1.import(std_path.clone())?;
mod1.lookup_str("map")?;
// TODO(@jroesch): this requires another patch of mine to enable.
// if cfg!(feature = "python") {
// crate::python::load().unwrap();
// let mut mod2 = IRModule::empty()?;
// mod2.import_from_std("prelude.rly")?;
// mod2.lookup_str("map")?;
// }
Ok(())
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/op.rs | /*
* 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.
*/
use crate::ir::relay::ExprNode;
use crate::runtime::array::Array;
use crate::runtime::ObjectRef;
use crate::runtime::String as TString;
use tvm_macros::Object;
type FuncType = ObjectRef;
type AttrFieldInfo = ObjectRef;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Op"]
#[type_key = "Op"]
pub struct OpNode {
pub base: ExprNode,
pub name: TString,
pub op_type: FuncType,
pub description: TString,
pub arguments: Array<AttrFieldInfo>,
pub attrs_type_key: TString,
pub attrs_type_index: u32,
pub num_inputs: i32,
pub support_level: i32,
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/relay/attrs/mod.rs | /*
* 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.
*/
pub mod nn;
pub mod reduce;
pub mod transform;
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/relay/attrs/nn.rs | /*
* 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.
*/
use crate::ir::attrs::BaseAttrsNode;
use crate::ir::PrimExpr;
use crate::runtime::array::Array;
use crate::runtime::DataType;
use crate::runtime::String as TString;
use tvm_macros::Object;
type IndexExpr = PrimExpr;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PadAttrs"]
#[type_key = "relay.attrs.PadAttrs"]
pub struct PadAttrsNode {
pub base: BaseAttrsNode,
pub pad_width: Array<Array<IndexExpr>>,
pub pad_mode: TString,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Conv1DAttrs"]
#[type_key = "relay.attrs.Conv1DAttrs"]
pub struct Conv1DAttrsNode {
pub base: BaseAttrsNode,
pub strides: Array<IndexExpr>,
pub padding: Array<IndexExpr>,
pub dilation: Array<IndexExpr>,
// TODO(@gussmith23) groups is "int", what should it be here?
pub groups: i32,
pub channels: IndexExpr,
pub kernel_size: Array<IndexExpr>,
pub data_layout: TString,
pub kernel_layout: TString,
pub out_layout: TString,
pub out_dtype: DataType,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Conv2DAttrs"]
#[type_key = "relay.attrs.Conv2DAttrs"]
pub struct Conv2DAttrsNode {
pub base: BaseAttrsNode,
pub strides: Array<IndexExpr>,
pub padding: Array<IndexExpr>,
pub dilation: Array<IndexExpr>,
// TODO(@gussmith23) groups is "int", what should it be here?
pub groups: i32,
pub channels: IndexExpr,
pub kernel_size: Array<IndexExpr>,
pub data_layout: TString,
pub kernel_layout: TString,
pub out_layout: TString,
pub auto_scheduler_rewritten_layout: TString,
pub out_dtype: DataType,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Conv3DAttrs"]
#[type_key = "relay.attrs.Conv3DAttrs"]
pub struct Conv3DAttrsNode {
pub base: BaseAttrsNode,
pub strides: Array<IndexExpr>,
pub padding: Array<IndexExpr>,
pub dilation: Array<IndexExpr>,
pub groups: i32,
pub channels: IndexExpr,
pub kernel_size: Array<IndexExpr>,
pub data_layout: TString,
pub kernel_layout: TString,
pub out_layout: TString,
pub auto_scheduler_rewritten_layout: TString,
pub out_dtype: DataType,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Conv3DTransposeAttrs"]
#[type_key = "relay.attrs.Conv3DTransposeAttrs"]
pub struct Conv3DTransposeAttrsNode {
pub base: BaseAttrsNode,
pub channels: IndexExpr,
pub kernel_size: Array<IndexExpr>,
pub strides: Array<IndexExpr>,
pub padding: Array<IndexExpr>,
pub output_padding: Array<IndexExpr>,
pub dilation: Array<IndexExpr>,
pub groups: i32,
pub data_layout: TString,
pub kernel_layout: TString,
pub out_layout: TString,
pub out_dtype: DataType,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "BiasAddAttrs"]
#[type_key = "relay.attrs.BiasAddAttrs"]
pub struct BiasAddAttrsNode {
pub base: BaseAttrsNode,
pub axis: i32,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "MatmulAttrs"]
#[type_key = "relay.attrs.MatmulAttrs"]
pub struct MatmulAttrsNode {
pub base: BaseAttrsNode,
pub units: IndexExpr,
pub out_dtype: DataType,
pub transpose_a: bool,
pub transpose_b: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "DenseAttrs"]
#[type_key = "relay.attrs.DenseAttrs"]
pub struct DenseAttrsNode {
pub base: BaseAttrsNode,
pub units: IndexExpr,
pub auto_scheduler_rewritten_layout: TString,
pub out_dtype: DataType,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "GlobalPool2DAttrs"]
#[type_key = "relay.attrs.GlobalPool2DAttrs"]
pub struct GlobalPool2DAttrsNode {
pub base: BaseAttrsNode,
pub layout: TString,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "MaxPool2DAttrs"]
#[type_key = "relay.attrs.MaxPool2DAttrs"]
pub struct MaxPool2DAttrsNode {
pub base: BaseAttrsNode,
pub pool_size: Array<IndexExpr>,
pub strides: Array<IndexExpr>,
pub padding: Array<IndexExpr>,
pub dilation: Array<IndexExpr>,
pub layout: TString,
pub ceil_mode: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "SoftmaxAttrs"]
#[type_key = "relay.attrs.SoftmaxAttrs"]
pub struct SoftmaxAttrsNode {
pub base: BaseAttrsNode,
pub axis: i32,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "BatchNormAttrs"]
#[type_key = "relay.attrs.BatchNormAttrs"]
pub struct BatchNormAttrsNode {
pub base: BaseAttrsNode,
pub axis: i32,
pub epsilon: f64,
pub center: bool,
pub scale: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "LeakyReluAttrs"]
#[type_key = "relay.attrs.LeakyReluAttrs"]
pub struct LeakyReluAttrsNode {
pub base: BaseAttrsNode,
pub alpha: f64,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "AvgPool2DAttrs"]
#[type_key = "relay.attrs.AvgPool2DAttrs"]
pub struct AvgPool2DAttrsNode {
pub base: BaseAttrsNode,
pub pool_size: Array<IndexExpr>,
pub strides: Array<IndexExpr>,
pub padding: Array<IndexExpr>,
pub dilation: Array<IndexExpr>,
pub layout: TString,
pub ceil_mode: bool,
pub count_include_pad: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "UpSamplingAttrs"]
#[type_key = "relay.attrs.UpSamplingAttrs"]
pub struct UpSamplingAttrsNode {
pub base: BaseAttrsNode,
pub scale_h: f64,
pub scale_w: f64,
pub layout: TString,
pub method: TString,
pub align_corners: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "DropoutAttrs"]
#[type_key = "relay.attrs.DropoutAttrs"]
pub struct DropoutAttrsNode {
pub base: BaseAttrsNode,
pub rate: f64,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "BatchMatmulAttrs"]
#[type_key = "relay.attrs.BatchMatmulAttrs"]
pub struct BatchMatmulAttrsNode {
pub base: BaseAttrsNode,
pub auto_scheduler_rewritten_layout: TString,
pub out_dtype: DataType,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "LayerNormAttrs"]
#[type_key = "relay.attrs.LayerNormAttrs"]
pub struct LayerNormAttrsNode {
pub base: BaseAttrsNode,
pub axis: i32,
pub epsilon: f64,
pub center: bool,
pub scale: bool,
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/relay/attrs/reduce.rs | /*
* 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.
*/
use crate::ir::attrs::BaseAttrsNode;
use crate::ir::PrimExpr;
use crate::runtime::array::Array;
use tvm_macros::Object;
type IndexExpr = PrimExpr;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "ReduceAttrs"]
#[type_key = "relay.attrs.ReduceAttrs"]
pub struct ReduceAttrsNode {
pub base: BaseAttrsNode,
pub axis: Array<IndexExpr>,
pub keepdims: bool,
pub exclude: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "VarianceAttrs"]
#[type_key = "relay.attrs.ReduceAttrs"]
pub struct VarianceAttrsNode {
pub base: BaseAttrsNode,
pub axis: Array<IndexExpr>,
pub keepdims: bool,
pub exclude: bool,
pub unbiased: bool,
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/relay/attrs/transform.rs | /*
* 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.
*/
use crate::ir::attrs::BaseAttrsNode;
use crate::ir::relay::TString;
use crate::ir::tir::IntImm;
use crate::ir::PrimExpr;
use crate::runtime::array::Array;
use crate::runtime::ObjectRef;
use tvm_macros::Object;
use tvm_rt::DataType;
type IndexExpr = PrimExpr;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "ClipAttrs"]
#[type_key = "relay.attrs.ClipAttrs"]
pub struct ClipAttrsNode {
pub base: BaseAttrsNode,
pub a_min: f64,
pub a_max: f64,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "CastAttrs"]
#[type_key = "relay.attrs.CastAttrs"]
pub struct CastAttrsNode {
pub base: BaseAttrsNode,
pub dtype: DataType,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "ExpandDimsAttrs"]
#[type_key = "relay.attrs.ExpandDimsAttrs"]
pub struct ExpandDimsAttrsNode {
pub base: BaseAttrsNode,
pub axis: i32,
pub num_newaxis: i32,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "ConcatenateAttrs"]
#[type_key = "relay.attrs.ConcatenateAttrs"]
pub struct ConcatenateAttrsNode {
pub base: BaseAttrsNode,
pub axis: i32,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "ReshapeAttrs"]
#[type_key = "relay.attrs.ReshapeAttrs"]
pub struct ReshapeAttrsNode {
pub base: BaseAttrsNode,
pub newshape: Array<IndexExpr>,
pub reverse: bool,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "SplitAttrs"]
#[type_key = "relay.attrs.SplitAttrs"]
pub struct SplitAttrsNode {
pub base: BaseAttrsNode,
pub indices_or_sections: ObjectRef,
pub axis: i32,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TransposeAttrs"]
#[type_key = "relay.attrs.TransposeAttrs"]
pub struct TransposeAttrsNode {
pub base: BaseAttrsNode,
pub axes: Array<IndexExpr>,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "SqueezeAttrs"]
#[type_key = "relay.attrs.SqueezeAttrs"]
pub struct SqueezeAttrsNode {
pub base: BaseAttrsNode,
pub axis: Array<IntImm>,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TakeAttrs"]
#[type_key = "relay.attrs.TakeAttrs"]
pub struct TakeAttrsNode {
pub base: BaseAttrsNode,
pub batch_dims: IntImm,
pub axis: IntImm,
pub mode: TString,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "StackAttrs"]
#[type_key = "relay.attrs.StackAttrs"]
pub struct StackAttrsNode {
pub base: BaseAttrsNode,
pub axis: IntImm,
}
// TODO(@gussmith23) How to support Optional type? This "just works" when values
// are provided for begin/end/strides, but I'm not sure what happens if None is
// passed from the C++ side.
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "StridedSliceAttrs"]
#[type_key = "relay.attrs.StridedSliceAttrs"]
pub struct StridedSliceAttrsNode {
pub base: BaseAttrsNode,
pub begin: Array<IntImm>,
pub end: Array<IntImm>,
pub strides: Array<IntImm>,
pub slice_mode: TString,
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/relay/mod.rs | /*
* 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.
*/
use crate::runtime::array::Array;
use crate::runtime::{self, object::*, IsObjectRef, String as TString};
use super::attrs::Attrs;
use super::expr::BaseExprNode;
use super::function::BaseFuncNode;
use super::span::Span;
use super::ty::Type;
use tvm_macros::Object;
use tvm_rt::NDArray;
pub use super::expr::{GlobalVar, GlobalVarNode};
pub use crate::runtime::DataType;
pub mod attrs;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Expr"]
#[type_key = "RelayExpr"]
pub struct ExprNode {
pub base: BaseExprNode,
pub checked_type: Type,
pub virtual_device: ObjectRef,
}
impl ExprNode {
pub fn base<T: IsObject>(span: Span) -> ExprNode {
ExprNode {
base: BaseExprNode::base::<T>(span.clone()),
checked_type: Type::null(),
virtual_device: ObjectRef::null(),
}
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Id"]
#[type_key = "relay.Id"]
pub struct IdNode {
pub base: Object,
pub name_hint: TString,
}
impl Id {
fn new(name_hint: TString) -> Id {
let node = IdNode {
base: Object::base::<IdNode>(),
name_hint: name_hint,
};
Id(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Constant"]
#[type_key = "relay.Constant"]
pub struct ConstantNode {
pub base: ExprNode,
pub data: NDArray,
}
impl Constant {
pub fn new(data: NDArray, span: Span) -> Constant {
let node = ConstantNode {
base: ExprNode::base::<ConstantNode>(span),
data: data,
};
Constant(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Tuple"]
#[type_key = "relay.Tuple"]
pub struct TupleNode {
pub base: ExprNode,
pub fields: Array<Expr>,
}
impl Tuple {
pub fn new(fields: Array<Expr>, span: Span) -> Tuple {
let node = TupleNode {
base: ExprNode::base::<TupleNode>(span),
fields,
};
Tuple(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Var"]
#[type_key = "relay.Var"]
pub struct VarNode {
pub base: ExprNode,
pub vid: Id,
pub type_annotation: Type,
}
impl Var {
pub fn new(name_hint: String, type_annotation: Type, span: Span) -> Var {
let node = VarNode {
base: ExprNode::base::<VarNode>(span),
vid: Id::new(name_hint.into()),
type_annotation: type_annotation,
};
Var(Some(ObjectPtr::new(node)))
}
pub fn name_hint(&self) -> &TString {
&self.vid.0.as_ref().unwrap().name_hint
}
pub fn static_tensor(name_hint: String, sh: Vec<i32>, dtype: DataType) -> Var {
let sh = Array::from_vec(sh.into_iter().map(Into::into).collect()).unwrap();
Self::new(
name_hint,
super::ty::TensorType::new(sh, dtype, Span::null()).upcast(),
Span::null(),
)
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Call"]
#[type_key = "relay.Call"]
pub struct CallNode {
pub base: ExprNode,
deleter: ObjectRef,
pub op: Expr,
pub args: Array<Expr>,
pub attrs: Attrs,
pub type_args: Array<Type>,
}
impl Call {
pub fn new(
op: Expr,
args: Array<Expr>,
attrs: Attrs,
type_args: Array<Type>,
span: Span,
) -> Call {
let node = CallNode {
base: ExprNode::base::<CallNode>(span),
deleter: todo!("Don't know how to construct this"),
op: op,
args: args,
attrs: attrs,
type_args: type_args,
};
Call(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Let"]
#[type_key = "relay.Let"]
pub struct LetNode {
pub base: ExprNode,
pub var: Var,
pub value: Expr,
pub body: Expr,
}
impl Let {
pub fn new(var: Var, value: Expr, body: Expr, span: Span) -> Let {
let node = LetNode {
base: ExprNode::base::<LetNode>(span),
var,
value,
body,
};
Let(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "If"]
#[type_key = "relay.If"]
pub struct IfNode {
pub base: ExprNode,
pub cond: Expr,
pub true_branch: Expr,
pub false_branch: Expr,
}
impl If {
pub fn new(cond: Expr, true_branch: Expr, false_branch: Expr, span: Span) -> If {
let node = IfNode {
base: ExprNode::base::<IfNode>(span),
cond,
true_branch,
false_branch,
};
If(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TupleGetItem"]
#[type_key = "relay.TupleGetItem"]
pub struct TupleGetItemNode {
pub base: ExprNode,
pub tuple: Expr,
pub index: i32,
}
impl TupleGetItem {
pub fn new(tuple: Expr, index: i32, span: Span) -> TupleGetItem {
let node = TupleGetItemNode {
base: ExprNode::base::<TupleGetItemNode>(span),
tuple,
index,
};
TupleGetItem(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "RefCreate"]
#[type_key = "relay.RefCreate"]
pub struct RefCreateNode {
pub base: ExprNode,
pub value: Expr,
}
impl RefCreate {
pub fn new(value: Expr, span: Span) -> RefCreate {
let node = RefCreateNode {
base: ExprNode::base::<RefCreateNode>(span),
value,
};
RefCreate(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "RefRead"]
#[type_key = "relay.RefRead"]
pub struct RefReadNode {
pub base: ExprNode,
pub ref_value: Expr,
}
impl RefRead {
pub fn new(ref_value: Expr, span: Span) -> RefRead {
let node = RefReadNode {
base: ExprNode::base::<RefReadNode>(span),
ref_value,
};
RefRead(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "RefWrite"]
#[type_key = "relay.RefWrite"]
pub struct RefWriteNode {
pub base: ExprNode,
pub ref_value: Expr,
pub value: Expr,
}
impl RefWrite {
pub fn new(ref_value: Expr, value: Expr, span: Span) -> RefWrite {
let node = RefWriteNode {
base: ExprNode::base::<RefWriteNode>(span),
ref_value,
value,
};
RefWrite(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Constructor"]
#[type_key = "relay.Constructor"]
pub struct ConstructorNode {
pub base: ExprNode,
pub name_hint: String,
pub inputs: Array<Type>,
pub tag: i32,
}
impl Constructor {
pub fn new(name_hint: String, inputs: Array<Type>, tag: i32, span: Span) -> Constructor {
let node = ConstructorNode {
base: ExprNode::base::<ConstructorNode>(span),
name_hint,
inputs,
tag,
};
Constructor(Some(ObjectPtr::new(node)))
}
}
// TODO(@jroesch): define the type data
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Pattern"]
#[type_key = "relay.Pattern"]
pub struct PatternNode {
pub base: Object,
pub span: Span,
}
impl PatternNode {
pub fn base<T: IsObject>(span: Span) -> PatternNode {
PatternNode {
base: Object::base::<T>(),
span: span,
}
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PatternWildcard"]
#[type_key = "relay.PatternWildcard"]
pub struct PatternWildcardNode {
pub base: PatternNode,
}
impl PatternWildcard {
pub fn new(span: Span) -> PatternWildcard {
let node = PatternWildcardNode {
base: PatternNode::base::<PatternWildcardNode>(span),
};
PatternWildcard(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PatternVar"]
#[type_key = "relay.PatternVar"]
pub struct PatternVarNode {
pub base: PatternNode,
pub var: Var,
}
impl PatternVar {
pub fn new(var: Var, span: Span) -> PatternVar {
let node = PatternVarNode {
base: PatternNode::base::<PatternVarNode>(span),
var: var,
};
PatternVar(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PatternConstructor"]
#[type_key = "relay.PatternConstructor"]
pub struct PatternConstructorNode {
pub base: PatternNode,
pub constructor: Constructor,
pub patterns: Array<Pattern>,
}
impl PatternConstructor {
pub fn new(
constructor: Constructor,
patterns: Array<Pattern>,
span: Span,
) -> PatternConstructor {
let node = PatternConstructorNode {
base: PatternNode::base::<PatternConstructorNode>(span),
constructor,
patterns,
};
PatternConstructor(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PatternTuple"]
#[type_key = "relay.PatternTuple"]
pub struct PatternTupleNode {
pub base: PatternNode,
pub patterns: Array<Pattern>,
}
impl PatternTuple {
pub fn new(patterns: Array<Pattern>, span: Span) -> PatternTuple {
let node = PatternTupleNode {
base: PatternNode::base::<PatternTupleNode>(span),
patterns,
};
PatternTuple(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Clause"]
#[type_key = "relay.Clause"]
pub struct ClauseNode {
pub base: Object,
pub lhs: Pattern,
pub rhs: Expr,
}
impl Clause {
pub fn new(lhs: Pattern, rhs: Expr, _span: Span) -> Clause {
let node = ClauseNode {
base: Object::base::<ClauseNode>(),
lhs,
rhs,
};
Clause(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Match"]
#[type_key = "relay.Match"]
pub struct MatchNode {
pub base: ExprNode,
pub data: Expr,
pub clauses: Array<Clause>,
pub complete: bool,
}
impl Match {
pub fn new(data: Expr, clauses: Array<Clause>, complete: bool, span: Span) -> Match {
let node = MatchNode {
base: ExprNode::base::<MatchNode>(span),
data,
clauses,
complete,
};
Match(Some(ObjectPtr::new(node)))
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Function"]
#[type_key = "relay.Function"]
pub struct FunctionNode {
pub base: BaseFuncNode,
pub params: Array<Var>,
pub body: Expr,
pub ret_type: Type,
pub type_params: Array<Type>,
}
impl Function {
pub fn new(
params: Array<Var>,
body: Expr,
ret_type: Type,
type_params: Array<Type>,
) -> Function {
let node = FunctionNode {
base: BaseFuncNode::base::<FunctionNode>(),
params: params,
body: body,
ret_type: ret_type,
type_params: type_params,
};
Function(Some(ObjectPtr::new(node)))
}
pub fn simple<E>(params: Vec<Var>, body: E) -> Function
where
E: IsObjectRef,
E::Object: AsRef<<Expr as IsObjectRef>::Object>,
{
let params = Array::from_vec(params).unwrap();
Self::new(
params,
body.upcast(),
Type::null(),
Array::from_vec(vec![]).unwrap(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::as_text;
use crate::runtime::String as TString;
use anyhow::Result;
#[test]
fn test_id() -> Result<()> {
let string = TString::from("foo");
let id = Id::new(string);
let text = as_text(id.clone());
assert!(text.contains("relay.Id"));
Ok(())
}
#[test]
fn test_global() -> Result<()> {
let gv = GlobalVar::new("main".to_string(), Span::null());
let text = as_text(gv.clone());
assert!(text.contains("@main"));
Ok(())
}
#[test]
fn test_var() -> Result<()> {
let var = Var::new("local".to_string(), Type::null(), Span::null());
let text = as_text(var.clone());
assert!(text.contains("%local"));
Ok(())
}
#[test]
fn test_parse_constant() -> Result<()> {
let module = crate::ir::module::IRModule::parse(
"",
r#"
#[version = "0.0.5"]
def @main() -> float32 {
0.01639530062675476f
}
"#,
)
.unwrap();
let main = module
.lookup(module.get_global_var("main").unwrap())
.unwrap();
let func = main.downcast::<crate::ir::relay::Function>().unwrap();
let constant = func
.body
.clone()
.downcast::<crate::ir::relay::Constant>()
.unwrap();
let tuple_type = constant
.clone()
.upcast::<Expr>()
.checked_type
.clone()
.downcast::<crate::ir::ty::TensorType>()
.unwrap();
// Test type
assert_eq!(tuple_type.shape.len(), 0,);
assert_eq!(tuple_type.dtype, "float32".parse().unwrap(),);
// Check that actual data matches up with type
assert_eq!(constant.data.dtype(), "float32".parse().unwrap(),);
assert_eq!(constant.data.len(), 1);
assert_eq!(constant.data.size(), 4);
assert_eq!(constant.data.shape(), &[]);
Ok(())
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/source_map.rs | /*
* 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 exprss or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use crate::runtime::map::Map;
use crate::runtime::object::Object;
use crate::runtime::string::String as TString;
use super::span::SourceName;
use tvm_macros::Object;
/// A program source in any language.
///
/// Could represent the source from an ML framework or a source of an IRModule.
#[repr(C)]
#[derive(Object, Debug)]
#[type_key = "Source"]
#[ref_name = "Source"]
pub struct SourceNode {
pub base: Object,
/// The source name.
pub source_name: SourceName,
/// The raw source.
pub source: TString,
// TODO(@jroesch): Non-ABI compat field
// A mapping of line breaks into the raw source.
// std::vector<std::pair<int, int>> line_map;
}
/// A mapping from a unique source name to source fragments.
#[repr(C)]
#[derive(Object, Debug)]
#[type_key = "SourceMap"]
#[ref_name = "SourceMap"]
pub struct SourceMapNode {
/// The base object.
pub base: Object,
/// The source mapping.
pub source_map: Map<SourceName, Source>,
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/span.rs | /*
* 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.
*/
use crate::runtime::{Object, ObjectPtr, String as TString};
use tvm_macros::Object;
/// A source file name, contained in a Span.
#[repr(C)]
#[derive(Object, Debug)]
#[type_key = "SourceName"]
#[ref_name = "SourceName"]
pub struct SourceNameNode {
pub base: Object,
pub name: TString,
}
/// Span information for diagnostic purposes.
#[repr(C)]
#[derive(Object, Debug)]
#[type_key = "Span"]
#[ref_name = "Span"]
pub struct SpanNode {
pub base: Object,
/// The source name.
pub source_name: SourceName,
/// The line number.
pub line: i32,
/// The column offset.
pub column: i32,
/// The end line number.
pub end_line: i32,
/// The end column number.
pub end_column: i32,
}
impl Span {
pub fn new(
source_name: SourceName,
line: i32,
end_line: i32,
column: i32,
end_column: i32,
) -> Span {
let span_node = SpanNode {
base: Object::base::<SpanNode>(),
source_name,
line,
end_line,
column,
end_column,
};
Span(Some(ObjectPtr::new(span_node)))
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/tir.rs | /*
* 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.
*/
use super::{PrimExpr, PrimExprNode};
use crate::ir::span::Span;
use crate::runtime::{IsObjectRef, String as TVMString};
use crate::DataType;
use tvm_macros::Object;
macro_rules! define_node {
($name:ident, $ref:expr, $typekey:expr; $node:ident { $($id:ident : $t:ty),*}) => {
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = $ref]
#[type_key = $typekey]
pub struct $node {
base: PrimExprNode,
$(pub $id : $t),*
}
impl $name {
pub fn new(datatype: DataType, $($id : $t,)*) -> $name {
let base = PrimExprNode::base::<$node>(datatype, Span::null());
let node = $node { base, $($id),* };
node.into()
}
}
}
}
// TODO(@jroesch): should move up to expr.rs to mirror TVM.
define_node!(IntImm, "IntImm", "IntImm";
IntImmNode { value: i64 });
impl From<i32> for IntImm {
fn from(i: i32) -> IntImm {
IntImm::new(DataType::int(32, 1), i as i64)
}
}
impl From<i32> for PrimExpr {
fn from(i: i32) -> PrimExpr {
IntImm::from(i).upcast()
}
}
define_node!(Var, "Var", "tir.Var";
VarNode { name_hint: TVMString });
define_node!(Add, "Add", "tir.Add"; AddNode { a: PrimExpr, b: PrimExpr });
define_node!(Sub, "Sub", "tir.Sub"; SubNode { a: PrimExpr, b: PrimExpr });
define_node!(Mul, "Mul", "tir.Mul"; MulNode { a: PrimExpr, b: PrimExpr });
define_node!(Div, "Div", "tir.Div"; DivNode { a: PrimExpr, b: PrimExpr });
define_node!(Mod, "Mod", "tir.Mod"; ModNode { a: PrimExpr, b: PrimExpr });
define_node!(FloorDiv, "FloorDiv", "tir.FloorDiv"; FloorDivNode { a: PrimExpr, b: PrimExpr });
define_node!(FloorMod, "FloorMod", "tir.FloorMod"; FloorModNode { a: PrimExpr, b: PrimExpr });
define_node!(Min, "Min", "tir.Min"; MinNode { a: PrimExpr, b: PrimExpr });
define_node!(Max, "Max", "tir.Max"; MaxNode { a: PrimExpr, b: PrimExpr });
// the new datatype is in the base expr
define_node!(Cast, "Cast", "tir.Cast"; CastNode { value: PrimExpr });
// renamed base to start to avoid name clash
define_node!(Ramp, "Ramp", "tir.Ramp"; RampNode { start: PrimExpr, stride: PrimExpr, lanes: i32 });
define_node!(Select, "Select", "tir.Select";
SelectNode { condition: PrimExpr, true_value: PrimExpr, false_value: PrimExpr });
define_node!(Eq, "Eq", "tir.EQ"; EqNode { a: PrimExpr, b: PrimExpr });
define_node!(Ne, "Ne", "tir.NE"; NeNode { a: PrimExpr, b: PrimExpr });
define_node!(Lt, "Lt", "tir.LT"; LtNode { a: PrimExpr, b: PrimExpr });
define_node!(Le, "Le", "tir.LE"; LeNode { a: PrimExpr, b: PrimExpr });
define_node!(Gt, "Gt", "tir.GT"; GtNode { a: PrimExpr, b: PrimExpr });
define_node!(Ge, "Ge", "tir.GE"; GeNode { a: PrimExpr, b: PrimExpr });
define_node!(And, "And", "tir.And"; AndNode { a: PrimExpr, b: PrimExpr });
define_node!(Or, "Or", "tir.Or"; OrNode { a: PrimExpr, b: PrimExpr });
define_node!(Not, "Not", "tir.Not"; NotNode { value: PrimExpr });
define_node!(Let, "Let", "tir.Let"; LetNode { var: Var, value: PrimExpr, body: PrimExpr });
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/ir/ty.rs | /*
* 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.
*/
use tvm_macros::Object;
use tvm_rt::{array::Array, DataType};
use crate::ir::relay::Constructor;
use crate::ir::span::Span;
use crate::ir::PrimExpr;
use crate::runtime::{string::String as TString, IsObject, IsObjectRef, Object, ObjectPtr};
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Type"]
#[type_key = "Type"]
pub struct TypeNode {
pub base: Object,
pub span: Span,
}
impl TypeNode {
fn base<T: IsObject>(span: Span) -> Self {
TypeNode {
base: Object::base::<T>(),
span,
}
}
}
/*
* \brief Primitive data types used in the low-level IR.
*
* PrimType represents POD-values and handles that are
* not automatically managed by the runtime.
*
* \sa PrimType
*/
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PrimType"]
#[type_key = "PrimType"]
pub struct PrimTypeNode {
pub base: TypeNode,
/// The corresponding dtype field.
pub dtype: DataType,
}
/*
*!
* \brief Low-level raw pointer type.
*
* PointerType represents type hints in the TIR to be
* passed to the final code generator.
*
* PointerType should not occur in the high-level analysis.
*
* \sa PointerType
*/
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PointerType"]
#[type_key = "PointerType"]
pub struct PointerTypeNode {
pub base: TypeNode,
/// The type of the element which the pointer points to.
pub element_type: Type,
}
/// Possible kinds of type variables.
#[derive(PartialEq, Eq, Debug)]
pub enum TypeKind {
Type = 0,
/// Template variable in shape expression.
ShapeVar = 1,
Constraint = 4,
AdtHandle = 5,
TypeData = 6,
}
/// Type parameter in functions.
///
/// A type variable can be viewed as template parameter in c++ template function.
///
/// For example, in the following pesudo code,
/// the TypeVar of f is TypeVar("n", kind=kShapeVar).
/// This function can take in a Tensor with shape=(3, 3) and
/// returns a Tensor with shape=(9,)
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TypeVar"]
#[type_key = "TypeVar"]
pub struct TypeVarNode {
pub base: TypeNode,
pub name_hint: TString,
pub kind: TypeKind,
}
/// A global type variable that is used for defining new types or type aliases.
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "GlobalTypeVar"]
#[type_key = "GlobalTypeVar"]
pub struct GlobalTypeVarNode {
pub base: TypeNode,
pub name_hint: TString,
pub kind: TypeKind,
}
impl GlobalTypeVar {
pub fn new<S>(name_hint: S, kind: TypeKind, span: Span) -> GlobalTypeVar
where
S: Into<TString>,
{
let node = GlobalTypeVarNode {
base: TypeNode::base::<GlobalTypeVarNode>(span),
name_hint: name_hint.into(),
kind: kind,
};
ObjectPtr::new(node).into()
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TupleType"]
#[type_key = "TupleType"]
pub struct TupleTypeNode {
pub base: TypeNode,
pub fields: Array<Type>,
}
impl TupleType {
// todo add coercion
pub fn new(fields: Vec<Type>, span: Span) -> Self {
let node = TupleTypeNode {
base: TypeNode::base::<TupleTypeNode>(span),
fields: Array::from_vec(fields).unwrap(),
};
ObjectPtr::new(node).into()
}
pub fn empty() -> TupleType {
TupleType::new(vec![], Span::null())
}
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TypeConstraint"]
#[type_key = "TypeConstraint"]
pub struct TypeConstraintNode {
pub base: TypeNode,
}
/// The representation of a polymorphic function type.
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "FuncType"]
#[type_key = "FuncType"]
pub struct FuncTypeNode {
pub base: TypeNode,
/// The type of arguments.
pub arg_types: Array<Type>,
/// The return type of the function.
pub ret_type: Type,
/// ...
pub type_params: Array<TypeVar>,
/// Type constraints that must hold when
/// calling this function.
pub type_constraints: Array<TypeConstraint>,
}
/*
* \brief Intermediate values that is used to indicate incomplete type
* during type inference.
*
* If we view the type relations as "computational graph of types",
* then IncompleteType represents intermediate values of the graph,
* TypeVar represents the input to the graph.
*/
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "IncompleteType"]
#[type_key = "IncompleteType"]
pub struct IncompleteTypeNode {
pub base: TypeNode,
pub kind: TypeKind,
}
/*
* \brief Reference Type High-level Relay IR.
*
* \sa RelayRefType.
*/
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "RefType"]
#[type_key = "relay.RefType"]
pub struct RelayRefTypeNode {
pub base: TypeNode,
pub value: Type,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "BaseTensorType"]
#[type_key = "relay.BaseTensorType"]
pub struct BaseTensorTypeNode {
pub base: TypeNode,
}
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TensorType"]
#[type_key = "relay.TensorType"]
pub struct TensorTypeNode {
pub base: TypeNode,
pub shape: Array<PrimExpr>,
pub dtype: DataType,
}
impl TensorType {
pub fn new(shape: Array<PrimExpr>, dtype: DataType, span: Span) -> TensorType {
let node = TensorTypeNode {
base: TypeNode::base::<TensorTypeNode>(span),
shape,
dtype,
};
ObjectPtr::new(node).into()
}
pub fn static_sh(shape: Vec<i32>, dtype: DataType, span: Span) -> TensorType {
let sh = Array::from_vec(shape.into_iter().map(Into::into).collect()).unwrap();
Self::new(sh, dtype, span)
}
}
// TODO(@jroesch): implement these in future.
//
// using TypeCall = tvm::TypeCall;
// using TypeCallNode = tvm::TypeCallNode;
// using TypeRelation = tvm::TypeRelation;
// using TypeRelationNode = tvm::TypeRelationNode;
// using TypeRelationFn = tvm::TypeRelationFn;
// using TypeReporter = tvm::TypeReporter;
// using TypeReporterNode = tvm::TypeReporterNode;
/* TypeData container node.
\brief Stores all data for an Algebraic Data Type (ADT).
In particular, it stores the handle (global type var) for an ADT
and the constructors used to build it and is kept in the module. Note
that type parameters are also indicated in the type data: this means that
for any instance of an ADT, the type parameters must be indicated. That is,
an ADT definition is treated as a type-level function, so an ADT handle
must be wrapped in a TypeCall node that instantiates the type-level arguments.
The kind checker enforces this. */
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "TypeData"]
#[type_key = "relay.TypeData"]
pub struct TypeDataNode {
/// The header is simply the name of the ADT.
/// We adopt nominal typing for ADT definitions;
/// that is, differently-named ADT definitions with same constructors
/// have different types.
pub base: TypeNode,
pub type_name: GlobalTypeVar,
/// The type variables (to allow for polymorphism).
pub type_vars: Array<TypeVar>,
/// The constructors.
pub constructors: Array<Constructor>,
}
impl TypeData {
pub fn new<TypeVars, Ctors>(
type_name: GlobalTypeVar,
type_vars: TypeVars,
constructors: Ctors,
span: Span,
) -> TypeData
where
TypeVars: IntoIterator<Item = TypeVar>,
Ctors: IntoIterator<Item = Constructor>,
{
use std::iter::FromIterator;
let type_data = TypeDataNode {
base: TypeNode::base::<TypeDataNode>(span),
type_name,
type_vars: Array::from_iter(type_vars),
constructors: Array::from_iter(constructors),
};
TypeData(Some(ObjectPtr::new(type_data)))
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/lib.rs | /*
* 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.
*/
//! [TVM](https://github.com/apache/tvm) is a compiler stack for deep learning systems.
//!
//! This crate provides an idiomatic Rust API for TVM runtime frontend.
//!
//! One particular use case is that given optimized deep learning model artifacts,
//! (compiled with TVM) which include a shared library
//! `lib.so`, `graph.json` and a byte-array `param.params`, one can load them
//! in Rust idiomatically to create a TVM Graph Executor and
//! run the model for some inputs and get the
//! desired predictions *all in Rust*.
//!
//! Checkout the `examples` repository for more details.
pub use crate::{errors::*, function::Function, module::Module, ndarray::NDArray};
pub use tvm_rt::{DataType, Device, DeviceType};
pub use tvm_rt::device;
pub use tvm_rt::errors;
pub use tvm_rt::function;
pub use tvm_rt::module;
pub use tvm_rt::ndarray;
#[cfg(feature = "python")]
pub mod compiler;
pub mod ir;
#[cfg(feature = "python")]
pub mod python;
pub mod runtime;
pub mod transform;
pub use runtime::version;
#[macro_export]
macro_rules! export {
($($fn_name:expr),*) => {
pub fn tvm_export(ns: &str) -> Result<(), tvm::Error> {
$(
let name = String::from(ns) + ::std::stringify!($fn_name);
tvm::runtime::function::register_override($fn_name, name, true)?;
)*
Ok(())
}
}
}
#[macro_export]
macro_rules! export_mod {
($ns:expr, $($mod_name:expr),*) => {
pub fn tvm_mod_export() -> Result<(), tvm::Error> {
$(
$mod_name::tvm_export($ns)?;
)*
Ok(())
}
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/python.rs | /*
* 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.
*/
use pyo3::prelude::*;
/// Load the Python interpreter into the address space.
///
/// This enables the ability for Rust code to call TVM
/// functionality defined in Python.
///
/// For example registered TVM functions can now be
/// obtained via `Function::get`.
pub fn load() -> Result<String, ()> {
let gil = Python::acquire_gil();
let py = gil.python();
// let main_mod = initialize();
//let main_mod = main_mod.as_ref(py);
load_python_tvm_(py).map_err(|e| {
// We can't display Python exceptions via std::fmt::Display,
// so print the error here manually.
e.print_and_set_sys_last_vars(py);
})
}
pub fn import(mod_to_import: &str) -> PyResult<()> {
let gil = Python::acquire_gil();
let py = gil.python();
import_python(py, mod_to_import)?;
Ok(())
}
fn import_python<'p, 'b: 'p>(py: Python<'p>, to_import: &'b str) -> PyResult<&'p PyModule> {
let imported_mod = py.import(to_import)?;
Ok(imported_mod)
}
fn load_python_tvm_(py: Python) -> PyResult<String> {
let imported_mod = import_python(py, "tvm")?;
let version: String = imported_mod.get("__version__")?.extract()?;
Ok(version)
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::Result;
#[ignore]
#[test]
fn test_run() -> Result<()> {
load().unwrap();
Ok(())
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/runtime/mod.rs | /*
* 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.
*/
pub use tvm_rt::*;
| https://github.com/zk-ml/tachikoma |
rust/tvm/src/transform.rs | /*
* 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.
*/
use crate::ir::relay::Function;
use crate::runtime::array::Array;
use crate::runtime::{
external,
function::{self, Result, ToFunction},
String as TString,
};
use crate::runtime::{Object, ObjectPtr, ObjectRef};
use tvm_macros::Object;
pub type Pass = ObjectRef;
pub type IRModule = ObjectRef;
pub type PassContext = ObjectRef;
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "PassInfo"]
#[type_key = "transform.PassInfo"]
pub struct PassInfoNode {
pub base: Object,
pub opt_level: i32,
pub name: TString,
pub required: Array<TString>,
}
impl PassInfo {
pub fn new(opt_level: i32, name: String, required: Vec<String>) -> Result<PassInfo> {
let required = required.into_iter().map(|name| name.into()).collect();
let required = Array::from_vec(required)?;
let node = PassInfoNode {
base: Object::base::<PassInfoNode>(),
opt_level,
name: name.into(),
required,
};
Ok(PassInfo(Some(ObjectPtr::new(node))))
}
}
external! {
#[name("relay._transform.MakeFunctionPass")]
fn create_func_pass(func: function::Function, pass_info: PassInfo) -> Pass;
}
pub fn function_pass<F: Fn(Function, IRModule, PassContext) -> Function + 'static>(
pass_fn: F,
pass_info: PassInfo,
) -> Result<Pass> {
let func = pass_fn.to_function();
create_func_pass(func, pass_info)
}
/// A macro for generating the correct TVM symbols for plugin loading.
///
/// The expression passed to the macro will be run when TVM loads the
/// shared library.
///
/// This is useful for calling register to register packed functions
/// to consume via TVM's packed function APIs.
#[macro_export]
macro_rules! initialize {
($body:expr) => {
#[no_mangle]
pub unsafe extern "C" fn initialize(
args: *mut tvm_sys::ffi::TVMValue,
type_codes: *mut c_int,
num_args: c_int,
ret: tvm_sys::ffi::TVMRetValueHandle,
) -> c_int {
$body
return 0;
}
};
}
#[macro_export]
macro_rules! export_pass {
($name:literal,$func:expr) => {
#[no_mangle]
pub unsafe extern "C" fn initialize(
args: *mut tvm_sys::ffi::TVMValue,
type_codes: *mut c_int,
num_args: c_int,
ret: tvm_sys::ffi::TVMRetValueHandle,
) -> c_int {
register($func, $name).unwrap();
return 0;
}
};
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/basics/build.rs | /*
* 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.
*/
use anyhow::{Context, Result};
fn main() -> Result<()> {
let out_dir = std::env::var("OUT_DIR").unwrap();
let tvm_mk_add = concat!(env!("CARGO_MANIFEST_DIR"), "/src/tvm_add.py");
let output = std::process::Command::new(tvm_mk_add)
.args(&[
if cfg!(feature = "cpu") {
"llvm"
} else {
"cuda"
},
&std::env::var("OUT_DIR").unwrap(),
])
.output()
.with_context(|| anyhow::anyhow!(tvm_mk_add))?;
assert!(
std::path::Path::new(&format!("{}/test_add.so", out_dir)).exists(),
"Could not build tvm lib: {}",
String::from_utf8(output.stderr)
.context("utf-8 conversion failed")?
.trim()
.split("\n")
.last()
.unwrap_or("")
);
println!("cargo:rustc-link-search=native={}", out_dir);
Ok(())
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/basics/src/main.rs | /*
* 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.
*/
use std::str::FromStr;
use tvm::*;
fn main() {
let shape = &mut [2];
let mut data = vec![3f32, 4.0];
let (dev, dev_name) = if cfg!(feature = "cpu") {
(Device::cpu(0), "cpu")
} else {
(Device::cuda(0), "cuda")
};
let dtype = DataType::from_str("float32").unwrap();
let mut arr = NDArray::empty(shape, dev, dtype);
arr.copy_from_buffer(data.as_mut_slice());
let ret = NDArray::empty(shape, dev, dtype);
let fadd = Module::load(&concat!(env!("OUT_DIR"), "/test_add.so")).unwrap();
if !fadd.enabled(dev_name) {
return;
}
if cfg!(feature = "cuda") {
fadd.import_module(Module::load(&concat!(env!("OUT_DIR"), "/test_add.ptx")).unwrap());
}
// todo(@jroesch): fix the entry_name
fadd.get_function("__tvm_main__", false)
.expect("module must have entry point")
.invoke(vec![(&arr).into(), (&arr).into(), (&ret).into()])
.unwrap();
assert_eq!(ret.to_vec::<f32>().unwrap(), vec![6f32, 8.0]);
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/basics/src/tvm_add.py | #!/usr/bin/env python3
# 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.
import os.path as osp
import sys
import tvm
from tvm import te
from tvm.contrib import cc
def main(target, out_dir):
n = te.var("n")
A = te.placeholder((n,), name="A")
B = te.placeholder((n,), name="B")
C = te.compute(A.shape, lambda i: A[i] + B[i], name="C")
s = te.create_schedule(C.op)
if target == "cuda":
bx, tx = s[C].split(C.op.axis[0], factor=64)
s[C].bind(bx, te.thread_axis("blockIdx.x"))
s[C].bind(tx, te.thread_axis("threadIdx.x"))
fadd = tvm.build(s, [A, B, C], tvm.target.Target(target, host="llvm"), name="myadd")
fadd.save(osp.join(out_dir, "test_add.o"))
if target == "cuda":
fadd.imported_modules[0].save(osp.join(out_dir, "test_add.ptx"))
cc.create_shared(osp.join(out_dir, "test_add.so"), [osp.join(out_dir, "test_add.o")])
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/callback/src/bin/array.rs | /*
* 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.
*/
#![allow(unused_imports)]
extern crate ndarray as rust_ndarray;
use rust_ndarray::ArrayD;
use std::{
convert::{TryFrom, TryInto},
str::FromStr,
};
use tvm::{
errors::Error,
function::register_untyped,
runtime::{ArgValue, RetValue},
*,
};
fn main() {
fn sum<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {
let mut ret = 0.0;
for arg in args {
let arg: NDArray = arg.try_into()?;
let rnd: ArrayD<f32> = ArrayD::try_from(&arg)?;
ret += rnd.scalar_sum();
}
Ok(RetValue::from(ret))
}
let shape = &[2];
let data = vec![3.0, 4.0];
let mut arr = NDArray::empty(shape, Device::cpu(0), DataType::float(32, 1));
arr.copy_from_buffer(data.as_slice());
register_untyped(sum, "sum", true).unwrap();
let func = Function::get("sum").expect("function registered");
let ret: f32 = func
.invoke(vec![(&arr).into()])
.unwrap()
.try_into()
.expect("call should succeed");
assert_eq!(ret, 7.0);
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/callback/src/bin/error.rs | /*
* 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.
*/
use std::panic;
use tvm::{
errors::Error,
runtime::{ArgValue, RetValue},
*,
};
fn main() {
fn error<'a>(_args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {
Err(errors::NDArrayError::DataTypeMismatch {
expected: DataType::int(64, 1),
actual: DataType::float(64, 1),
}
.into())
}
function::register_untyped(error, "error", true).unwrap();
let func = Function::get("error");
assert!(func.is_some());
match func.unwrap().invoke(vec![10.into(), 20.into()]) {
Err(_) => {}
Ok(_) => panic!("expected error"),
}
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/callback/src/bin/float.rs | /*
* 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.
*/
#![allow(unused_imports)]
use std::convert::TryInto;
use tvm::{
errors::Error,
runtime::{ArgValue, RetValue},
*,
};
fn main() {
fn sum<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {
let mut ret = 0.0;
for arg in args.into_iter() {
let val: f64 = arg.try_into()?;
ret += val;
}
Ok(RetValue::from(ret))
}
function::register_untyped(sum, "sum", true).expect("registration should succeed");
let func = Function::get("sum").expect("sum was just registered.");
let ret: f64 = func
.invoke(vec![10.0f64.into(), 20.0.into(), 30.0.into()])
.unwrap()
.try_into()
.unwrap();
assert_eq!(ret, 60f64);
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/callback/src/bin/int.rs | /*
* 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.
*/
use std::convert::TryInto;
use tvm::{
errors::Error,
runtime::{ArgValue, RetValue},
*,
};
fn main() {
fn sum<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {
let mut ret = 0i64;
for arg in args.iter() {
let val: i64 = arg.try_into()?;
ret += val;
}
Ok(RetValue::from(ret))
}
tvm::function::register_untyped(sum, "mysum".to_owned(), false).unwrap();
let func = Function::get("mysum").unwrap();
let ret: i64 = func
.invoke(vec![10.into(), 20.into(), 30.into()])
.unwrap()
.try_into()
.unwrap();
assert_eq!(ret, 60);
}
| https://github.com/zk-ml/tachikoma |
rust/tvm/tests/callback/src/bin/string.rs | /*
* 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.
*/
use std::convert::TryInto;
use tvm::{
errors::Error,
runtime::{ArgValue, RetValue},
*,
};
// FIXME
fn main() {
fn concat_str<'a>(args: Vec<ArgValue<'a>>) -> Result<RetValue, Error> {
let mut ret = "".to_string();
for arg in args.iter() {
let val: &str = arg.try_into()?;
ret += val;
}
Ok(RetValue::from(ret))
}
let a = std::ffi::CString::new("a").unwrap();
let b = std::ffi::CString::new("b").unwrap();
let c = std::ffi::CString::new("c").unwrap();
tvm::function::register_untyped(concat_str, "concat_str".to_owned(), false).unwrap();
let func = Function::get("concat_str").expect("just registered a function");
let args = vec![
a.as_c_str().into(),
b.as_c_str().into(),
c.as_c_str().into(),
];
let ret: String = func
.invoke(args)
.expect("function call should succeed")
.try_into()
.unwrap();
assert_eq!(ret, "abc".to_owned());
}
| https://github.com/zk-ml/tachikoma |
src/arith/conjunctive_normal_form.h | /*
* 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.
*/
/*!
* \file conjunctive_normal_form.h
*
* \brief Centralized location for simplifying into specific forms
*/
#ifndef TVM_ARITH_CONJUNCTIVE_NORMAL_FORM_H_
#define TVM_ARITH_CONJUNCTIVE_NORMAL_FORM_H_
#include <tvm/tir/expr.h>
namespace tvm {
namespace arith {
class Analyzer;
/*! \brief Convert boolean expression to AND of ORs and simplify
*
* \param expr The PrimExpr to be simplified
*
* \param analyzer The analyzer with which to simplify
*
* \return The simplified expression
*/
PrimExpr SimplifyAsAndOfOrs(const PrimExpr& expr, Analyzer* analyzer);
} // namespace arith
} // namespace tvm
#endif // TVM_ARITH_CONJUNCTIVE_NORMAL_FORM_H_
| https://github.com/zk-ml/tachikoma |
src/arith/const_fold.h | /*
* 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.
*/
/*!
* \file const_fold.h
* \brief Centralized location for constant folding.
*/
#ifndef TVM_ARITH_CONST_FOLD_H_
#define TVM_ARITH_CONST_FOLD_H_
#include <tvm/runtime/container/optional.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/op.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include "int_operator.h"
namespace tvm {
namespace arith {
/*!
* \brief Try to run binary compute with constant folding.
*
* \param a The left operand.
* \param b The right operand.
* \tparam Op The operator type.
*
* \note a and b Must already matched data types with each other.
* \return NullOpt if constant fold fails, otherwise return folded result.
*/
template <typename Op>
inline Optional<PrimExpr> TryConstFold(PrimExpr a, PrimExpr b);
/*!
* \brief Try to run unary compute with constant folding.
*
* \param a The left operand.
* \tparam Op The operator type.
*
* \note a and b Must already matched data types with each other.
* \return NullOpt if constant fold fails, otherwise return folded result.
*/
template <typename Op>
inline Optional<PrimExpr> TryConstFold(PrimExpr a);
/*!
* \brief Check whether type is used to represent index.
*
* Index types are frequently used in shape computation
* and need to be aggressively constant-folded.
*
* \param type The type to represent index.
* \return the checked result.
*/
inline bool IsIndexType(const DataType& type) {
return type.is_int() && type.lanes() == 1 && (type.bits() == 32 || type.bits() == 64);
}
/*! \brief Helper to get const folding result repr in int64. */
inline int64_t GetFoldResultInt64Repr(int64_t x, const DataType& dtype) {
if (dtype.bits() < 64) {
x &= (1LL << dtype.bits()) - 1;
}
if (dtype.is_int()) {
// get sign extended value of integer with specified bits
int64_t m = 1LL << (dtype.bits() - 1);
x = (x ^ m) - m;
}
return x;
}
/*! \brief Helper to get fp32 const folding result repr in double. */
inline double GetFoldResultDoubleRepr(float x) {
double res = static_cast<double>(x);
if (std::isinf(res) || std::isnan(res)) {
return res;
}
// certain platform (eg, on gcc7-i386) do the folding arithmetic
// on float and write back to double is optimized to double
// precision arithmetic, this is legal and we check the output
// range thus to ensure consistency when the float result is inf.
if (res < std::numeric_limits<float>::lowest()) {
LOG(WARNING) << "underlying float value overflow";
return -std::numeric_limits<double>::infinity();
} else if (res > std::numeric_limits<float>::max()) {
LOG(WARNING) << "underlying float value overflow";
return std::numeric_limits<double>::infinity();
}
return res;
}
#define TVM_ARITH_CONST_PROPAGATION(BODY) \
using tir::FloatImmNode; \
const IntImmNode* pa = a.as<IntImmNode>(); \
const IntImmNode* pb = b.as<IntImmNode>(); \
const FloatImmNode* fa = a.as<FloatImmNode>(); \
const FloatImmNode* fb = b.as<FloatImmNode>(); \
BODY;
#define TVM_INDEX_CONST_PROPAGATION(BODY) \
const IntImmNode* pa = a.as<IntImmNode>(); \
const IntImmNode* pb = b.as<IntImmNode>(); \
const DataType& ta = a.dtype(); \
const DataType& tb = b.dtype(); \
if (arith::IsIndexType(ta) && arith::IsIndexType(tb)) { \
BODY; \
}
// specialization of constant folders.
template <>
inline Optional<PrimExpr> TryConstFold<tir::Add>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) {
int64_t res = pa->value + pb->value;
return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));
}
if (pa && pa->value == 0) return b;
if (pb && pb->value == 0) return a;
if (fa && fb) {
if (rtype.bits() == 32) {
return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) +
static_cast<float>(fb->value)));
} else if (rtype.bits() == 64) {
return FloatImm(rtype, fa->value + fb->value);
} else {
return NullOpt;
}
}
if (fa && fa->value == 0) return b;
if (fb && fb->value == 0) return a;
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Sub>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
ICHECK(!((pa && pa->dtype.is_uint() && pa->value == 0U) &&
(pb && pb->dtype.is_uint() && pb->value > 0U)))
<< "Checked failed. Minuend 's value is 0U and it's dtype is uint "
<< "while Subtrahend's dtype is uint; which will cause a negative uint";
const DataType& rtype = a.dtype();
if (pa && pb) {
int64_t res = pa->value - pb->value;
return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));
}
if (pb && pb->value == 0) return a;
if (fa && fb) {
if (rtype.bits() == 32) {
return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) -
static_cast<float>(fb->value)));
} else if (rtype.bits() == 64) {
return FloatImm(rtype, fa->value - fb->value);
} else {
return NullOpt;
}
}
if (fb && fb->value == 0) return a;
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Mul>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) {
int64_t res = pa->value * pb->value;
return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));
}
if (pa) {
if (pa->value == 1) return b;
if (pa->value == 0) return a;
}
if (pb) {
if (pb->value == 1) return a;
if (pb->value == 0) return b;
}
if (fa && fb) {
if (rtype.bits() == 32) {
return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) *
static_cast<float>(fb->value)));
} else if (rtype.bits() == 64) {
return FloatImm(rtype, fa->value * fb->value);
} else {
return NullOpt;
}
}
if (fa) {
if (fa->value == 1) return b;
if (fa->value == 0) return a;
}
if (fb) {
if (fb->value == 1) return a;
if (fb->value == 0) return b;
}
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Div>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) {
// due to division and mod can have different modes
// NOTE: this will assumes truc div.
ICHECK_NE(pb->value, 0) << "Divide by zero";
int64_t res = pa->value / pb->value;
return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));
}
if (pa) {
if (pa->value == 0) return a;
}
if (pb) {
if (pb->value == 1) return a;
ICHECK_NE(pb->value, 0) << "Divide by zero";
}
if (fa && fb) {
ICHECK_NE(fb->value, 0) << "Divide by zero";
if (rtype.bits() == 32) {
return FloatImm(rtype, GetFoldResultDoubleRepr(static_cast<float>(fa->value) /
static_cast<float>(fb->value)));
} else if (rtype.bits() == 64) {
return FloatImm(rtype, fa->value / fb->value);
} else {
return NullOpt;
}
}
if (fa && fa->value == 0) return a;
if (fb) {
if (fb->value == 1) return a;
ICHECK_NE(fb->value, 0) << "Divide by zero";
}
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Mod>(PrimExpr a, PrimExpr b) {
TVM_INDEX_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) {
ICHECK_NE(pb->value, 0) << "Divide by zero";
int64_t res = pa->value % pb->value;
return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));
}
if (pa) {
if (pa->value == 0) return a;
}
if (pb) {
if (pb->value == 1) return tir::make_zero(rtype);
ICHECK_NE(pb->value, 0) << "Divide by zero";
}
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::FloorDiv>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) {
ICHECK_NE(pb->value, 0) << "Divide by zero";
int64_t res = arith::floordiv(pa->value, pb->value);
return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));
}
if (pa) {
if (pa->value == 0) return a;
}
if (pb) {
if (pb->value == 1) return a;
ICHECK_NE(pb->value, 0) << "Divide by zero";
}
if (fa && fb && fb->value != 0) {
if (rtype.bits() == 32) {
return FloatImm(rtype, GetFoldResultDoubleRepr(std::floor(static_cast<float>(fa->value) /
static_cast<float>(fb->value))));
} else if (rtype.bits() == 64) {
return FloatImm(rtype, std::floor(fa->value / fb->value));
} else {
return NullOpt;
}
}
if (fa && fa->value == 0) return a;
if (fb) {
if (fb->value == 1) return a;
ICHECK_NE(fb->value, 0) << "Divide by zero";
}
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::FloorMod>(PrimExpr a, PrimExpr b) {
TVM_INDEX_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) {
ICHECK_NE(pb->value, 0) << "Divide by zero";
int64_t res = arith::floormod(pa->value, pb->value);
return IntImm(rtype, GetFoldResultInt64Repr(res, rtype));
}
if (pa) {
if (pa->value == 0) return a;
}
if (pb) {
if (pb->value == 1) return tir::make_zero(rtype);
ICHECK_NE(pb->value, 0) << "Divide by zero";
}
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Min>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) return IntImm(rtype, std::min(pa->value, pb->value));
if (fa && fb) return FloatImm(rtype, std::min(fa->value, fb->value));
});
if (a.same_as(b)) return a;
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Max>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
const DataType& rtype = a.dtype();
if (pa && pb) return IntImm(rtype, std::max(pa->value, pb->value));
if (fa && fb) return FloatImm(rtype, std::max(fa->value, fb->value));
});
if (a.same_as(b)) return a;
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::GT>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
if (pa && pb) return IntImm(DataType::UInt(1), pa->value > pb->value);
if (fa && fb) return IntImm(DataType::UInt(1), fa->value > fb->value);
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::GE>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
if (pa && pb) return IntImm(DataType::UInt(1), pa->value >= pb->value);
if (fa && fb) return IntImm(DataType::UInt(1), fa->value >= fb->value);
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::LT>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
if (pa && pb) return IntImm(DataType::UInt(1), pa->value < pb->value);
if (fa && fb) return IntImm(DataType::UInt(1), fa->value < fb->value);
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::LE>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
if (pa && pb) return IntImm(DataType::UInt(1), pa->value <= pb->value);
if (fa && fb) return IntImm(DataType::UInt(1), fa->value <= fb->value);
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::EQ>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
if (pa && pb) return IntImm(DataType::UInt(1), pa->value == pb->value);
if (fa && fb) return IntImm(DataType::UInt(1), fa->value == fb->value);
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::NE>(PrimExpr a, PrimExpr b) {
TVM_ARITH_CONST_PROPAGATION({
if (pa && pb) return IntImm(DataType::UInt(1), pa->value != pb->value);
if (fa && fb) return IntImm(DataType::UInt(1), fa->value != fb->value);
});
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::And>(PrimExpr a, PrimExpr b) {
const IntImmNode* pa = a.as<IntImmNode>();
const IntImmNode* pb = b.as<IntImmNode>();
if (pa && pa->value) return b;
if (pa && !pa->value) return a;
if (pb && pb->value) return a;
if (pb && !pb->value) return b;
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Or>(PrimExpr a, PrimExpr b) {
const IntImmNode* pa = a.as<IntImmNode>();
const IntImmNode* pb = b.as<IntImmNode>();
if (pa && pa->value) return a;
if (pa && !pa->value) return b;
if (pb && pb->value) return b;
if (pb && !pb->value) return a;
return NullOpt;
}
template <>
inline Optional<PrimExpr> TryConstFold<tir::Not>(PrimExpr a) {
const IntImmNode* pa = a.as<IntImmNode>();
if (pa) {
return IntImm(DataType::UInt(1), !(pa->value));
}
return NullOpt;
}
/*! \brief Helper namespace for symbolic value limits */
struct SymbolicLimits {
/*! \brief positive infinity */
static PrimExpr pos_inf_;
/*! \brief negative infinity */
static PrimExpr neg_inf_;
};
/*!
* \brief Opaque expression representing positive infinity.
*
* It can can only be used as parameter of by min/max
* for integer analysis and cannot be used in normal expressions.
*
* \return positive infinity.
*/
inline PrimExpr pos_inf() { return SymbolicLimits::pos_inf_; }
/*!
* \brief Check if value is positive infinity.
* \param value The value to be checked.
*
* \return The check result.
*/
inline bool is_pos_inf(const PrimExpr& value) { return value.same_as(SymbolicLimits::pos_inf_); }
/*!
* \brief Opaque expression representing negative infinity.
*
* It can can only be used as parameter of by min/max
* for integer analysis and cannot be used in normal expressions.
*
* \return negative infinity.
*/
inline PrimExpr neg_inf() { return SymbolicLimits::neg_inf_; }
/*!
* \brief Check if value is negative infinity.
* \param value The value to be checked.
*
* \return The check result.
*/
inline bool is_neg_inf(const PrimExpr& value) { return value.same_as(SymbolicLimits::neg_inf_); }
} // namespace arith
} // namespace tvm
#endif // TVM_ARITH_CONST_FOLD_H_
| https://github.com/zk-ml/tachikoma |
src/arith/constraint_extract.h | /*
* 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.
*/
/*!
* \file contraint_extract.h
*
* \brief Centralized location for extraction of constraints from a boolean expression.
*/
#ifndef TVM_ARITH_CONSTRAINT_EXTRACT_H_
#define TVM_ARITH_CONSTRAINT_EXTRACT_H_
#include <tvm/tir/expr.h>
#include <vector>
namespace tvm {
namespace arith {
/* \brief Returns constraints that are true if the expression is true.
*
* Utility to break up a boolean expression into independent
* constraints.
*
* Example: `i==5 && j==3` => `[i==5 && j==3, i==5, j==3]`
* Example: `i==5 || j==3` => `[i==5 || j==3]`
* Example: `!(i>5 || j==3)` => `[!(i==5 || j==3), i<=5, j!=3]`
*
* Intended for use in bounds analysis or simplification within a
* conditional, or identifying independent conditionals that may be
* hoisted.
*
* \param expr The expression to be analyzers
*
* \returns A vector of independent constraints
*/
std::vector<PrimExpr> ExtractConstraints(const PrimExpr& expr);
} // namespace arith
} // namespace tvm
#endif // TVM_ARITH_CONSTRAINT_EXTRACT_H_
| https://github.com/zk-ml/tachikoma |
src/arith/int_operator.h | /*
* 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.
*/
/*!
* \file int_operator.h
* \brief Additional useful operators for integer.
*/
#ifndef TVM_ARITH_INT_OPERATOR_H_
#define TVM_ARITH_INT_OPERATOR_H_
#include <limits>
#include <utility>
namespace tvm {
namespace arith {
/*!
* \brief Check if an integer op with operand x, y will overflow.
* \param x The left operand.
* \param y The left operand.
* \param min_value The minimum value of the domain.
* \param max_value The maximum value of the domain.
* \return Whether overflow can happen.
* \tparam Op The integer operator.
*/
template <typename Op>
inline bool WillOverflow(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {
return false;
}
template <>
inline bool WillOverflow<tir::AddNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {
if ((y > 0) && (x > max_value - y)) return true;
if ((y < 0) && (x < min_value - y)) return true;
return false;
}
template <>
inline bool WillOverflow<tir::SubNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {
if ((y > 0) && (x < min_value + y)) return true;
if ((y < 0) && (x > max_value + y)) return true;
return false;
}
template <>
inline bool WillOverflow<tir::MulNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {
if (y == 0) return false;
if (y > 0) {
if (x < min_value / y) return true;
if (x > max_value / y) return true;
} else {
if (y == -1 && x == std::numeric_limits<int64_t>::min()) return true;
if (x > min_value / y) return true;
if (x < max_value / y) return true;
}
return false;
}
template <>
inline bool WillOverflow<tir::ModNode>(int64_t x, int64_t y, int64_t min_value, int64_t max_value) {
return y == 0;
}
/*!
* \brief Perform trunc division of two integers.
* \param x The left operand.
* \param y The right operand.
* \return the result.
*/
inline int64_t truncdiv(int64_t x, int64_t y) { return x / y; }
/*!
* \brief Compute the truncdiv remainder of two integers.
* \param x The left operand.
* \param y The right operand.
* \return the result.
*/
inline int64_t truncmod(int64_t x, int64_t y) { return x % y; }
/*!
* \brief Perform floor division of two integers.
* \param x The left operand.
* \param y The right operand.
* \return the result.
*/
inline int64_t floordiv(int64_t x, int64_t y) {
int64_t rdiv = x / y;
int64_t rmod = x % y;
bool is_floor_div = (y >= 0 && rmod >= 0) || (y < 0 && rmod <= 0);
return is_floor_div ? rdiv : (rdiv - 1);
}
/*!
* \brief Compute the floordiv remainder of two integers.
* \param x The left operand.
* \param y The right operand.
* \return the result.
*/
inline int64_t floormod(int64_t x, int64_t y) {
int64_t rmod = x % y;
bool is_floor_div = (y >= 0 && rmod >= 0) || (y < 0 && rmod <= 0);
return is_floor_div ? rmod : rmod + y;
}
/*!
* \brief Use Extended Euclidean algorithm to solve ax + by = gcd(a, b)
* \param a The first coefficient.
* \param b The second coefficient.
* \param x The solution of x.
* \param y The solution of y.
* \return The GCD of a and b.
*/
inline int64_t ExtendedEuclidean(int64_t a, int64_t b, int64_t* x, int64_t* y) {
// Extended Euclidean algorithm
// if a < 0, the problem can be convert into
// |a|* (-x) + b * y = gcd(|a|, b)
//
// initial condition:
// a * 0 + b * 1 = b
// a * 1 + b * 0 = a
int64_t s = 0, old_s = 1;
int64_t r = b, old_r = a >= 0 ? a : -a;
// Iteration (r2 < r1):
// a * x1 + b * y1 = r1
// a * x2 + b * y2 = r2
// The above two eqs can derive the following eq (q = r1 / r2)
// a * (x1 - x2 * q) + b * (y1 - y2 * q) = r1 - r2 * q = r3
// Because r3 < r2, the iteration can eventually terminate
while (r != 0) {
int64_t q = old_r / r;
int64_t tmp = old_r;
old_r = r;
r = tmp - q * r;
tmp = old_s;
old_s = s;
s = tmp - q * s;
}
*x = a >= 0 ? old_s : -old_s;
if (b != 0) {
*y = (old_r - (*x) * a) / b;
} else {
*y = 1;
}
return old_r;
}
/*!
* \brief Take GCD of a and b.
* \param a The first operand.
* \param b The second operand.
* \return The result.
*/
inline int64_t ZeroAwareGCD(int64_t a, int64_t b) {
if (a < 0) a = -a;
if (b < 0) b = -b;
if (a < b) std::swap(a, b);
if (b == 0) return a;
// perform GCD (greatest common divisor)
// ax + by = gcd(a, b) z if a != 0, b != 0
while (a % b != 0) {
a = a % b;
std::swap(a, b);
}
return b;
}
/*!
* \brief Calculate the least common multiple for two values.
* \param a an integer number
* \param b an integer number
* \return the least common multiple.
*/
inline int64_t LeastCommonMultiple(int64_t a, int64_t b) {
int64_t x, y;
return (a * b) / ExtendedEuclidean(a, b, &x, &y);
}
} // namespace arith
} // namespace tvm
#endif // TVM_ARITH_INT_OPERATOR_H_
| https://github.com/zk-ml/tachikoma |
src/arith/interval_set.h | /*
* 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.
*/
/*!
* \file int_set.h
* \brief Internal data structure for integer set.
*/
#ifndef TVM_ARITH_INTERVAL_SET_H_
#define TVM_ARITH_INTERVAL_SET_H_
#include <tvm/arith/analyzer.h>
#include <tvm/tir/op.h>
#include <limits>
#include "const_fold.h"
namespace tvm {
namespace arith {
// Acknowledgement: IntervalSet design originates from Halide.
/*!
* \brief Symbolic interval set.
*
* \note We intentionally keep the internal of IntSet private,
as we might change it later.
*/
class IntervalSetNode : public IntSetNode {
public:
/*! \brief Minimum value in the interval. */
PrimExpr min_value;
/*! \brief Maximum value in the interval. */
PrimExpr max_value;
// visitor overload.
void VisitAttrs(tvm::AttrVisitor* v) {
v->Visit("min_value", &min_value);
v->Visit("max_value", &max_value);
}
/*! \return Whether the interval has upper bound. */
bool HasUpperBound() const { return !is_pos_inf(max_value) && !IsEmpty(); }
/*! \return Whether the interval has lower bound. */
bool HasLowerBound() const { return !is_neg_inf(min_value) && !IsEmpty(); }
/*! \return Whether the interval is a single point. */
bool IsSinglePoint() const {
if (min_value.same_as(max_value)) {
return true;
}
Analyzer analyzer;
return analyzer.CanProveEqual(min_value, max_value);
}
/*! \return whether interval represent nothing */
bool IsEmpty() const {
// during computations, either extreme could occur.
return is_pos_inf(min_value) || is_neg_inf(max_value);
}
/*! \return whether interval represent everything */
bool IsEverything() const { return is_neg_inf(min_value) && is_pos_inf(max_value); }
static constexpr const char* _type_key = "arith.IntervalSet";
TVM_DECLARE_FINAL_OBJECT_INFO(IntervalSetNode, IntSetNode);
};
/*!
* \brief Interval set used for symbolic integer analysis.
* \sa IntervalSetNode
*/
class IntervalSet : public IntSet {
public:
/*!
* \brief Make a new instance of interval set.
* \param min_value The minimum value in the interval.
* \param max_value The maximum value in the interval.
* \return The created set.
*/
TVM_DLL IntervalSet(PrimExpr min_value, PrimExpr max_value);
/*!
* \brief Create an IntervalSet that represents a single point.
* \param value The value to be represented.
* \return The result set.
*/
static IntervalSet SinglePoint(PrimExpr value) { return IntervalSet(value, value); }
/*!
* \brief Create an IntervalSet that represents everything.
* \param value The value to be represented.
* \return The result set.
*/
static IntervalSet Everything() { return IntervalSet(neg_inf(), pos_inf()); }
/*!
* \brief Create an empty eet.
* \return The result set.
*/
static IntervalSet Empty() { return IntervalSet(pos_inf(), neg_inf()); }
TVM_DEFINE_OBJECT_REF_COW_METHOD(IntervalSetNode);
TVM_DEFINE_OBJECT_REF_METHODS(IntervalSet, IntSet, IntervalSetNode);
};
/*!
* \brief Create union of two IntervalSets.
* \param analyzer The analyzer for simplification analysis.
* \param a The first set.
* \param b The second set.
* \return The result set.
*/
TVM_DLL IntervalSet Union(Analyzer* analyzer, IntervalSet a, IntervalSet b);
/*!
* \brief Create insersection of two IntervalSets.
* \param analzyer The analyzer for simplification analysis.
* \param a The first set.
* \param b The second set.
* \return The result set.
*/
TVM_DLL IntervalSet Intersect(Analyzer* analzyer, IntervalSet a, IntervalSet b);
} // namespace arith
} // namespace tvm
#endif // TVM_ARITH_INTERVAL_SET_H_
| https://github.com/zk-ml/tachikoma |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.