Expand description
Tensors, automatic differentiation, device selection, and errors for RustTorch.
Use this crate when you need tensor calculations without the higher-level
model and data-loading APIs. Applications that train neural networks can
instead use rusttorch, which re-exports these
types alongside its layers and optimizers.
Tensor is backed by LibTorch and supports numerical operations, views,
reductions, and gradient recording. Fallible methods use the f_ prefix;
their errors convert into the crate’s Result type.
§Calculate a gradient
Mark leaf tensors as requiring gradients before constructing a calculation. Backpropagating a scalar result fills each leaf tensor’s gradient.
use rusttorch_core::{Kind, Result, Tensor};
let values = Tensor::f_from_slice(&[2_f32, 3.])?.set_requires_grad(true);
let squared_sum = values.f_mul(&values)?.f_sum(Kind::Float)?;
squared_sum.f_backward()?;
let gradient = values.grad();
assert_eq!(gradient.double_value(&[0]), 4.0);
assert_eq!(gradient.double_value(&[1]), 6.0);Use no_grad or no_grad_guard for calculations that do not need a
gradient graph, such as prediction and manual parameter updates.
§Select a compute device
Keep tensors participating in an operation on the same device.
DeviceSpec::Auto selects CUDA, then MPS, then CPU according to runtime
availability. An explicit request returns an error if the device is not
available; available_devices reports the usable backends.
use rusttorch_core::{DeviceSpec, Kind, Result, Tensor, resolve_device};
let device = resolve_device(DeviceSpec::Cpu)?;
let features = Tensor::f_zeros([8, 4], (Kind::Float, device))?;
assert_eq!(features.device(), device);Re-exports§
pub use device::DeviceCapabilities;pub use device::DeviceSpec;pub use device::available_devices;pub use device::resolve_device;pub use error::Result;pub use error::RustTorchError;
Modules§
- device
- Runtime device discovery and strict device selection.
- error
- Errors returned by the fallible RustTorch API.
Structs§
- Tensor
- A tensor object.
Enums§
Functions§
- manual_
seed - Seeds LibTorch’s shared random generator before drawing tensors.
- no_grad
- Runs a closure without keeping track of gradients.
- no_
grad_ guard - Disables gradient tracking, this will be enabled back when the
returned value gets deallocated.
Note that it is important to bind this to a name like
_guardand not to_as the latter would immediately drop the guard. See https://internals.rust-lang.org/t/pre-rfc-must-bind/12658/46 for more details.