Skip to main content

Crate tvm_tirx

Crate tvm_tirx 

Source
Expand description

The TIRx compiler in Rust: its IR objects over TVM FFI, and the definition of new types, operators and passes that extend it.

The modules:

  • ir: the IR shared by every dialect, with the primitive expressions in ir::prim and the pass infrastructure in ir::transform.
  • tirx: tensor programs: functions, tensor types, layouts, tile instructions, passes and analyses.
  • sym: symbolic integer analysis.
  • target: compilation targets.
  • backend: backend objects, such as the attributes of CUDA instructions.
  • runtime: runtime objects and queries, and tensor allocation.
  • codegen: compiling IR modules into runtime modules.
  • script: printing IR objects as TVMScript.

§Using the crate

The crate links libtvm_tirx_compiler, which the build script finds through tvm-tirx-config --libdir; tvm-tirx-config and tvm-ffi-config must be on PATH when the crate is built. Many of its APIs call global functions of that library, as target::Target::new calls target.Target, and any global function can also be called through tvm_ffi::Function::get_global. A program that calls them only through tvm_ffi, without an API of this crate, must link the library itself (tvm-tirx-config --libs compiler).

use tvm_tirx::target::Target;
use tvm_tirx::tvm_ffi::{Function, String};

let target = Target::new("llvm")?;
assert_eq!(target.kind.name()?, "llvm");

let same = Function::get_global("target.Target")?.call_tuple((String::from("llvm"),))?;
assert_eq!(Target::try_from(same)?.kind.name()?, "llvm");

A handle such as ir::Expr is a reference-counted pointer to its object, ir::ExprObj, so cloning it does not copy the IR. A constructor new checks its arguments and fills in defaults, and returns a Result when a check can fail; from_fields stores the fields as given.

§Defining operators and types

Operators and types are defined in a tvm_ffi::static_init_block!, which runs when the program or library loads: an operator by an ir::OpDef chain, a type by [tvm_ffi::rs_object] and ir::register_type.

use tvm_tirx::ir::op_attr::CALL_EFFECT_KIND;
use tvm_tirx::ir::sig::{self, IntExpr};
use tvm_tirx::ir::{register_type, CallEffectKind, CallObj, Op, OpDef, Type};
use tvm_tirx::tvm_ffi::{self, Result};

fn index_type(call: &CallObj) -> Result<Type> {
    Ok(call.args[0].ty.clone())
}

tvm_ffi::static_init_block! {
    OpDef::new("my_ext.clamp", "Clamp an index to the range `[0, bound)`.")
        .signature((
            sig::arg::<IntExpr>("index", "The index."),
            sig::arg::<IntExpr>("bound", "The exclusive upper bound."),
        ))
        .set_infer_type(index_type)
        .set_attr(CALL_EFFECT_KIND, CallEffectKind::Pure);
    register_type::<PairType>()?;
}

let clamp = Op::get("my_ext.clamp")?;

A type extends ir::TypeObj; its fields are reflected, so Python and the TVMScript printer see them. The generated code names tvm_ffi, which use tvm_tirx::tvm_ffi brings into scope.

use tvm_tirx::ir::{PrimType, Type, TypeObj, UNKNOWN_LOC};
use tvm_tirx::tvm_ffi::{self, rs_object, IntoArg, ObjectRefCore};

#[rs_object(type_key = "my_ext.PairType", final, immutable)]
pub struct PairTypeObj {
    base_: TypeObj,
    pub first: Type,
    pub second: Type,
    #[reflect(seq_hash_ignore)]
    pub note: tvm_ffi::String,
}

#[derive(Clone, tvm_ffi::derive::ObjectRef)]
#[object_ref(parent = Type)]
pub struct PairType {
    data_: tvm_ffi::ObjectArc<PairTypeObj>,
}

impl PairType {
    pub fn new(first: impl IntoArg<Type>, second: impl IntoArg<Type>) -> Self {
        let (first, second) = (first.into_owned(), second.into_owned());
        Self::from_object(PairTypeObj::new(TypeObj::new(UNKNOWN_LOC.into()), first, second, ""))
    }
}

fn main() {
    let pair = PairType::new(PrimType::int(32), PrimType::float(32));
    let ty: Type = pair.into();
    assert!(ty.downcast_ref::<PairTypeObj>().is_some());
}

§The library Python loads

The crate is also built as libtvm_tirx_rust, which import tvm_tirx loads, so Python uses the operators and types the crate defines as it uses the native ones. A cdylib of operators of its own, such as examples/define_ir.rs, registers them when Python loads it; a crate it depends on but never names is not linked in, so name it, as use my_ops as _; does.

§Generated code

The code between // tvm-ffi-stubgen(begin) and // tvm-ffi-stubgen(end) is generated, and the rest is hand-written. Regenerate it with the tvm-ffi-stubgen of 3rdparty/tvm-ffi after rebuilding libtvm_tirx_compiler (--check only reports stale blocks):

tvm-ffi-stubgen rust/tvm-tirx/src --target rust --dlls build/lib/libtvm_tirx_compiler.so

§Tests

Build libtvm_tirx_compiler first. The tests of src/<path>.rs are in tests/<path>.rs:

uv run --no-sync cargo test --manifest-path rust/Cargo.toml

Re-exports§

pub use tvm_ffi;

Modules§

backend
Backends. Each submodule holds the objects of one backend, such as the attributes of the CUDA instructions in cuda.
codegen
Code generation. build_module compiles an IRModule into a runtime Module with the code generator of the target’s kind, and llvm queries the LLVM backend.
ir
The IR shared by every dialect. Expressions (Expr), statements (Stmt) and types (Type) are the three node hierarchies; functions are expressions, and an IRModule binds them to global names, the unit of compilation that the passes of transform rewrite.
runtime
Runtime objects and queries. A MemoryScope names the memory a pointer or tensor lives in; the functions allocate tensors and query devices and the runtime.
script
TVMScript printing. script prints an IR object as TVMScript, the Python-syntax text form of the IR.
sym
Symbolic integer analysis. An Analyzer proves, bounds and simplifies integer expressions under the facts of a ConstraintContext; int_set and iter_affine_map describe the values and the iterator structure of index expressions.
target
Compilation targets. A Target describes the device and options code is compiled for, as an instance of a registered TargetKind; it is created from a tag, a kind name or a config.
tirx
Tensor programs. A Function computes on tensors, variables typed by a TensorType whose Layout maps their indices to memory and threads; tile instructions are dispatched per ThreadScope, and transform and analysis hold the passes and analyses.

Macros§

def_expr_op_over_loads
Add the primitive-expression operators to an existing reference wrapper.