Skip to main content

tvm_tirx/
runtime.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Runtime objects and queries. A [`MemoryScope`] names the memory a pointer or tensor lives in;
21//! the functions allocate tensors and query devices and the runtime.
22
23// tvm-ffi-stubgen(file): mod(missing_docs = allow)
24// No `prefix`: only the objects with a block below are bound, not all of `runtime`.
25// Names the hand-written wrappers use: the import section keeps them even when no generated block
26// does.
27// tvm-ffi-stubgen(import): tvm_ffi::Any
28// tvm-ffi-stubgen(import): tvm_ffi::DLDataType
29// tvm-ffi-stubgen(import): tvm_ffi::DLDevice
30// tvm-ffi-stubgen(import): tvm_ffi::Result
31// tvm-ffi-stubgen(import): tvm_ffi::Shape
32// tvm-ffi-stubgen(import): tvm_ffi::String
33// tvm-ffi-stubgen(import): tvm_ffi::Tensor
34// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
35// tvm-ffi-stubgen(import): std::borrow::Borrow
36
37// tvm-ffi-stubgen(begin): import-section
38use std::borrow::Borrow;
39use tvm_ffi::Any;
40use tvm_ffi::DLDataType;
41use tvm_ffi::DLDevice;
42use tvm_ffi::IntoArg;
43use tvm_ffi::ObjectArc;
44use tvm_ffi::Result;
45use tvm_ffi::Shape;
46use tvm_ffi::String;
47use tvm_ffi::Tensor;
48use tvm_ffi::enum_ref::EnumObj;
49// tvm-ffi-stubgen(end)
50
51// `ir.PtrType.storage_scope` refers to this type.
52/// A registered memory space, such as `global` or `shared`, that a pointer or tensor lives in.
53///
54/// Registration order has no meaning, and a backend must support a scope before it can allocate
55/// storage in it; [`EnumDef::new`](tvm_ffi::reflection::EnumDef::new) adds one, and
56/// [`EnumRef::get`](tvm_ffi::EnumRef::get) looks one up by name.
57// tvm-ffi-stubgen(begin): object/runtime.MemoryScope
58#[allow(missing_docs)]
59#[repr(C)]
60#[derive(tvm_ffi::derive::ObjectRef, Clone)]
61pub struct MemoryScope {
62    data_: ObjectArc<MemoryScopeObj>,
63}
64
65/// The object behind [`MemoryScope`].
66// Complete: reflected fields fill [48, 48) exactly.
67#[allow(missing_docs)]
68#[repr(C)]
69#[derive(tvm_ffi::derive::Object)]
70#[object(type_key = "runtime.MemoryScope", final, immutable)]
71pub struct MemoryScopeObj {
72    base_: EnumObj,
73}
74
75const _: () = {
76    assert!(::core::mem::size_of::<MemoryScopeObj>() == 48);
77    assert!(::core::mem::align_of::<MemoryScopeObj>() == 8);
78};
79
80impl tvm_ffi::EnumRef for MemoryScope {}
81// tvm-ffi-stubgen(end)
82
83/// Allocate an uninitialized tensor on `device`, in the memory scope `mem_scope` or the global one
84/// (`runtime.TensorAllocWithScope`).
85///
86/// # Errors
87///
88/// Returns an error if the allocator of `device` does not support `mem_scope`; the CPU one supports
89/// only the global scope.
90///
91/// # Examples
92///
93/// ```
94/// use tvm_tirx::ir::dtype;
95/// use tvm_tirx::runtime;
96/// use tvm_tirx::tvm_ffi::{DLDevice, DLDeviceType};
97///
98/// let cpu = DLDevice::new(DLDeviceType::kDLCPU, 0);
99/// let buffer = runtime::empty(&[2, 8], dtype::float(32), cpu, None)?;
100///
101/// let bytes = runtime::create_view(&buffer, &[64], dtype::int(8), 0)?;
102/// assert_eq!(bytes.shape(), &[64]);
103///
104/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
105/// ```
106pub fn empty(
107    shape: &[i64],
108    dtype: DLDataType,
109    device: DLDevice,
110    mem_scope: Option<&MemoryScope>,
111) -> Result<Tensor> {
112    tvm_ffi::cached_global_func!("runtime.TensorAllocWithScope")
113        .call_tuple((Shape::from(shape), dtype, device, mem_scope.cloned()))?
114        .try_into()
115}
116
117/// Create a view of the storage of `source`, `relative_byte_offset` bytes past its data, with
118/// another shape and data type (`runtime.TensorCreateView`).
119///
120/// # Errors
121///
122/// Returns an error if `source` is not contiguous or the view does not fit in its storage.
123pub fn create_view(
124    source: impl IntoArg<Tensor>,
125    shape: &[i64],
126    dtype: DLDataType,
127    relative_byte_offset: u64,
128) -> Result<Tensor> {
129    tvm_ffi::cached_global_func!("runtime.TensorCreateView")
130        .call_tuple((source.into_arg().borrow(), Shape::from(shape), dtype, relative_byte_offset))?
131        .try_into()
132}
133
134/// Return the attribute `name` of `device`, such as `exist` or `max_threads_per_block`, or `None`
135/// when the device does not report it (`runtime.GetDeviceAttr`).
136///
137/// # Errors
138///
139/// Returns an error if the runtime of the device is not enabled and `name` is not `exist`, which is
140/// then `false`.
141pub fn get_device_attr(device: DLDevice, name: &str) -> Result<Option<Any>> {
142    let value = tvm_ffi::cached_global_func!("runtime.GetDeviceAttr").call_tuple((
143        device.device_type,
144        device.device_id,
145        String::from(name),
146    ))?;
147    Ok((!value.is_none()).then_some(value))
148}
149
150/// Return whether the runtime of the device or target kind `target` (`"cpu"`, `"cuda"`,
151/// `"llvm"`...) is enabled (`runtime.RuntimeEnabled`).
152pub fn enabled(target: &str) -> Result<bool> {
153    tvm_ffi::cached_global_func!("runtime.RuntimeEnabled")
154        .call_tuple((String::from(target),))?
155        .try_into()
156}
157
158/// Return the number of threads the runtime thread pool uses (`runtime.NumThreads`).
159pub fn num_threads() -> Result<i32> {
160    tvm_ffi::cached_global_func!("runtime.NumThreads").call_tuple(())?.try_into()
161}
162
163// The CUDA queries are in the CUDA runtime library, which may not be built or loaded: they are
164// looked up when called, and their absence is an error.
165
166/// Return the number of CUDA devices (`runtime.GetCudaDeviceCount`).
167///
168/// # Errors
169///
170/// Returns an error if the CUDA runtime is not built or loaded.
171pub fn get_cuda_device_count() -> Result<i32> {
172    tvm_ffi::Function::get_global("runtime.GetCudaDeviceCount")?.call_tuple(())?.try_into()
173}
174
175/// Return the free and total memory of the current CUDA device, as a message
176/// (`runtime.GetCudaFreeMemory`).
177///
178/// # Errors
179///
180/// Returns an error if the CUDA runtime is not built or loaded.
181pub fn get_cuda_free_memory() -> Result<String> {
182    tvm_ffi::Function::get_global("runtime.GetCudaFreeMemory")?.call_tuple(())?.try_into()
183}