Research CommonsResearch Commons
cppgrad/Quickstart

Quickstart

Create tensors, build a computation graph, run a backward pass, and read gradients with cppgrad.

This walkthrough assumes you've finished Installation and can build a project that links cppgrad.

1. Create tensors

Tensors are created through factory functions. Pass requires_grad=true for any tensor whose gradient you want tracked.

#include <cppgrad/tensor/tensor.hpp>
using namespace cppgrad;
 
Tensor a = Tensor::full({2, 2}, 3.0f, /*requires_grad=*/true);
Tensor b = Tensor::full({2, 2}, 2.0f, /*requires_grad=*/true);

Other constructors include Tensor::zeros, Tensor::rand, and friends — see Tensors.

2. Build a computation graph

Ordinary operators record nodes on the autograd tape as you go:

Tensor c = a + b;   // elementwise add
Tensor d = c * b;   // elementwise multiply

Nothing special is required — using a and b in expressions builds the graph implicitly.

3. Backward pass

Call .backward() on the output to propagate gradients back through the graph:

d.backward();

4. Read gradients

Each leaf tensor now carries its gradient:

std::cout << "Grad of a:\n" << a.grad() << std::endl;
std::cout << "Grad of b:\n" << b.grad() << std::endl;

Full example

#include <cppgrad/tensor/tensor.hpp>
#include <iostream>
 
int main() {
  using namespace cppgrad;
 
  Tensor a = Tensor::full({2, 2}, 3.0f, /*requires_grad=*/true);
  Tensor b = Tensor::full({2, 2}, 2.0f, /*requires_grad=*/true);
 
  Tensor c = a + b;
  Tensor d = c * b;
 
  d.backward();
 
  std::cout << "Grad of a:\n" << a.grad() << std::endl;
  std::cout << "Grad of b:\n" << b.grad() << std::endl;
  return 0;
}
VSCode tasks

The repo ships predefined tasks — Build cppgrad, Run Tensor Example, Run Tests, and Rebuild and Run Tensor Example — under Terminal › Run Task. Set a breakpoint in tensor_example.cpp and press F5 to debug.

Next