Skip to content

Commit 5563b72

Browse files
nhynestqchen
authored andcommitted
Add rust runtime (#1597)
1 parent 6330797 commit 5563b72

28 files changed

+3208
-3
lines changed

.gitignore

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,8 @@ ENV/
9191
*~
9292
*.pyc
9393
*~
94-
build
9594
config.mk
9695
config.cmake
97-
build_*
9896
Win32
9997
*.dir
10098
perf
@@ -187,7 +185,6 @@ tvm_u.*
187185
tvm_t.*
188186
# Mac OS X
189187
.DS_Store
190-
build*
191188

192189
# Jetbrain
193190
.idea

rust/.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Cargo.lock
2+
target/
3+
**/*.rs.bk

rust/.rustfmt.toml

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
max_width = 100
2+
hard_tabs = false
3+
tab_spaces = 2
4+
newline_style = "Auto"
5+
use_small_heuristics = "Default"
6+
indent_style = "Block"
7+
wrap_comments = false
8+
comment_width = 80
9+
normalize_comments = false
10+
format_strings = false
11+
format_macro_matchers = false
12+
format_macro_bodies = true
13+
empty_item_single_line = true
14+
struct_lit_single_line = true
15+
fn_single_line = false
16+
where_single_line = false
17+
imports_indent = "Block"
18+
imports_layout = "Mixed"
19+
merge_imports = true
20+
reorder_imports = true
21+
reorder_modules = true
22+
reorder_impl_items = false
23+
type_punctuation_density = "Wide"
24+
space_before_colon = false
25+
space_after_colon = true
26+
spaces_around_ranges = false
27+
binop_separator = "Front"
28+
remove_nested_parens = true
29+
combine_control_expr = true
30+
struct_field_align_threshold = 0
31+
match_arm_blocks = true
32+
force_multiline_blocks = false
33+
fn_args_density = "Tall"
34+
brace_style = "SameLineWhere"
35+
control_brace_style = "AlwaysSameLine"
36+
trailing_semicolon = true
37+
trailing_comma = "Vertical"
38+
match_block_trailing_comma = false
39+
blank_lines_upper_bound = 1
40+
blank_lines_lower_bound = 0
41+
edition = "Edition2015"
42+
merge_derives = true
43+
use_try_shorthand = true
44+
use_field_init_shorthand = false
45+
force_explicit_abi = true
46+
condense_wildcard_suffixes = false
47+
color = "Auto"
48+
required_version = "0.99.4"
49+
unstable_features = false
50+
disable_all_formatting = false
51+
skip_children = false
52+
hide_parse_errors = false
53+
error_on_line_overflow = false
54+
error_on_unformatted = false
55+
report_todo = "Never"
56+
report_fixme = "Never"
57+
ignore = []
58+
emit_mode = "Files"
59+
make_backup = false

rust/.travis.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
language: rust
2+
rust:
3+
- nightly
4+
matrix:
5+
fast_finish: true

rust/Cargo.toml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
[package]
2+
name = "tvm"
3+
version = "0.1.0"
4+
license = "Apache-2.0"
5+
description = "TVM Rust runtime"
6+
repository = "https://github.com/dmlc/tvm"
7+
readme = "README.md"
8+
keywords = ["tvm", "nnvm"]
9+
categories = ["api-bindings", "science"]
10+
authors = ["Nick Hynes <[email protected]>"]
11+
12+
[features]
13+
default = ["nom/std"]
14+
sgx = ["nom/alloc"]
15+
16+
[dependencies]
17+
bounded-spsc-queue = "0.4.0"
18+
error-chain = { version = "0.12.0", default-features = false }
19+
itertools = "0.7.8"
20+
lazy_static = "1.1.0"
21+
ndarray = "0.11.2"
22+
nom = {version = "4.0.0", default-features = false }
23+
serde = "1.0.59"
24+
serde_derive = "1.0.79"
25+
serde_json = "1.0.17"
26+
27+
[target.'cfg(not(target_env = "sgx"))'.dependencies]
28+
num_cpus = "1.8.0"

rust/src/errors.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#[cfg(target_env = "sgx")]
2+
use alloc::alloc;
3+
#[cfg(not(target_env = "sgx"))]
4+
use std::alloc;
5+
use std::num;
6+
7+
use ndarray;
8+
use serde_json;
9+
10+
error_chain! {
11+
errors {
12+
TryFromTVMRetValueError(expected: String, actual: i64) {
13+
description("mismatched types while downcasting TVMRetValue")
14+
display("invalid downcast: expected `{}` but was `{}`", expected, actual)
15+
}
16+
17+
GraphFormatError(msg: String) {
18+
description("unable to load graph")
19+
display("could not load graph json: {}", msg)
20+
}
21+
22+
LoadGraphParamsError(msg: String) {
23+
description("unable to load graph params")
24+
display("could not load graph params: {}", msg)
25+
}
26+
}
27+
foreign_links {
28+
Alloc(alloc::AllocErr);
29+
GraphDeserialize(serde_json::Error);
30+
ParseInt(num::ParseIntError);
31+
ShapeError(ndarray::ShapeError);
32+
}
33+
}
34+
35+
impl From<alloc::LayoutErr> for Error {
36+
fn from(_err: alloc::LayoutErr) -> Error {
37+
Error::from_kind(ErrorKind::Msg("Layout error".to_string()))
38+
}
39+
}

rust/src/lib.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
//! This crate is an implementation of the TVM runtime for modules compiled with `--system-lib`.
2+
//! It's mainly useful for compiling to WebAssembly and SGX,
3+
//! but also native if you prefer Rust to C++.
4+
//!
5+
//! For TVM graphs, the entrypoint to this crate is `runtime::GraphExecutor`.
6+
//! Single-function modules are used via the `packed_func!` macro after obtaining
7+
//! the function from `runtime::SystemLibModule`
8+
//!
9+
//! The main entrypoints to this crate are `GraphExecutor`
10+
//! For examples of use, please refer to the multi-file tests in the `tests` directory.
11+
12+
#![feature(
13+
alloc,
14+
allocator_api,
15+
box_syntax,
16+
extern_prelude,
17+
fn_traits,
18+
try_from,
19+
unboxed_closures,
20+
vec_remove_item
21+
)]
22+
23+
#[cfg(target_env = "sgx")]
24+
extern crate alloc;
25+
extern crate bounded_spsc_queue;
26+
#[cfg(target_env = "sgx")]
27+
extern crate core;
28+
#[macro_use]
29+
extern crate error_chain;
30+
#[macro_use]
31+
extern crate itertools;
32+
#[macro_use]
33+
extern crate lazy_static;
34+
extern crate ndarray;
35+
#[macro_use]
36+
extern crate nom;
37+
#[cfg(not(target_env = "sgx"))]
38+
extern crate num_cpus;
39+
extern crate serde;
40+
#[macro_use]
41+
extern crate serde_derive;
42+
extern crate serde_json;
43+
44+
pub mod ffi {
45+
#![allow(
46+
non_camel_case_types,
47+
non_snake_case,
48+
non_upper_case_globals,
49+
unused
50+
)]
51+
52+
pub mod runtime {
53+
use std::os::raw::{c_char, c_int, c_void};
54+
55+
include!(concat!(
56+
env!("CARGO_MANIFEST_DIR"),
57+
"/src/runtime/c_runtime_api.rs"
58+
));
59+
60+
pub type BackendPackedCFunc =
61+
extern "C" fn(args: *const TVMValue, type_codes: *const c_int, num_args: c_int) -> c_int;
62+
}
63+
}
64+
65+
pub mod errors;
66+
pub mod runtime;
67+
68+
pub use errors::*;

rust/src/runtime/allocator.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#[cfg(target_env = "sgx")]
2+
use alloc::alloc::{self, Layout};
3+
#[cfg(not(target_env = "sgx"))]
4+
use std::alloc::{self, Layout};
5+
6+
use errors::*;
7+
8+
const DEFAULT_ALIGN_BYTES: usize = 4;
9+
10+
#[derive(PartialEq, Eq)]
11+
pub struct Allocation {
12+
layout: Layout,
13+
ptr: *mut u8,
14+
}
15+
16+
impl Allocation {
17+
/// Allocates a chunk of memory of `size` bytes with optional alignment.
18+
pub fn new(size: usize, align: Option<usize>) -> Result<Self> {
19+
let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES);
20+
let layout = Layout::from_size_align(size, alignment)?;
21+
let ptr = unsafe { alloc::alloc(layout.clone()) };
22+
if ptr.is_null() {
23+
alloc::handle_alloc_error(layout);
24+
}
25+
Ok(Self {
26+
ptr: ptr,
27+
layout: layout,
28+
})
29+
}
30+
31+
pub fn as_mut_ptr(&self) -> *mut u8 {
32+
self.ptr
33+
}
34+
35+
/// Returns the size of the Allocation in bytes.
36+
pub fn size(&self) -> usize {
37+
self.layout.size()
38+
}
39+
40+
/// Returns the byte alignment of the Allocation.
41+
pub fn align(&self) -> usize {
42+
self.layout.align()
43+
}
44+
}
45+
46+
impl Drop for Allocation {
47+
fn drop(&mut self) {
48+
unsafe {
49+
alloc::dealloc(self.ptr, self.layout.clone());
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)