candle_core

Struct Var

Source
pub struct Var(/* private fields */);
Expand description

A variable is a wrapper around a tensor, however variables can have their content modified whereas tensors are immutable.

Implementations§

Source§

impl Var

Source

pub fn zeros<S: Into<Shape>>( shape: S, dtype: DType, device: &Device, ) -> Result<Self>

Source

pub fn ones<S: Into<Shape>>( shape: S, dtype: DType, device: &Device, ) -> Result<Self>

Source

pub fn from_tensor(t: &Tensor) -> Result<Self>

Source

pub fn rand_f64<S: Into<Shape>>( lo: f64, up: f64, s: S, dtype: DType, device: &Device, ) -> Result<Self>

Source

pub fn randn_f64<S: Into<Shape>>( mean: f64, std: f64, s: S, dtype: DType, device: &Device, ) -> Result<Self>

Source

pub fn rand<S: Into<Shape>, T: FloatDType>( lo: T, up: T, s: S, device: &Device, ) -> Result<Self>

Source

pub fn randn<S: Into<Shape>, T: FloatDType>( mean: T, std: T, s: S, device: &Device, ) -> Result<Self>

Source

pub fn new<A: NdArray>(array: A, device: &Device) -> Result<Self>

Creates a new tensor on the specified device using the content and shape of the input. This is similar to new but the resulting tensor is a variable.

Source

pub fn from_vec<S: Into<Shape>, D: WithDType>( data: Vec<D>, shape: S, device: &Device, ) -> Result<Self>

Source

pub fn from_slice<S: Into<Shape>, D: WithDType>( array: &[D], shape: S, device: &Device, ) -> Result<Self>

Source

pub fn as_detached_tensor(&self) -> Tensor

Source

pub fn as_tensor(&self) -> &Tensor

Source

pub fn into_inner(self) -> Tensor

Consumes this Var and return the underlying tensor.

Source

pub fn set(&self, src: &Tensor) -> Result<()>

Sets the content of the inner tensor, this does not require a mutable reference as inner mutability is used.

Methods from Deref<Target = Tensor>§

Source

pub fn backward(&self) -> Result<GradStore>

Source

pub fn conv1d( &self, kernel: &Self, padding: usize, stride: usize, dilation: usize, groups: usize, ) -> Result<Self>

Applies a 1D convolution over the input tensor.

Source

pub fn conv_transpose1d( &self, kernel: &Self, padding: usize, output_padding: usize, stride: usize, dilation: usize, groups: usize, ) -> Result<Self>

Applies a 1D transposed convolution over the input tensor.

Source

pub fn conv2d( &self, kernel: &Self, padding: usize, stride: usize, dilation: usize, groups: usize, ) -> Result<Self>

Applies a 2D convolution over the input tensor.

Source

pub fn conv_transpose2d( &self, kernel: &Self, padding: usize, output_padding: usize, stride: usize, dilation: usize, ) -> Result<Self>

Applies a 2D transposed convolution over the input tensor.

Source

pub fn write_bytes<W: Write>(&self, f: &mut W) -> Result<()>

Source

pub fn apply_op1_no_bwd<C: CustomOp1>(&self, c: &C) -> Result<Self>

Applies a unary custom op without backward support

Source

pub fn apply_op2_no_bwd<C: CustomOp2>(&self, rhs: &Self, c: &C) -> Result<Self>

Applies a binary custom op without backward support

Source

pub fn apply_op3_no_bwd<C: CustomOp3>( &self, t2: &Self, t3: &Self, c: &C, ) -> Result<Self>

Applies a ternary custom op without backward support

Source

pub fn apply_op1_arc( &self, c: Arc<Box<dyn CustomOp1 + Send + Sync>>, ) -> Result<Self>

Applies a unary custom op.

Source

pub fn apply_op1<C: 'static + CustomOp1 + Send + Sync>( &self, c: C, ) -> Result<Self>

Source

pub fn apply_op2_arc( &self, rhs: &Self, c: Arc<Box<dyn CustomOp2 + Send + Sync>>, ) -> Result<Self>

Applies a binary custom op.

Source

pub fn apply_op2<C: 'static + CustomOp2 + Send + Sync>( &self, r: &Self, c: C, ) -> Result<Self>

Source

pub fn apply_op3_arc( &self, t2: &Self, t3: &Self, c: Arc<Box<dyn CustomOp3 + Send + Sync>>, ) -> Result<Self>

Applies a ternary custom op.

Source

pub fn apply_op3<C: 'static + CustomOp3 + Send + Sync>( &self, t2: &Self, t3: &Self, c: C, ) -> Result<Self>

Source

pub fn inplace_op1<C: InplaceOp1>(&self, c: &C) -> Result<()>

Applies a unary custom op in place.

Source

pub fn inplace_op2<C: InplaceOp2>(&self, rhs: &Self, c: &C) -> Result<()>

Applies a unary custom op in place (for the first tensor).

Source

pub fn inplace_op3<C: InplaceOp3>( &self, t2: &Self, t3: &Self, c: &C, ) -> Result<()>

Applies a ternary custom op in place (for the first tensor).

Source

pub fn write_npy<T: AsRef<Path>>(&self, path: T) -> Result<()>

Writes a multi-dimensional array in the npy format.

Source

pub fn save_safetensors<P: AsRef<Path>>( &self, name: &str, filename: P, ) -> Result<()>

Source

pub fn dims0(&self) -> Result<()>

Source

pub fn dims1(&self) -> Result<usize>

Source

pub fn dims2(&self) -> Result<(usize, usize)>

Source

pub fn dims3(&self) -> Result<(usize, usize, usize)>

Source

pub fn dims4(&self) -> Result<(usize, usize, usize, usize)>

Source

pub fn dims5(&self) -> Result<(usize, usize, usize, usize, usize)>

Source

pub fn arg_sort_last_dim(&self, asc: bool) -> Result<Tensor>

Returns the indices that sort the tensor along the last dimension.

If asc is true, sorting is in ascending order. Otherwise sorting is performed in descending order. The sort is unstable so there is no guarantees on the final order when it comes to ties.

Source

pub fn sort_last_dim(&self, asc: bool) -> Result<(Tensor, Tensor)>

Sorts the tensor along the last dimension, returns the sorted tensor together with the sorted indexes.

If asc is true, sorting is in ascending order. Otherwise sorting is performed in descending order. The sort is unstable so there is no guarantees on the final order when it comes to ties.

Source

pub fn ones_like(&self) -> Result<Self>

Creates a new tensor filled with ones with same shape, dtype, and device as the other tensor.

use candle_core::{Tensor, DType, Device};
let a = Tensor::zeros((2, 3), DType::F32, &Device::Cpu)?;
let b = a.ones_like()?;
// b == a + 1
Source

pub fn zeros_like(&self) -> Result<Self>

Creates a new tensor filled with ones with same shape, dtype, and device as the other tensor.

use candle_core::{Tensor, DType, Device};
let a = Tensor::zeros((2, 3), DType::F32, &Device::Cpu)?;
let b = a.zeros_like()?;
// b is on CPU f32.
Source

pub fn rand_like(&self, lo: f64, up: f64) -> Result<Self>

Source

pub fn randn_like(&self, mean: f64, stdev: f64) -> Result<Self>

Source

pub fn track_op(&self) -> bool

Returns true if the computation graph should track this op, that is if it is a variable or if it has some variable as dependencies.

Source

pub fn add(&self, rhs: &Self) -> Result<Self>

Source

pub fn mul(&self, rhs: &Self) -> Result<Self>

Source

pub fn sub(&self, rhs: &Self) -> Result<Self>

Source

pub fn div(&self, rhs: &Self) -> Result<Self>

Source

pub fn maximum<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Source

pub fn minimum<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Source

pub fn broadcast_add(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_mul(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_sub(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_div(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_maximum(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_minimum(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_eq(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_ne(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_lt(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_le(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_gt(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_ge(&self, rhs: &Self) -> Result<Self>

Source

pub fn recip(&self) -> Result<Self>

Source

pub fn neg(&self) -> Result<Self>

Source

pub fn exp(&self) -> Result<Self>

Source

pub fn log(&self) -> Result<Self>

Source

pub fn sin(&self) -> Result<Self>

Source

pub fn cos(&self) -> Result<Self>

Source

pub fn tanh(&self) -> Result<Self>

Source

pub fn abs(&self) -> Result<Self>

Source

pub fn sqr(&self) -> Result<Self>

Source

pub fn sqrt(&self) -> Result<Self>

Source

pub fn gelu(&self) -> Result<Self>

Source

pub fn gelu_erf(&self) -> Result<Self>

Source

pub fn erf(&self) -> Result<Self>

Source

pub fn relu(&self) -> Result<Self>

Source

pub fn silu(&self) -> Result<Self>

Source

pub fn ceil(&self) -> Result<Self>

Source

pub fn floor(&self) -> Result<Self>

Source

pub fn round(&self) -> Result<Self>

Source

pub fn sign(&self) -> Result<Self>

Source

pub fn round_to(&self, decimals: i32) -> Result<Self>

Round element of the input tensor to the nearest integer.

If the number of decimals is negative, it specifies the number of positions to the left of the decimal point.

Source

pub fn to_scalar<S: WithDType>(&self) -> Result<S>

Retrieves the single scalar value hold in the tensor. If the tensor contains multiple dimensions, an error is returned instead.

Source

pub fn to_vec0<S: WithDType>(&self) -> Result<S>

An alias for to_scalar.

Source

pub fn repeat<S: Into<Shape>>(&self, shape: S) -> Result<Tensor>

Repeat this tensor along the specified dimensions.

Source

pub fn affine(&self, mul: f64, add: f64) -> Result<Self>

This operation multiplies the input tensor by mul then adds add and return the result. The input values mul and add are casted to the appropriate type so some rounding might be performed.

use candle_core::{Tensor, Device};
let a = Tensor::new(&[[0f32, 1.], [2., 3.]], &Device::Cpu)?;
let a = a.affine(4., -2.)?;
assert_eq!(a.to_vec2::<f32>()?, &[[-2.0, 2.0], [6.0, 10.0]]);
Source

pub fn elu(&self, alpha: f64) -> Result<Self>

Applies the Exponential Linear Unit (ELU) function on each element of the input tensor.

Source

pub fn powf(&self, e: f64) -> Result<Self>

Raise the tensor to some float exponent e.

Source

pub fn chunk<D: Dim>(&self, chunks: usize, dim: D) -> Result<Vec<Self>>

Split a tensor into the specified number of chunks, this may return less chunks than specified.

Source

pub fn narrow<D: Dim>(&self, dim: D, start: usize, len: usize) -> Result<Self>

Returns a new tensor that is a narrowed version of the input, the dimension dim ranges from start to start + len.

use candle_core::{Tensor, Device};
let a = Tensor::new(&[
    [0f32, 1., 2.],
    [3.  , 4., 5.],
    [6.  , 7., 8.]
], &Device::Cpu)?;

let b = a.narrow(0, 1, 2)?;
assert_eq!(b.shape().dims(), &[2, 3]);
assert_eq!(b.to_vec2::<f32>()?, &[
    [3., 4., 5.],
    [6., 7., 8.]
]);

let c = a.narrow(1, 1, 1)?;
assert_eq!(c.shape().dims(), &[3, 1]);
assert_eq!(c.to_vec2::<f32>()?, &[
    [1.],
    [4.],
    [7.]
]);
Source

pub fn roll<D>(&self, shift: i32, dim: D) -> Result<Self>
where D: Dim + Clone,

Roll the tensor input along the given dimension. Elements that are shifted beyond the last position are re-introduced at the first position.

let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let tensor = tensor.roll(1, 0)?;
assert_eq!(tensor.to_vec2::<f32>()?, &[[4., 5.], [0., 1.], [2., 3.]]);
let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let tensor = tensor.roll(-1, 0)?;
assert_eq!(tensor.to_vec2::<f32>()?, &[[2., 3.], [4., 5.], [0., 1.]]);
Source

pub fn sum_keepdim<D: Dims>(&self, sum_dims: D) -> Result<Self>

Returns the sum of all elements in the input tensor. The sum is performed over all the input dimensions.

The resulting tensor has a shape that is similar to the shape of the input tensor, except that the number of elements for each dimension index in sum_dims is 1.

use candle_core::{Tensor, Device};
let a = Tensor::new(&[[0f32, 1.], [2., 3.]], &Device::Cpu)?;
let s = a.sum_keepdim(0)?;
assert_eq!(s.to_vec2::<f32>()?, &[[2., 4.]]);
let s = a.sum_keepdim(1)?;
assert_eq!(s.to_vec2::<f32>()?, &[[1.], [5.]]);
let s = a.sum_keepdim((0, 1))?;
assert_eq!(s.to_vec2::<f32>()?, &[[6.]]);
Source

pub fn sum<D: Dims>(&self, sum_dims: D) -> Result<Self>

Returns the sum of all elements in the input tensor. The sum is performed over all the input dimensions and compared to sum_keepdim these dimensions are squeezed rather than kept.

Source

pub fn mean_keepdim<D: Dims>(&self, mean_dims: D) -> Result<Self>

Returns the mean of all elements in the input tensor. The mean is performed over all the input dimensions.

The resulting tensor has a shape that is similar to the shape of the input tensor, except that the number of elements for each dimension index in mean_dims is 1.

use candle_core::{Tensor, Device};
let a = Tensor::new(&[[0f32, 1.], [2., 3.]], &Device::Cpu)?;
let s = a.mean_keepdim(0)?;
assert_eq!(s.to_vec2::<f32>()?, &[[1., 2.]]);
let s = a.mean_keepdim(1)?;
assert_eq!(s.to_vec2::<f32>()?, &[[0.5], [2.5]]);
let s = a.mean_keepdim((0, 1))?;
assert_eq!(s.to_vec2::<f32>()?, &[[1.5]]);
Source

pub fn mean<D: Dims>(&self, mean_dims: D) -> Result<Self>

Returns the mean of all elements in the input tensor. The mean is performed over all the input dimensions and compared to mean_keepdim these dimensions are squeezed rather than kept.

Source

pub fn var_keepdim<D: Dim>(&self, dim: D) -> Result<Self>

Returns the unbiased variance over the selected dimension.

Source

pub fn var<D: Dim>(&self, dim: D) -> Result<Self>

Returns the unbiased variance over the selected dimension.

Source

pub fn max_keepdim<D: Dim>(&self, dim: D) -> Result<Self>

Gathers the maximum value across the selected dimension. The resulting shape has the same number of dimensions as the original tensor and the select dimension has a single element.

Source

pub fn max<D: Dim>(&self, dim: D) -> Result<Self>

Similar to max_keepdim but the target dimension is squeezed.

Source

pub fn min_keepdim<D: Dim>(&self, dim: D) -> Result<Self>

Gathers the minimum value across the selected dimension. The resulting shape has the same number of dimensions as the original tensor and the select dimension has a single element.

Source

pub fn min<D: Dim>(&self, dim: D) -> Result<Self>

Similar to min_keepdim but the target dimension is squeezed.

Source

pub fn argmax_keepdim<D: Dim>(&self, dim: D) -> Result<Self>

Source

pub fn argmax<D: Dim>(&self, dim: D) -> Result<Self>

Similar to argmax_keepdim but the target dimension is squeezed.

Source

pub fn argmin_keepdim<D: Dim>(&self, dim: D) -> Result<Self>

Source

pub fn argmin<D: Dim>(&self, dim: D) -> Result<Self>

Similar to argmin_keepdim but the target dimension is squeezed.

Source

pub fn cmp<T: TensorOrScalar>(&self, rhs: T, op: CmpOp) -> Result<Self>

Element-wise comparison between two tensors, e.g. equality, greater than, … The actual comparison operation is specified by the op argument.

The returned tensor has the same shape as the original tensors and uses u8 elements.

Source

pub fn eq<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Element-wise equality.

Source

pub fn ne<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Element-wise non-equality.

Source

pub fn lt<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Element-wise comparison with lower-than, the returned tensor uses value 1 where self < rhs and 0 otherwise.

Source

pub fn gt<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Element-wise comparison with greater-than, the returned tensor uses value 1 where self > rhs and 0 otherwise.

Source

pub fn ge<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Element-wise comparison with greater-equal, the returned tensor uses value 1 where self >= rhs and 0 otherwise.

Source

pub fn le<T: TensorOrScalar>(&self, rhs: T) -> Result<Self>

Element-wise comparison with lower-equal, the returned tensor uses value 1 where self <= rhs and 0 otherwise.

Source

pub fn clamp<T1: TensorOrScalar, T2: TensorOrScalar>( &self, min: T1, max: T2, ) -> Result<Self>

Clamp the tensor values to be between min and max.

Source

pub fn interpolate1d(&self, target_size: usize) -> Result<Self>

Interpolate the input tensor to the target_size size, taking the value of the nearest element.

The input tensor should have three dimensions, (batch, channels, l), the returned tensor also has three dimensions, (batch, channels, target_size).

Source

pub fn upsample_nearest1d(&self, target_size: usize) -> Result<Self>

Alias for interpolate1d.

Source

pub fn interpolate2d(&self, target_h: usize, target_w: usize) -> Result<Self>

Interpolate the input tensor to the (target_h, target_w) size, taking the value of the nearest element.

The input tensor should have four dimensions, (batch, channels, h, w), the returned tensor also has four dimensions, (batch, channels, target_h, target_w).

Source

pub fn upsample_nearest2d( &self, target_h: usize, target_w: usize, ) -> Result<Self>

Alias for interpolate2d.

Source

pub fn avg_pool2d<T: ToUsize2>(&self, sz: T) -> Result<Self>

2D average pooling over an input tensor with multiple channels.

The input tensor should have four dimensions, (batch, channels, h, w), the returned tensor also has four dimensions, (batch, channels, h', w'). The pooling is performed on the two last dimensions using a kernel of size sz. The returned element is the average value over the kernel window.

Source

pub fn avg_pool2d_with_stride<T: ToUsize2>( &self, kernel_size: T, stride: T, ) -> Result<Self>

Same as avg_pool2d but with a stride that can be set to a value different from the kernel size.

Source

pub fn max_pool2d<T: ToUsize2>(&self, sz: T) -> Result<Self>

2D max pooling over an input tensor with multiple channels.

The input tensor should have four dimensions, (batch, channels, h, w), the returned tensor also has four dimensions, (batch, channels, h', w'). The pooling is performed on the two last dimensions using a kernel of size sz, the returned element is the maximum value over the kernel window.

Source

pub fn max_pool2d_with_stride<T: ToUsize2>( &self, kernel_size: T, stride: T, ) -> Result<Self>

Same as max_pool2d but with a stride that can be set to a value different from the kernel size.

Source

pub fn matmul(&self, rhs: &Self) -> Result<Self>

Returns the matrix-multiplication of the input tensor with the other provided tensor.

§Arguments
  • self - A tensor with dimensions b1, b2, ..., bi, m, k.
  • rhs - A tensor with dimensions b1, b2, ..., bi, k, n.

The resulting tensor has dimensions b1, b2, ..., bi, m, n.

Source

pub fn broadcast_matmul(&self, rhs: &Self) -> Result<Self>

Matrix-multiplication with broadcasting support.

Compared to matmul the two matrixes are allowed to have different dimensions as long as they are compatible for broadcast. E.g. if self has shape (j, 1, n, k) and rhs has shape (l, k, m), the output will have shape (j, l, n, m).

Source

pub fn where_cond(&self, on_true: &Self, on_false: &Self) -> Result<Self>

Returns a tensor with the same shape as the input tensor, the values are taken from on_true if the input tensor value is not zero, and on_false at the positions where the input tensor is equal to zero.

Source

pub fn embedding(&self, ids: &Self) -> Result<Self>

Returns a tensor with the values from the self tensor at the index corresponding to the values hold in the ids tensor.

§Arguments
  • self - A tensor with dimensions v, h.
  • ids - A tensor with dimensions s and with integer values between 0 and v (exclusive).

The resulting tensor has dimensions s, h. s is called the sequence length, v the vocabulary size, and h the hidden size.

use candle_core::{Tensor, Device};
let values = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let ids = Tensor::new(&[2u32, 1u32, 2u32], &Device::Cpu)?;
let emb = values.embedding(&ids)?;
assert_eq!(emb.to_vec2::<f32>()?, &[[4., 5.], [2., 3.], [4., 5.]]);
Source

pub fn scatter_add<D: Dim>( &self, indexes: &Self, source: &Self, dim: D, ) -> Result<Self>

Source

pub fn slice_scatter<D: Dim>( &self, src: &Self, dim: D, start: usize, ) -> Result<Self>

Embeds the values of the src tensor into the self tensor on the specified dimension.

Source

pub fn slice_scatter0(&self, src: &Self, start: usize) -> Result<Self>

Embeds the values of the src tensor into the self tensor on the first dimension.

Source

pub fn index_add<D: Dim>( &self, indexes: &Self, source: &Self, dim: D, ) -> Result<Self>

Accumulate element from source at indexes indexes and add them to self.

Source

pub fn gather<D: Dim>(&self, indexes: &Self, dim: D) -> Result<Self>

Gather values across the target dimension.

§Arguments
  • self - The input tensor.
  • indexes - The indices of elements to gather, this should have same number of dimensions as self and indexes.dims()[d] <= self.dims()[d] for all dimensions d != dim
  • dim - the target dimension.

The resulting tensor has the same shape as indexes and use values from self indexed on dimension dim by the values in indexes.

Source

pub fn index_select<D: Dim>(&self, indexes: &Self, dim: D) -> Result<Self>

Select values for the input tensor at the target indexes across the specified dimension.

The indexes is argument is an int tensor with a single dimension. The output has the same number of dimension as the self input. The target dimension of the output has length the length of indexes and the values are taken from self using the index from indexes. Other dimensions have the same number of elements as the input tensor.

Source

pub fn strided_index(&self) -> StridedIndex<'_>

Returns an iterator over position of the elements in the storage when ranging over the index tuples in lexicographic order.

Source

pub fn strided_blocks(&self) -> StridedBlocks<'_>

Similar to strided_index but returns the position of the start of each contiguous block as well as the length of the contiguous blocks. For a contiguous tensor, the index iterator will only return the start offset and the size would be the number of elements in the tensor.

Source

pub fn to_vec1<S: WithDType>(&self) -> Result<Vec<S>>

Returns the data contained in a 1D tensor as a vector of scalar values.

Source

pub fn to_vec2<S: WithDType>(&self) -> Result<Vec<Vec<S>>>

Returns the data contained in a 2D tensor as a vector of vector of scalar values.

Source

pub fn to_vec3<S: WithDType>(&self) -> Result<Vec<Vec<Vec<S>>>>

Returns the data contained in a 3D tensor.

Source

pub fn dtype(&self) -> DType

The dtype for the elements stored in the input tensor.

Source

pub fn device(&self) -> &Device

The device on which the input tensor is located.

Source

pub fn shape(&self) -> &Shape

The tensor shape, i.e. dimension sizes on each axis.

Source

pub fn dims(&self) -> &[usize]

The dimension size for this tensor on each axis.

Source

pub fn dim<D: Dim>(&self, dim: D) -> Result<usize>

The dimension size for a specified dimension index.

Source

pub fn layout(&self) -> &Layout

The layout of the input tensor, this stores both the shape of the tensor as well as the strides and the start offset to apply to the underlying storage.

Source

pub fn stride(&self) -> &[usize]

Source

pub fn rank(&self) -> usize

The number of dimensions for this tensor, 0 for a scalar tensor, 1 for a 1D tensor, etc.

Source

pub fn elem_count(&self) -> usize

The number of elements stored in this tensor.

Source

pub fn id(&self) -> TensorId

The unique identifier for this tensor.

Source

pub fn is_variable(&self) -> bool

Whether this tensor is a variable or not. A variable is a tensor for which gradient is tracked and on which backpropagation can be performed.

Source

pub fn sum_all(&self) -> Result<Tensor>

Computes the sum of all the elements in this tensor and returns a tensor holding this scalar with zero dimensions.

use candle_core::{Tensor, Device};
let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let tensor = tensor.sum_all()?;
assert_eq!(tensor.to_scalar::<f32>()?, 15.);
Source

pub fn mean_all(&self) -> Result<Tensor>

Source

pub fn flatten<D1: Dim, D2: Dim>( &self, start_dim: D1, end_dim: D2, ) -> Result<Tensor>

Flattens the input tensor on the dimension indexes from start_dim to end_dim (both inclusive).

Source

pub fn flatten_to<D: Dim>(&self, end_dim: D) -> Result<Tensor>

Flattens the input tensor on the dimension indexes from 0 to end_dim (inclusive).

Source

pub fn flatten_from<D: Dim>(&self, start_dim: D) -> Result<Tensor>

Flattens the input tensor on the dimension indexes from start_dim (inclusive) to the last dimension.

Source

pub fn flatten_all(&self) -> Result<Tensor>

Flattens the input tensor by reshaping it into a one dimension tensor.

use candle_core::{Tensor, Device};
let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let tensor = tensor.flatten_all()?;
assert_eq!(tensor.to_vec1::<f32>()?, &[0., 1., 2., 3., 4., 5.]);
Source

pub fn get(&self, i: usize) -> Result<Tensor>

Returns the sub-tensor fixing the index at i on the first dimension.

use candle_core::{Tensor, Device};
let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let t = tensor.get(0)?;
assert_eq!(t.to_vec1::<f32>()?, &[0., 1.]);
let t = tensor.get(1)?;
assert_eq!(t.to_vec1::<f32>()?, &[2., 3.]);
Source

pub fn get_on_dim<D: Dim>(&self, dim: D, index: usize) -> Result<Tensor>

Returns the sub-tensor fixing the index at index on the dimension dim.

use candle_core::{Tensor, Device};
let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let t = tensor.get_on_dim(1, 0)?;
assert_eq!(t.to_vec1::<f32>()?, &[0., 2., 4.]);
let t = tensor.get_on_dim(1, 1)?;
assert_eq!(t.to_vec1::<f32>()?, &[1., 3., 5.]);
let t = tensor.get_on_dim(0, 1)?;
assert_eq!(t.to_vec1::<f32>()?, &[2., 3.]);
Source

pub fn t(&self) -> Result<Tensor>

Returns a tensor that is a transposed version of the input, the two last dimensions of the input are swapped.

use candle_core::{Tensor, Device};
let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
let tensor = tensor.t()?;
assert_eq!(tensor.to_vec2::<f32>()?, &[[0.0, 2.0, 4.0], [1.0, 3.0, 5.0]]);
Source

pub fn transpose<D1: Dim, D2: Dim>(&self, dim1: D1, dim2: D2) -> Result<Tensor>

Returns a tensor that is a transposed version of the input, the given dimensions are swapped.

Source

pub fn permute<D: Dims>(&self, dims: D) -> Result<Tensor>

Returns a tensor with the same data as the input where the dimensions have been permuted. dims must be a permutation, i.e. include each dimension index exactly once.

use candle_core::{Tensor, Device};
let tensor = Tensor::arange(0u32, 120u32, &Device::Cpu)?.reshape((2, 3, 4, 5))?;
assert_eq!(tensor.dims(), &[2, 3, 4, 5]);
let tensor = tensor.permute((2, 3, 1, 0))?;
assert_eq!(tensor.dims(), &[4, 5, 3, 2]);
Source

pub fn is_contiguous(&self) -> bool

Returns true if the data is stored in a C contiguous (aka row major) way.

Source

pub fn is_fortran_contiguous(&self) -> bool

Returns true if the data is stored in a Fortran contiguous (aka column major) way.

Source

pub fn copy(&self) -> Result<Tensor>

Compared to clone, this copies the actual storage but may fail because of running out of memory.

Source

pub fn detach(&self) -> Tensor

Returns a new tensor detached from the current graph, gradient are not propagated through this new node. The storage of this tensor is shared with the initial tensor.

If the tensor is already detached from the computation graph, the same tensor is returned.

Source

pub fn to_device(&self, device: &Device) -> Result<Tensor>

If the target device is the same as the tensor device, only a shallow copy is performed.

Source

pub fn broadcast_left<S: Into<Shape>>(&self, left_shape: S) -> Result<Self>

Returns a new tensor duplicating data from the original tensor. New dimensions are inserted on the left.

Source

pub fn broadcast_as<S: Into<Shape>>(&self, shape: S) -> Result<Self>

Broadcast the input tensor to the target shape. This returns an error if the input shape is not compatible with the target shape.

If the input shape is i_1, i_2, ... i_k, the target shape has to have k dimensions or more and shape j_1, ..., j_l, t_1, t_2, ..., t_k. The dimensions j_1 to j_l can have any value, the dimension t_a must be equal to i_a if i_a is different from 1. If i_a is equal to 1, any value can be used.

Source

pub fn expand<S: Into<Shape>>(&self, shape: S) -> Result<Self>

An alias for broadcast_as.

Source

pub fn to_dtype(&self, dtype: DType) -> Result<Self>

Casts the input tensor to the target dtype.

use candle_core::{Tensor, Device};
let tensor = Tensor::new(3.14159265358979f64, &Device::Cpu)?;
assert_eq!(tensor.to_scalar::<f64>()?, 3.14159265358979);
let tensor = tensor.to_dtype(candle_core::DType::F32)?;
assert_eq!(tensor.to_scalar::<f32>()?, 3.1415927);
Source

pub fn contiguous(&self) -> Result<Tensor>

Returns a tensor that is in row major order. This is the same as the original tensor if it was already contiguous, otherwise a copy is triggered.

Source

pub fn force_contiguous(&self) -> Result<Tensor>

Returns a tensor that is in row major order. This always makes a copy.

Source

pub fn reshape<S: ShapeWithOneHole>(&self, s: S) -> Result<Tensor>

Reshape returns a tensor with the target shape provided that the number of elements of the original tensor is the same. If the input tensor is contiguous, this is a view on the original data. Otherwise this uses a new storage and copies the data over, the returned tensor is always contiguous.

The shape can be specified using a tuple of usize and at most one () in which case the behavior is the same as when using -1 in PyTorch: this dimension size is adjusted so as to match the number of elements in the tensor.

let a = Tensor::zeros((2, 3), DType::F32, &Device::Cpu)?;

let c = a.reshape((1, 6))?;
assert_eq!(c.shape().dims(), &[1, 6]);

let c = a.reshape((3, 2))?;
assert_eq!(c.shape().dims(), &[3, 2]);

let c = a.reshape((2, (), 1))?;
assert_eq!(c.shape().dims(), &[2, 3, 1]);
Source

pub fn squeeze<D: Dim>(&self, dim: D) -> Result<Self>

Creates a new tensor with the specified dimension removed if its size was one.

let a = Tensor::zeros((2, 3, 1), DType::F32, &Device::Cpu)?;

let c = a.squeeze(2)?;
assert_eq!(c.shape().dims(), &[2, 3]);

let c = a.squeeze(D::Minus1)?;
assert_eq!(c.shape().dims(), &[2, 3]);
Source

pub fn unsqueeze<D: Dim>(&self, dim: D) -> Result<Self>

Creates a new tensor with a dimension of size one inserted at the specified position.

let a = Tensor::zeros((2, 3), DType::F32, &Device::Cpu)?;

let c = a.unsqueeze(0)?;
assert_eq!(c.shape().dims(), &[1, 2, 3]);

let c = a.unsqueeze(D::Minus1)?;
assert_eq!(c.shape().dims(), &[2, 3, 1]);
Source

pub fn pad_with_zeros<D: Dim>( &self, dim: D, left: usize, right: usize, ) -> Result<Self>

Pad the input tensor using 0s along dimension dim. This adds left elements before the input tensor values and right elements after.

Source

pub fn pad_with_same<D: Dim>( &self, dim: D, left: usize, right: usize, ) -> Result<Self>

Pad the input tensor using same values along dimension dim. This adds left elements before the input tensor values and right elements after.

Source

pub fn apply<M: Module>(&self, m: &M) -> Result<Self>

Run the forward method of m on self.

Source

pub fn apply_t<M: ModuleT>(&self, m: &M, train: bool) -> Result<Self>

Run the forward method of m on self.

Source

pub fn storage_and_layout(&self) -> (RwLockReadGuard<'_, Storage>, &Layout)

The storage used by this tensor, together with the layout to use to access it safely.

Source

pub fn normalize_axis(&self, axis: i64) -> Result<usize>

Normalize a ‘relative’ axis value: positive values are kept, negative values means counting the dimensions from the back.

Source

pub fn cumsum<D: Dim>(&self, dim: D) -> Result<Self>

Returns the cumulative sum of elements of the input tensor summed over the specified dimension.

This operation is most efficient when dim is the last dimension of the tensor.

Source

pub fn slice_assign<D: RangeBounds<usize>>( &self, ranges: &[D], src: &Tensor, ) -> Result<Self>

Returns a copy of self where the values within ranges have been replaced with the content of src.

Source

pub fn log_sum_exp<D: Dims>(&self, sum_dims: D) -> Result<Self>

Returns log(sum(exp(tensor), dim)).

Source

pub fn pow(&self, rhs: &Tensor) -> Result<Self>

Pointwise pow operation.

Source

pub fn broadcast_pow(&self, rhs: &Tensor) -> Result<Self>

Broadcasting version of pow.

Source

pub fn slice_set<D: Dim>(&self, src: &Self, dim: D, offset: usize) -> Result<()>

Set the values on self using values from src. The copy starts at the specified offset for the target dimension dim on self. self and src must have the same shape except on dimension dim where the self size has to be greater than or equal to offset plus the src size.

Note that this modifies self in place and as such is not compatibel with back-propagation.

Trait Implementations§

Source§

impl Clone for Var

Source§

fn clone(&self) -> Var

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Var

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for Var

Source§

type Target = Tensor

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Display for Var

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Var

§

impl !RefUnwindSafe for Var

§

impl Send for Var

§

impl Sync for Var

§

impl Unpin for Var

§

impl !UnwindSafe for Var

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize = _

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> ErasedDestructor for T
where T: 'static,