Reading preferences
Concept

Tensors and Automatic Differentiation

Compare a small gradient in PyTorch, TensorFlow, and JAX.

python, pytorch, tensorflow, jax, tensors, autodiff

One derivative, three tools

PyTorch, TensorFlow, and JAX provide numerical arrays and automatic differentiation for machine-learning and scientific work. A gradient describes how a scalar output changes with its inputs. This is a bridge to the mathematics and ML modules, not a claim that a gradient alone trains a useful model.

Python illustration

In a separate environment with PyTorch installed:

import torch

x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
loss = (x * x).sum()
loss.backward()
print(loss.item())
print(x.grad.tolist())

Prepared output — not live execution:

14.0
[2.0, 4.0, 6.0]

The scalar is 1² + 2² + 3² = 14. Its gradient with respect to each input is 2x, giving [2, 4, 6]. PyTorch records operations for differentiation when gradients are enabled.

See the reasoning

Follow values and gradients

Trace a scalar sum of squares and its gradient. This is a prepared demonstration, not live code execution.

Start with a tensor

Forward and backward calculations
  1. x[1, 2, 3]Current focus
  2. Squarespending
  3. Losspending
  4. Gradientpending

x has three floating-point values and requests gradients.

Equivalent ideas, different APIs

TensorFlow records operations inside a gradient tape:

import tensorflow as tf

x = tf.Variable([1.0, 2.0, 3.0])
with tf.GradientTape() as tape:
    loss = tf.reduce_sum(x * x)
gradient = tape.gradient(loss, x)
print(gradient.numpy().tolist())

JAX transforms a scalar-valued function into a gradient function:

import jax
import jax.numpy as jnp

gradient = jax.grad(lambda x: jnp.sum(x * x))
print(gradient(jnp.array([1.0, 2.0, 3.0])).tolist())

Each prepared output is [2.0, 4.0, 6.0]. The libraries have distinct execution models, supported devices, numeric precision, and installation requirements. JAX transformations work best with pure functions and explicit state. Floating-point results can vary; validate shapes, dtypes, devices, and assumptions. These packages run only in a learner's separate environment, not on Intuvo.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What is a tensor in these libraries?
2. What is the gradient of x squared at x = 3?
3. What does backward compute in the example?
4. What does jax.grad return for a suitable scalar-valued function?

References and further reading