Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add varbuilder get_unchecked #28

Merged
merged 2 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion candle-core/benches/benchmarks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ pub(crate) mod random;
pub(crate) mod unary;
pub(crate) mod where_cond;

use candle_core::{cuda::WrapErr, Device, Result};
use candle_core::{Device, Result};

#[cfg(feature = "cuda")]
use candle_core::cuda::WrapErr;

pub(crate) trait BenchDevice {
fn sync(&self) -> Result<()>;
Expand Down
154 changes: 114 additions & 40 deletions candle-nn/src/var_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ pub trait Backend: Send + Sync {
dev: &Device,
) -> Result<Tensor>;

/// Retrieve a tensor based on the name.
fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor>;

fn contains_tensor(&self, name: &str) -> bool;
}

Expand All @@ -70,6 +73,9 @@ pub trait SimpleBackend: Send + Sync {
dev: &Device,
) -> Result<Tensor>;

/// Retrieve a tensor based on the name.
fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor>;

fn contains_tensor(&self, name: &str) -> bool;
}

Expand All @@ -86,6 +92,10 @@ impl<'a> Backend for Box<dyn SimpleBackend + 'a> {
self.as_ref().get(s, name, h, dtype, dev)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
self.as_ref().get_unchecked(name, dtype, dev)
}

fn contains_tensor(&self, name: &str) -> bool {
self.as_ref().contains_tensor(name)
}
Expand Down Expand Up @@ -186,6 +196,19 @@ impl<'a, B: Backend> VarBuilderArgs<'a, B> {
self.get_with_hints(s, name, Default::default())
}

/// Retrieve the tensor associated with the given name at the current path.
pub fn get_unchecked(&self, name: &str) -> Result<Tensor> {
self.get_unchecked_dtype(name, self.data.dtype)
}

/// Retrieve the tensor associated with the given name & dtype at the current path.
pub fn get_unchecked_dtype(&self, name: &str, dtype: DType) -> Result<Tensor> {
let name = self.path(name);
self.data
.backend
.get_unchecked(&name, dtype, &self.data.device)
}

/// Retrieve the tensor associated with the given name & dtype at the current path.
pub fn get_with_hints_dtype<S: Into<Shape>>(
&self,
Expand Down Expand Up @@ -232,6 +255,12 @@ impl SimpleBackend for Zeros {
Tensor::zeros(s, dtype, dev)
}

fn get_unchecked(&self, _name: &str, _dtype: DType, _dev: &Device) -> Result<Tensor> {
candle::bail!(
"`Zeros` requires a shape for tensor retrieval, use `get` instead of `get_unchecked`"
)
}

fn contains_tensor(&self, _name: &str) -> bool {
true
}
Expand All @@ -246,6 +275,19 @@ impl SimpleBackend for HashMap<String, Tensor> {
dtype: DType,
dev: &Device,
) -> Result<Tensor> {
let tensor = self.get_unchecked(name, dtype, dev)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {name}"),
expected: s,
got: tensor.shape().clone(),
}
.bt())?
}
Ok(tensor)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
let tensor = self
.get(name)
.ok_or_else(|| {
Expand All @@ -255,14 +297,6 @@ impl SimpleBackend for HashMap<String, Tensor> {
.bt()
})?
.clone();
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {name}"),
expected: s,
got: tensor.shape().clone(),
}
.bt())?
}
tensor.to_device(dev)?.to_dtype(dtype)
}

Expand All @@ -283,6 +317,10 @@ impl SimpleBackend for VarMap {
VarMap::get(self, s, name, h, dtype, dev)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
VarMap::get_unchecked(self, name, dtype, dev)
}

fn contains_tensor(&self, name: &str) -> bool {
self.data().lock().unwrap().contains_key(name)
}
Expand All @@ -298,11 +336,24 @@ impl<'a> SimpleBackend for SafeTensorWithRouting<'a> {
fn get(
&self,
s: Shape,
path: &str,
name: &str,
_: crate::Init,
dtype: DType,
dev: &Device,
) -> Result<Tensor> {
let tensor = self.get_unchecked(name, dtype, dev)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {name}"),
expected: s,
got: tensor.shape().clone(),
}
.bt())?
}
Ok(tensor)
}

fn get_unchecked(&self, path: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
let index = self.routing.get(path).ok_or_else(|| {
Error::CannotFindTensor {
path: path.to_string(),
Expand All @@ -313,14 +364,6 @@ impl<'a> SimpleBackend for SafeTensorWithRouting<'a> {
.tensor(path)?
.load(dev)?
.to_dtype(dtype)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {path}"),
expected: s,
got: tensor.shape().clone(),
}
.bt())?
}
Ok(tensor)
}

Expand All @@ -333,22 +376,15 @@ impl SimpleBackend for candle::npy::NpzTensors {
fn get(
&self,
s: Shape,
path: &str,
name: &str,
_: crate::Init,
dtype: DType,
dev: &Device,
) -> Result<Tensor> {
let tensor = match self.get(path)? {
None => Err(Error::CannotFindTensor {
path: path.to_string(),
}
.bt())?,
Some(tensor) => tensor,
};
let tensor = tensor.to_device(dev)?.to_dtype(dtype)?;
let tensor = self.get_unchecked(name, dtype, dev)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {path}"),
msg: format!("shape mismatch for {name}"),
expected: s,
got: tensor.shape().clone(),
}
Expand All @@ -357,6 +393,18 @@ impl SimpleBackend for candle::npy::NpzTensors {
Ok(tensor)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
let tensor = match self.get(name)? {
None => Err(Error::CannotFindTensor {
path: name.to_string(),
}
.bt())?,
Some(tensor) => tensor,
};
let tensor = tensor.to_device(dev)?.to_dtype(dtype)?;
Ok(tensor)
}

fn contains_tensor(&self, name: &str) -> bool {
self.get(name).map_or(false, |v| v.is_some())
}
Expand All @@ -366,22 +414,15 @@ impl SimpleBackend for candle::pickle::PthTensors {
fn get(
&self,
s: Shape,
path: &str,
name: &str,
_: crate::Init,
dtype: DType,
dev: &Device,
) -> Result<Tensor> {
let tensor = match self.get(path)? {
None => Err(Error::CannotFindTensor {
path: path.to_string(),
}
.bt())?,
Some(tensor) => tensor,
};
let tensor = tensor.to_device(dev)?.to_dtype(dtype)?;
let tensor = self.get_unchecked(name, dtype, dev)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {path}"),
msg: format!("shape mismatch for {name}"),
expected: s,
got: tensor.shape().clone(),
}
Expand All @@ -390,6 +431,18 @@ impl SimpleBackend for candle::pickle::PthTensors {
Ok(tensor)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
let tensor = match self.get(name)? {
None => Err(Error::CannotFindTensor {
path: name.to_string(),
}
.bt())?,
Some(tensor) => tensor,
};
let tensor = tensor.to_device(dev)?.to_dtype(dtype)?;
Ok(tensor)
}

fn contains_tensor(&self, name: &str) -> bool {
self.get(name).map_or(false, |v| v.is_some())
}
Expand All @@ -404,7 +457,7 @@ impl SimpleBackend for candle::safetensors::MmapedSafetensors {
dtype: DType,
dev: &Device,
) -> Result<Tensor> {
let tensor = self.load(name, dev)?.to_dtype(dtype)?;
let tensor = self.get_unchecked(name, dtype, dev)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {name}"),
Expand All @@ -416,6 +469,10 @@ impl SimpleBackend for candle::safetensors::MmapedSafetensors {
Ok(tensor)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
self.load(name, dev)?.to_dtype(dtype)
}

fn contains_tensor(&self, name: &str) -> bool {
self.get(name).is_ok()
}
Expand All @@ -430,7 +487,7 @@ impl SimpleBackend for candle::safetensors::BufferedSafetensors {
dtype: DType,
dev: &Device,
) -> Result<Tensor> {
let tensor = self.load(name, dev)?.to_dtype(dtype)?;
let tensor = self.get_unchecked(name, dtype, dev)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {name}"),
Expand All @@ -442,6 +499,10 @@ impl SimpleBackend for candle::safetensors::BufferedSafetensors {
Ok(tensor)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
self.load(name, dev)?.to_dtype(dtype)
}

fn contains_tensor(&self, name: &str) -> bool {
self.get(name).is_ok()
}
Expand All @@ -456,7 +517,7 @@ impl<'a> SimpleBackend for candle::safetensors::SliceSafetensors<'a> {
dtype: DType,
dev: &Device,
) -> Result<Tensor> {
let tensor = self.load(name, dev)?.to_dtype(dtype)?;
let tensor = self.get_unchecked(name, dtype, dev)?;
if tensor.shape() != &s {
Err(candle::Error::UnexpectedShape {
msg: format!("shape mismatch for {name}"),
Expand All @@ -468,6 +529,10 @@ impl<'a> SimpleBackend for candle::safetensors::SliceSafetensors<'a> {
Ok(tensor)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
self.load(name, dev)?.to_dtype(dtype)
}

fn contains_tensor(&self, name: &str) -> bool {
self.get(name).is_ok()
}
Expand Down Expand Up @@ -718,6 +783,10 @@ impl Backend for ShardedSafeTensors {
Tensor::from_raw_buffer(&raw, view_dtype, &shape, dev)?.to_dtype(dtype)
}

fn get_unchecked(&self, _name: &str, _dtype: DType, _dev: &Device) -> Result<Tensor> {
candle::bail!("`get_unchecked` does not make sense for `ShardedSafeTensors`, use `get`.");
}

fn contains_tensor(&self, name: &str) -> bool {
self.0.get(name).is_ok()
}
Expand Down Expand Up @@ -751,6 +820,11 @@ impl<'a, R: Renamer + Sync + Send> SimpleBackend for Rename<'a, R> {
.to_device(dev)
}

fn get_unchecked(&self, name: &str, dtype: DType, dev: &Device) -> Result<Tensor> {
let name = self.renamer.rename(name);
self.inner.get_unchecked_dtype(&name, dtype)?.to_device(dev)
}

fn contains_tensor(&self, name: &str) -> bool {
let name = self.renamer.rename(name);
self.inner.contains_tensor(&name)
Expand Down
5 changes: 5 additions & 0 deletions candle-nn/src/var_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ impl VarMap {
Ok(tensor)
}

/// Retrieve or add a new variable.
pub fn get_unchecked(&self, _path: &str, _dtype: DType, _device: &Device) -> Result<Tensor> {
candle::bail!("`get_unchecked` does not make sense for `VarMap`, use `get`.");
}

pub fn data(&self) -> &Mutex<HashMap<String, Var>> {
&self.data
}
Expand Down
Loading