context.rs 9.03 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * 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.
 */

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
//! Provides [`TVMContext`] and related device specific queries.
//!
//! Create a new context by device type (cpu is 1) and device id.
//!
//! # Example
//!
//! ```
//! let ctx = TVMContext::new(1, 0);
//! let cpu0 = TVMContext::cpu(0);
//! assert_eq!(ctx, cpu0);
//! ```
//!
//! Or from a supported device name.
//!
//! ```
//! let cpu0 = TVMContext::from("cpu");
//! println!("{}", cpu0);
//! ```

use std::{
40
    convert::TryInto,
41 42 43 44 45
    fmt::{self, Display, Formatter},
    os::raw::c_void,
    ptr,
};

46 47
use failure::Error;

48
use tvm_common::ffi;
49

50
use crate::{function, TVMArgValue};
51 52

/// Device type can be from a supported device name. See the supported devices
53
/// in [TVM](https://github.com/apache/incubator-tvm).
54 55 56 57 58 59 60 61 62
///
/// ## Example
///
/// ```
/// let cpu = TVMDeviceType::from("cpu");
/// println!("device is: {}", cpu);
///```

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63
pub struct TVMDeviceType(pub i64);
64 65 66 67 68 69 70 71

impl Default for TVMDeviceType {
    /// default device is cpu.
    fn default() -> Self {
        TVMDeviceType(1)
    }
}

72
impl From<TVMDeviceType> for ffi::DLDeviceType {
73 74
    fn from(device_type: TVMDeviceType) -> Self {
        match device_type.0 {
75 76 77 78 79 80 81 82 83
            1 => ffi::DLDeviceType_kDLCPU,
            2 => ffi::DLDeviceType_kDLGPU,
            3 => ffi::DLDeviceType_kDLCPUPinned,
            4 => ffi::DLDeviceType_kDLOpenCL,
            7 => ffi::DLDeviceType_kDLVulkan,
            8 => ffi::DLDeviceType_kDLMetal,
            9 => ffi::DLDeviceType_kDLVPI,
            10 => ffi::DLDeviceType_kDLROCM,
            12 => ffi::DLDeviceType_kDLExtDev,
84 85 86 87 88
            _ => panic!("device type not found!"),
        }
    }
}

89 90
impl From<ffi::DLDeviceType> for TVMDeviceType {
    fn from(device_type: ffi::DLDeviceType) -> Self {
91
        match device_type {
92 93 94 95 96 97 98 99 100
            ffi::DLDeviceType_kDLCPU => TVMDeviceType(1),
            ffi::DLDeviceType_kDLGPU => TVMDeviceType(2),
            ffi::DLDeviceType_kDLCPUPinned => TVMDeviceType(3),
            ffi::DLDeviceType_kDLOpenCL => TVMDeviceType(4),
            ffi::DLDeviceType_kDLVulkan => TVMDeviceType(7),
            ffi::DLDeviceType_kDLMetal => TVMDeviceType(8),
            ffi::DLDeviceType_kDLVPI => TVMDeviceType(9),
            ffi::DLDeviceType_kDLROCM => TVMDeviceType(10),
            ffi::DLDeviceType_kDLExtDev => TVMDeviceType(12),
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 142 143
            _ => panic!("device type not found!"),
        }
    }
}

impl Display for TVMDeviceType {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                TVMDeviceType(1) => "cpu",
                TVMDeviceType(2) => "gpu",
                TVMDeviceType(3) => "cpu_pinned",
                TVMDeviceType(4) => "opencl",
                TVMDeviceType(8) => "meta",
                TVMDeviceType(9) => "vpi",
                TVMDeviceType(10) => "rocm",
                TVMDeviceType(_) => "rpc",
            }
        )
    }
}

impl<'a> From<&'a str> for TVMDeviceType {
    fn from(type_str: &'a str) -> Self {
        match type_str {
            "cpu" => TVMDeviceType(1),
            "llvm" => TVMDeviceType(1),
            "stackvm" => TVMDeviceType(1),
            "gpu" => TVMDeviceType(2),
            "cuda" => TVMDeviceType(2),
            "nvptx" => TVMDeviceType(2),
            "cl" => TVMDeviceType(4),
            "opencl" => TVMDeviceType(4),
            "metal" => TVMDeviceType(8),
            "vpi" => TVMDeviceType(9),
            "rocm" => TVMDeviceType(10),
            _ => panic!("{:?} not supported!", type_str),
        }
    }
}

144 145 146 147 148 149
impl<'a> From<&TVMDeviceType> for TVMArgValue<'a> {
    fn from(dev: &TVMDeviceType) -> Self {
        Self::Int(dev.0)
    }
}

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
/// Represents the underlying device context. Default is cpu.
///
/// ## Examples
///
/// ```
/// let ctx = TVMContext::from("gpu");
/// assert!(ctx.exist());
///
/// ```
///
/// It is possible to query the underlying context as follows
///
/// ```
/// println!("maximun threads per block: {}", ctx.max_threads_per_block());
/// println!("compute version: {}", ctx.compute_version());
/// ```
#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq)]
pub struct TVMContext {
    /// Supported device types
    pub device_type: TVMDeviceType,
    /// Device id
171
    pub device_id: i32,
172 173 174 175
}

impl TVMContext {
    /// Creates context from device type and id.
176
    pub fn new(device_type: TVMDeviceType, device_id: i32) -> Self {
177
        TVMContext {
178 179
            device_type,
            device_id,
180 181 182 183 184 185 186 187
        }
    }
}

macro_rules! impl_ctxs {
    ($(($ctx:ident, $dldevt:expr));+) => {
        $(
            impl TVMContext {
188
                pub fn $ctx(device_id: i32) -> Self {
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
                    Self::new(TVMDeviceType($dldevt), device_id)
                }
            }
        )+
    };
}

impl_ctxs!((cpu, 1);
            (gpu, 2);
            (nvptx, 2);
            (cuda, 2);
            (cpu_pinned, 3);
            (cl, 4);
            (opencl, 4);
            (metal, 8);
            (vpi, 9);
            (rocm, 10);
            (opengl, 11);
            (ext_dev, 12));

impl<'a> From<&'a str> for TVMContext {
    fn from(target: &str) -> Self {
        TVMContext::new(TVMDeviceType::from(target), 0)
    }
}

impl TVMContext {
    /// Checks whether the context exists or not.
    pub fn exist(&self) -> bool {
218
        let func = function::Function::get("_GetDeviceAttr").expect("API function always exists");
219 220 221
        let dt = self.device_type.0 as usize;
        // `unwrap` is ok here because if there is any error,
        // if would occure inside `call_packed!`
222
        let ret: u64 = call_packed!(func, dt, self.device_id, 0)
223
            .unwrap()
224 225
            .try_into()
            .unwrap();
226 227 228 229
        ret != 0
    }

    /// Synchronize the context stream.
230 231
    pub fn sync(&self) -> Result<(), Error> {
        check_call!(ffi::TVMSynchronize(
232 233 234 235 236 237 238 239 240 241 242 243 244
            self.device_type.0 as i32,
            self.device_id as i32,
            ptr::null_mut() as *mut c_void
        ));
        Ok(())
    }
}

macro_rules! impl_device_attrs {
    ($(($attr_name:ident, $attr_kind:expr));+) => {
        $(
            impl TVMContext {
                pub fn $attr_name(&self) -> usize {
245
                    let func = function::Function::get("_GetDeviceAttr")
246 247 248 249
                        .expect("API function always exists");
                    let dt = self.device_type.0 as usize;
                    // `unwrap` is ok here because if there is any error,
                    // if would occur in function call.
250
                    function::Builder::from(func)
251 252 253
                        .arg(dt)
                        .arg(self.device_id as usize)
                        .arg($attr_kind)
254
                        .invoke()
255 256 257
                        .unwrap()
                        .try_into()
                        .unwrap()
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
                }
            }
        )+
    };
}

impl_device_attrs!((max_threads_per_block, 1);
                (warp_size, 2);
                (max_shared_memory_per_block, 3);
                (compute_version, 4);
                (device_name, 5);
                (max_clock_rate, 6);
                (multi_processor_count, 7);
                (max_thread_dimensions, 8));

273 274
impl From<ffi::DLContext> for TVMContext {
    fn from(ctx: ffi::DLContext) -> Self {
275 276
        TVMContext {
            device_type: TVMDeviceType::from(ctx.device_type),
277
            device_id: ctx.device_id,
278 279 280 281
        }
    }
}

282
impl From<TVMContext> for ffi::DLContext {
283
    fn from(ctx: TVMContext) -> Self {
284
        ffi::DLContext {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
            device_type: ctx.device_type.into(),
            device_id: ctx.device_id as i32,
        }
    }
}

impl Display for TVMContext {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}({})", self.device_type, self.device_id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn context() {
        let ctx = TVMContext::cpu(0);
        println!("ctx: {}", ctx);
        let default_ctx = TVMContext::new(TVMDeviceType(1), 0);
        assert_eq!(ctx.clone(), default_ctx);
        assert_ne!(ctx, TVMContext::gpu(0));

        let str_ctx = TVMContext::new(TVMDeviceType::from("gpu"), 0);
        assert_eq!(str_ctx.clone(), str_ctx);
        assert_ne!(str_ctx, TVMContext::new(TVMDeviceType::from("cpu"), 0));
    }

    #[test]
    fn sync() {
        let ctx = TVMContext::cpu(0);
        assert!(ctx.sync().is_ok())
    }
}