Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:LaurentMazare Tch rs Basics Example

From Leeroopedia
Revision as of 15:32, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/LaurentMazare_Tch_rs_Basics_Example.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Knowledge Sources
Domains Deep Learning, Tensor Operations, Automatic Differentiation
Last Updated 2026-02-08 00:00 GMT

Overview

Demonstrates basic tensor operations, automatic gradient computation, and hardware device detection using the tch-rs library.

Description

This example serves as an introductory guide to the tch-rs crate. It covers several fundamental operations:

  • Tensor creation from slices and random distributions using Tensor::from_slice and Tensor::randn.
  • Automatic differentiation (autograd): a scalar tensor x = 2.0 is created with gradient tracking enabled, a polynomial y = x^2 + x + 36 is computed, and y.backward() calculates the gradient dy/dx = 2x + 1 = 5.0.
  • In-place operations such as += on tensors and clamp_ on gradients.
  • Device detection for CUDA, cuDNN, MPS, and Vulkan backends, along with version queries for cuDNN and CUDA runtime.
  • Device transfer using Tensor::to(device) to move tensors to GPU when available.

Usage

Use this example as a starting point to verify that tch-rs is correctly installed and that hardware backends (CUDA, MPS, Vulkan) are properly detected. It is also useful for learning how to perform basic tensor arithmetic and autograd in Rust.

Code Reference

Source Location

Signature

fn grad_example()

fn main()

Import

// Standalone binary example. Run with:
// cargo run --example basics
use tch::{kind, Tensor};

I/O Contract

Inputs

Name Type Required Description
(none) N/A No This example takes no external inputs. All tensors are created inline.

Outputs

Name Type Description
stdout Text Prints CUDA/cuDNN/MPS/Vulkan availability, tensor values, gradient values, and backend version strings.

Usage Examples

use tch::{kind, Tensor};

fn grad_example() {
    let mut x = Tensor::from(2.0).set_requires_grad(true);
    let y = &x * &x + &x + 36;
    println!("{}", y.double_value(&[]));  // prints 42.0
    x.zero_grad();
    y.backward();
    let dy_over_dx = x.grad();
    println!("Grad {}", dy_over_dx.double_value(&[]));  // prints 5.0
}

fn main() {
    // Device detection
    println!("Cuda available: {}", tch::Cuda::is_available());
    let device = tch::Device::cuda_if_available();

    // Create tensor and move to device
    let t = Tensor::from_slice(&[3, 1, 4, 1, 5]).to(device);
    t.print();

    // Random tensor operations
    let t = Tensor::randn([5, 4], kind::FLOAT_CPU);
    (&t + 1.5).print();

    // In-place addition
    let mut t = Tensor::from_slice(&[1.1f32, 2.1, 3.1]);
    t += 42;
    t.print();
    println!("{:?} {}", t.size(), t.double_value(&[1]));

    grad_example();
}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment