Skip to main content

tvm_ffi/
device.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//! The device stream of the FFI environment: [`current_stream`] and [`with_stream`].
20
21use crate::error::Result;
22use crate::type_traits::AnyCompatible;
23use tvm_ffi_sys::dlpack::DLDevice;
24use tvm_ffi_sys::{TVMFFIAny, TVMFFITypeIndex as TypeIndex};
25use tvm_ffi_sys::{TVMFFIEnvGetStream, TVMFFIEnvSetStream, TVMFFIStreamHandle};
26
27/// The current stream of `device`, as the caller or [`with_stream`] set it;
28/// null if none is set.
29pub fn current_stream(device: &DLDevice) -> TVMFFIStreamHandle {
30    unsafe { TVMFFIEnvGetStream(device.device_type, device.device_id) }
31}
32
33/// Call `f` with the device stream temporarily set to `stream`.
34///
35/// The previous stream is restored however `f` exits: when it returns a
36/// value, when it returns an error, and when it panics.
37///
38/// # Safety
39///
40/// `stream` must be a valid stream handle for the given device, or null.
41pub unsafe fn with_stream<T>(
42    device: &DLDevice,
43    stream: TVMFFIStreamHandle,
44    f: impl FnOnce() -> Result<T>,
45) -> Result<T> {
46    let mut prev_stream: TVMFFIStreamHandle = std::ptr::null_mut();
47    unsafe {
48        crate::check_safe_call!(TVMFFIEnvSetStream(
49            device.device_type,
50            device.device_id,
51            stream,
52            &mut prev_stream as *mut TVMFFIStreamHandle
53        ))?;
54    }
55    let restore = RestoreStream {
56        device: *device,
57        stream: prev_stream,
58    };
59    let result = f();
60    let restored = restore.restore();
61    let value = result?;
62    restored?;
63    Ok(value)
64}
65
66/// Restores a device's previous stream when dropped, so that an unwinding
67/// panic in `with_stream`'s closure still restores it.
68struct RestoreStream {
69    device: DLDevice,
70    stream: TVMFFIStreamHandle,
71}
72
73impl RestoreStream {
74    fn set(&self) -> i32 {
75        unsafe {
76            TVMFFIEnvSetStream(
77                self.device.device_type,
78                self.device.device_id,
79                self.stream,
80                std::ptr::null_mut(),
81            )
82        }
83    }
84
85    /// Restores the stream now, reporting a failure.
86    fn restore(self) -> Result<()> {
87        let restore = std::mem::ManuallyDrop::new(self);
88        crate::check_safe_call!(restore.set())
89    }
90}
91
92impl Drop for RestoreStream {
93    fn drop(&mut self) {
94        // Only reached while unwinding; a failure cannot be reported there.
95        self.set();
96    }
97}
98
99unsafe impl AnyCompatible for DLDevice {
100    #[inline]
101    unsafe fn is_undefined(field: *const Self) -> bool {
102        // No device type is zero.
103        unsafe { *std::ptr::addr_of!((*field).device_type) == 0 }
104    }
105
106    fn type_str() -> String {
107        // make it consistent with c++ representation
108        "Device".to_string()
109    }
110
111    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
112        data.type_index = TypeIndex::kTVMFFIDevice as i32;
113        data.small_str_len = 0;
114        data.data_union.v_uint64 = 0;
115        data.data_union.v_device = *src;
116    }
117
118    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
119        data.type_index = TypeIndex::kTVMFFIDevice as i32;
120        data.small_str_len = 0;
121        data.data_union.v_int64 = 0;
122        data.data_union.v_device = src;
123    }
124
125    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
126        data.type_index == TypeIndex::kTVMFFIDevice as i32
127    }
128
129    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
130        unsafe { data.data_union.v_device }
131    }
132
133    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
134        unsafe { data.data_union.v_device }
135    }
136
137    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
138        if data.type_index == TypeIndex::kTVMFFIDevice as i32 {
139            return Ok(unsafe { data.data_union.v_device });
140        }
141        let text = unsafe { <crate::String as AnyCompatible>::try_cast_from_any_view(data)? };
142        parse_device(text.as_str()).ok_or(())
143    }
144}
145
146/// The device a string such as `"cuda:1"` names, as C++ converts one: a
147/// device name, an optional `:index`, and anything after a space ignored.
148#[cold]
149fn parse_device(text: &str) -> Option<DLDevice> {
150    use tvm_ffi_sys::dlpack::DLDeviceType::*;
151    let text = text.split(' ').next().unwrap_or_default();
152    let (name, index) = match text.split_once(':') {
153        Some((name, index)) => (name, Some(index)),
154        None => (text, None),
155    };
156    let device_type = match name {
157        "cpu" => kDLCPU,
158        "cuda" => kDLCUDA,
159        "opencl" => kDLOpenCL,
160        "vulkan" => kDLVulkan,
161        "metal" | "mps" => kDLMetal,
162        "vpi" => kDLVPI,
163        "rocm" => kDLROCM,
164        "ext_dev" => kDLExtDev,
165        "oneapi" | "xpu" => kDLOneAPI,
166        "hexagon" => kDLHexagon,
167        "wgpu" | "webgpu" => kDLWebGPU,
168        "maia" => kDLMAIA,
169        "trn" => kDLTrn,
170        "tpu" => kDLTPU,
171        "tpu_host" => kDLTPUHost,
172        "ascend" => kDLAscend,
173        _ => return None,
174    };
175    let device_id = match index {
176        // Digits only, as C++ parses them: no sign.
177        Some(index) if !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit()) => {
178            index.parse::<i32>().ok()?
179        }
180        Some(_) => return None,
181        None => 0,
182    };
183    Some(DLDevice {
184        device_type: device_type as i32,
185        device_id,
186    })
187}