tvm_ffi/
device.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
 * 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::error::Result;
use crate::type_traits::AnyCompatible;
use tvm_ffi_sys::dlpack::DLDevice;
use tvm_ffi_sys::{TVMFFIAny, TVMFFITypeIndex as TypeIndex};
use tvm_ffi_sys::{TVMFFIEnvGetStream, TVMFFIEnvSetStream, TVMFFIStreamHandle};

/// Get the current stream for a device
pub fn current_stream(device: &DLDevice) -> TVMFFIStreamHandle {
    unsafe { TVMFFIEnvGetStream(device.device_type as i32, device.device_id) }
}
/// Call `f` with the device stream temporarily set to `stream`.
///
/// The previous stream is restored however `f` exits: when it returns a
/// value, when it returns an error, and when it panics.
///
/// # Safety
///
/// `stream` must be a valid stream handle for the given device, or null.
pub unsafe fn with_stream<T>(
    device: &DLDevice,
    stream: TVMFFIStreamHandle,
    f: impl FnOnce() -> Result<T>,
) -> Result<T> {
    let mut prev_stream: TVMFFIStreamHandle = std::ptr::null_mut();
    unsafe {
        crate::check_safe_call!(TVMFFIEnvSetStream(
            device.device_type as i32,
            device.device_id,
            stream,
            &mut prev_stream as *mut TVMFFIStreamHandle
        ))?;
    }
    let restore = RestoreStream {
        device: *device,
        stream: prev_stream,
    };
    let result = f();
    let restored = restore.restore();
    let value = result?;
    restored?;
    Ok(value)
}

/// Restores a device's previous stream when dropped, so that an unwinding
/// panic in `with_stream`'s closure still restores it.
struct RestoreStream {
    device: DLDevice,
    stream: TVMFFIStreamHandle,
}

impl RestoreStream {
    fn set(&self) -> i32 {
        unsafe {
            TVMFFIEnvSetStream(
                self.device.device_type as i32,
                self.device.device_id,
                self.stream,
                std::ptr::null_mut(),
            )
        }
    }

    /// Restores the stream now, reporting a failure.
    fn restore(self) -> Result<()> {
        let restore = std::mem::ManuallyDrop::new(self);
        crate::check_safe_call!(restore.set())
    }
}

impl Drop for RestoreStream {
    fn drop(&mut self) {
        // Only reached while unwinding; a failure cannot be reported there.
        self.set();
    }
}

/// AnyCompatible for DLDevice
unsafe impl AnyCompatible for DLDevice {
    #[inline]
    unsafe fn is_undefined(field: *const Self) -> bool {
        // No device type is zero; read as an integer, since zero is no `DLDeviceType`.
        *std::ptr::addr_of!((*field).device_type).cast::<u32>() == 0
    }

    fn type_str() -> String {
        // make it consistent with c++ representation
        "Device".to_string()
    }

    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIDevice as i32;
        data.small_str_len = 0;
        data.data_union.v_uint64 = 0;
        data.data_union.v_device = *src;
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIDevice as i32;
        data.small_str_len = 0;
        data.data_union.v_int64 = 0;
        data.data_union.v_device = src;
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        return data.type_index == TypeIndex::kTVMFFIDevice as i32;
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        data.data_union.v_device
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        data.data_union.v_device
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFIDevice as i32 {
            Ok(data.data_union.v_device)
        } else {
            Err(())
        }
    }
}