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 to_device() to VarBuilder to load weights to a specific GPU #1388

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
23 changes: 20 additions & 3 deletions candle-nn/src/var_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl<'a, B: Backend> Clone for VarBuilderArgs<'a, B> {
pub type VarBuilder<'a> = VarBuilderArgs<'a, Box<dyn SimpleBackend + 'a>>;

struct TensorData<B: Backend> {
backend: B,
backend: Arc<B>,
pub dtype: DType,
pub device: Device,
}
Expand Down Expand Up @@ -94,7 +94,7 @@ impl<'a> Backend for Box<dyn SimpleBackend + 'a> {
impl<'a, B: Backend> VarBuilderArgs<'a, B> {
pub fn new_with_args(backend: B, dtype: DType, dev: &Device) -> Self {
let data = TensorData {
backend,
backend: Arc::new(backend),
dtype,
device: dev.clone(),
};
Expand Down Expand Up @@ -150,6 +150,23 @@ impl<'a, B: Backend> VarBuilderArgs<'a, B> {
&self.data.device
}

/// If the target device is the same as the VarBuilder device, only a shallow copy is performed.
pub fn to_device(&self, dev: &Device) -> Self {
if self.device().same_device(dev) {
self.clone()
} else {
Self {
data: Arc::new(TensorData {
backend: self.data.backend.clone(),
dtype: self.data.dtype,
device: dev.clone(),
}),
path: self.path.clone(),
_phantom: self._phantom,
}
}
}

/// The dtype used by default.
pub fn dtype(&self) -> DType {
self.data.dtype
Expand Down Expand Up @@ -414,7 +431,7 @@ impl SimpleBackend for candle::safetensors::BufferedSafetensors {
impl<'a> VarBuilder<'a> {
fn new(backend: Box<dyn SimpleBackend + 'a>, dtype: DType, device: Device) -> Self {
let data = TensorData {
backend,
backend: Arc::new(backend),
dtype,
device,
};
Expand Down