use core::ops::Deref;
use burn::tensor::Device;
use crate::errors::{
BunsenError,
BunsenResult,
};
#[derive(Debug)]
pub struct DeviceSession {
device: Option<Device>,
}
impl DeviceSession {
pub fn new(device: Device) -> Self {
Self {
device: Some(device),
}
}
pub fn device(&self) -> &Device {
self.device
.as_ref()
.expect("an open session has its device")
}
pub fn close(mut self) -> BunsenResult<()> {
let device = self.device.take().expect("an open session has its device");
sync(&device)
}
}
impl Deref for DeviceSession {
type Target = Device;
fn deref(&self) -> &Device {
self.device()
}
}
impl From<Device> for DeviceSession {
fn from(device: Device) -> Self {
Self::new(device)
}
}
impl Drop for DeviceSession {
fn drop(&mut self) {
if let Some(device) = self.device.take()
&& let Err(error) = sync(&device)
{
log::warn!("{error}");
}
}
}
fn sync(device: &Device) -> BunsenResult<()> {
device
.sync()
.map_err(|e| BunsenError::sys("the device failed to finish its queued work").with_cause(e))
}
#[cfg(test)]
mod tests {
use burn::tensor::Tensor;
use super::*;
use crate::support::testing::cpu_device;
#[test]
fn test_close_waits_for_queued_work() {
let device = DeviceSession::new(cpu_device());
let x = Tensor::<2>::ones([4, 4], &*device);
let y = x.clone().matmul(x);
drop(y);
device.close().unwrap();
}
#[test]
fn test_drop_waits_without_panicking() {
let device: DeviceSession = cpu_device().into();
let _x = Tensor::<1>::zeros([8], device.device());
}
#[test]
fn test_derefs_to_its_device() {
let device = DeviceSession::new(cpu_device());
assert_eq!(&*device, &cpu_device());
assert_eq!(device.device(), &cpu_device());
}
}