Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch Autograd: Automatic Differentiation

PyTorch Autograd: Automatic Differentiation

Training in deep learning is essentially a process of repeatedly computing gradients and updating parameters.

Manually deriving the gradient of each layer is tedious and error-prone. PyTorch's Autograd (automatic differentiation) engine was created precisely to solve this problem -- it canautomatically compute the gradients of any computational graph, letting you focus on model design rather than calculus derivation.


Core Concepts

1. What Is Automatic Differentiation

Automatic differentiation is neither numerical differentiation (finite differences) nor symbolic differentiation (algebraic derivation); instead, itrecords the computation process and applies the chain rule step by step in reverseto compute derivatives exactly.

PyTorch's Autograd uses adynamic computation graph(Define-by-Run) approach: each forward pass builds a directed acyclic graph (DAG) in real time, recording each operation and its inputs and outputs; during backpropagation, it traverses the graph in reverse to compute the gradient of each node in turn.

2. The requires_grad Attribute

A Tensor's requires_grad attribute controls whether gradients need to be tracked for that tensor:

Example

import

torch

Create a tensor that requires gradient tracking (default requires_grad=False)

x

=

torch.

tensor

(

3.0

,

requires_grad

=

True

)

print

(

x

)

             

tensor(3., requires_grad=True)

print

(

x.

requires_grad

)

 

True

It can also be modified after creation

y

=

torch.

tensor

(

2.0

)

print

(

y.

requires_grad

)

 

False

y.

requires_grad_

(

True

)

 

Modify in place (note the trailing underscore)

print

(

y.

requires_grad

)

 

True

The result of an operation involving a tensor with requires_grad=True automatically inherits requires_grad=True

z

=

x * y

print

(

z.

requires_grad

)

 

True

3. grad_fn and the Computational Graph

Every tensor produced by an operation records a grad_fn, pointing to the operation node that created it. This is the "skeleton" of the computational graph:

Example

import

torch

x

=

torch.

tensor

(

2.0

,

requires_grad

=

True

)

y

=

torch.

tensor

(

3.0

,

requires_grad

=

True

)

z

=

x **

2

3

   

z = x² + 3y

print

(

z

)

         

tensor(13., grad_fn=)

print

(

z.

grad_fn

)

 

Trace the chain of operations that created z

print

(

z.

grad_fn

.

next_functions

)

(( , 0), (, 0))

You can see that z is formed by a power operation and a multiplication operation


backward() for backpropagation

1. Calling backward() on a Scalar Output

Call backward() on the final scalar (the loss value) .backward(), Autograd automatically works back through the computational graph to compute the gradients of all leaf nodes, storing the results in each tensor's .grad property through the following steps:

Example

import

torch

x

=

torch.

tensor

(

2.0

,

requires_grad

=

True

)

y

=

torch.

tensor

(

3.0

,

requires_grad

=

True

)

Forward pass: z = x^2 + 3y

z

=

x **

2

3

Backward pass: automatically compute dz/dx and dz/dy

z.

backward

(

)

View the gradients

print

(

x.

grad

)

 

tensor(4.)  ← dz/dx = 2x = 2×2 = 4

print

(

y.

grad

)

 

tensor(3.)  ← dz/dy = 3

Mathematical verification:

z = x² + 3y

dz/dx = 2x = 2×2 = 4  ✓

dz/dy = 3             ✓

2. The Accumulation Issue with Multiple backward() Calls

Autograd's gradients areaccumulated, not overwritten. Each time you call backward(), the gradient is added to .grad the existing value. This is the easiest pitfall to fall into in a training loop:

Example

import

torch

x

=

torch.

tensor

(

2.0

,

requires_grad

=

True

)

First backward pass

loss

=

x **

2

loss.

backward

(

)

print

(

x.

grad

)

   

tensor(4.)  ← dL/dx = 2x = 4

Second backward pass (without clearing!)

loss

=

x **

2

loss.

backward

(

)

print

(

x.

grad

)

   

tensor(8.) <- accumulated! Not 4, but 4+4=8

[OK] Correct approach: clear the gradients before every backward pass

x.

grad

.

zero_

(

)

 

Clear in place (note the underscore)

loss

=

x **

2

loss.

backward

(

)

print

(

x.

grad

)

   

tensor(4.) <- correct

When training a neural network, you must call this backward() before every backward pass optimizer.zero_grad() to clear the gradients; otherwise they keep accumulating and cause incorrect parameter updates.

3. Calling backward(gradient) on a Non-scalar Output

If the output is a vector or matrix rather than a scalar,backward() you need to pass a gradient argument with the same shape as the output (the "upstream gradient"); this essentially computes a vector-Jacobian product (VJP):

Example

import

torch

x

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

]

,

requires_grad

=

True

)

Forward pass: y is a vector

y

=

x **

2

 

y = [1, 4, 9]

A non-scalar must be given the gradient argument (same shape as y)

"gradient" can be understood as "the gradient of the loss with respect to y"

y.

backward

(

gradient

=

torch.

ones_like

(

y

)

)

 

Assume the upstream gradient is all ones

print

(

x.

grad

)

tensor([2., 4., 6.]) <- dy/dx = 2x, computed element by element

If the upstream gradient is not all ones (e.g., weighted)

x.

grad

.

zero_

(

)

y.

backward

(

gradient

=

torch.

tensor

(

[

1.0

,

0.5

,

2.0

]

)

)

 

Different weights

Actual computation: x.grad = 2x * gradient = [2*1, 4*0.5, 6*2]

print

(

x.

grad

)

tensor([2., 2., 12.])

A more common approach: first use sum/mean to get a scalar, then call backward()

x.

grad

.

zero_

(

)

loss

=

(

x **

2

)

.

sum

(

)

 

Aggregate the vector into a scalar

loss.

backward

(

)

print

(

x.

grad

)

tensor([2., 4., 6.]) <- equivalent to the first approach


torch.no_grad() stops gradient tracking

During model inference (prediction), gradients are not needed. Using torch.no_grad() skips building the computational graph, significantly saving memory and computation:

Example

import

torch

x

=

torch.

tensor

(

3.0

,

requires_grad

=

True

)

Inside a no_grad context, no operations have their gradients tracked

with

torch.

no_grad

(

)

:

    y

=

x **

2

   

print

(

y.

requires_grad

)

 

False <- no longer tracking gradients

   

print

(

y.

grad_fn

)

       

None <- no computational graph node

After exiting the no_grad context, tracking resumes normally

z

=

x **

2

print

(

z.

requires_grad

)

 

True

Common use: wrap the entire inference process during model evaluation

model

=

torch.

nn

.

Linear

(

10

,

1

)

inputs

=

torch.

randn

(

32

,

10

)

with

torch.

no_grad

(

)

:

    outputs

=

model

(

inputs

)

 

No computational graph is built, so it is faster and uses less memory

The @torch.no_grad() decorator form

You can also use the decorator form, which is suitable for marking an entire inference function as gradient-free:

Example

import

torch

import

torch.

nn

as

nn

model

=

nn.

Linear

(

10

,

1

)

@

torch.

no_grad

(

)

def

predict

(

model

,

x

)

:

   

"""Inference function, no gradient computation needed"""

   

return

model

(

x

)

x

=

torch.

randn

(

5

,

10

)

output

=

predict

(

model

,

x

)

print

(

output.

requires_grad

)

 

False


detach() detaches from the computational graph

.detach() Returns a new tensor that shares data with the original but does not track gradients. Commonly used in these scenarios:

Scenario Description
Convert an intermediate result to a numpy array numpy does not support tensors with gradients, so you must detach() first
Record the training loss (logging) Avoid keeping the whole computational graph, preventing memory leaks
Freeze gradient propagation for part of the network Scenarios such as GAN training and transfer learning

Example

import

torch

x

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

]

,

requires_grad

=

True

)

y

=

x **

2

3

 

y has grad_fn

The detached tensor shares data with y but is off the computational graph

y_detached

=

y.

detach

(

)

print

(

y_detached.

requires_grad

)

 

False

print

(

y_detached.

grad_fn

)

       

None

[OK] Convert to numpy (a tensor with gradients cannot be converted directly)

y.numpy() # [ERROR] raises RuntimeError

y_detached.

numpy

(

)

   

[OK] works fine

[OK] detach when recording the loss value (avoid keeping the graph and consuming memory)

losses

=

[

]

for

i

in

range

(

3

)

:

    loss

=

(

x **

2

)

.

sum

(

)

    losses.

append

(

loss.

detach

(

)

.

item

(

)

)

 

.item() converts a scalar tensor to a Python float

    loss.

backward

(

)

    x.

grad

.

zero_

(

)

print

(

losses

)

 

[14.0, 14.0, 14.0]


retain_graph keeps the computational graph

By default,backward() After execution, the computational graph isautomatically freed(saving memory). If you need to backpropagate multiple times through the same graph (as in some GAN training), you need to pass retain_graph=True:

Example

import

torch

x

=

torch.

tensor

(

2.0

,

requires_grad

=

True

)

y

=

x **

3

 

y = x³

First backward (keep the graph)

y.

backward

(

retain_graph

=

True

)

print

(

x.

grad

)

   

tensor(12.)  ← dy/dx = 3x² = 3×4 = 12

Second backward (the graph still exists)

x.

grad

.

zero_

(

)

y.

backward

(

retain_graph

=

True

)

print

(

x.

grad

)

   

tensor(12.) <- same result

The last time, there is no need to keep it

x.

grad

.

zero_

(

)

y.

backward

(

)

   

After that, the graph is freed

print

(

x.

grad

)

   

tensor(12.)

Trying backward again raises an error (the graph has been freed)

y.backward()   # ❌ RuntimeError: Trying to backward through the graph a second time

Using it unnecessarily retain_graph=True causes memory to keep growing because the graph cannot be freed. Only use it when multiple backward passes are truly needed.


Gradients in Neural Network Training

Below is a complete example of implementing gradient descent manually with Autograd, showing the full workflow of Autograd in real training:

Example

import

torch

Construct training data: y = 2x + 1 with noise

torch.

manual_seed

(

42

)

X

=

torch.

randn

(

100

,

1

)

y_true

=

2

1

0.1

randn

(

100

,

1

)

Initialize model parameters (requiring gradient tracking)

w

=

torch.

zeros

(

1

,

requires_grad

=

True

)

 

Weight

b

=

torch.

zeros

(

1

,

requires_grad

=

True

)

 

Bias

lr

=

0.1

   

Learning Rate

epochs

=

50

 

Number of Training Epochs

for

epoch

in

range

(

epochs

)

:

   

1. Forward pass: compute the predictions

    y_pred

=

X * w + b

   

2. Compute the loss (mean squared error)

    loss

=

(

(

y_pred - y_true

)

**

2

)

.

mean

(

)

   

3. Backward pass: automatically compute d(loss)/dw and d(loss)/db

    loss.

backward

(

)

   

4. Update parameters manually (wrap in no_grad to avoid tracking the update in the graph)

   

with

torch.

no_grad

(

)

:

        w -

=

lr * w.

grad

        b -

=

lr * b.

grad

   

5. Clear the gradients (must be done before the next backward pass)

    w.

grad

.

zero_

(

)

    b.

grad

.

zero_

(

)

   

if

(

epoch +

1

)

%

10

==

0

:

       

print

(

f

"Epoch {epoch+1:3d} | Loss: {loss.item():.4f} | w={w.item():.3f}, b={b.item():.3f}"

)

print

(

f

"\nTraining complete: w ~= {w.item():.3f} (true value 2.0), b ~= {b.item():.3f} (true value 1.0)"

)

Running the above code gives output similar to the following:



Epoch  10 | Loss: 0.1064 | w=1.587, b=0.805

Epoch  20 | Loss: 0.0281 | w=1.876, b=0.949

Epoch  30 | Loss: 0.0152 | w=1.954, b=0.983

Epoch  40 | Loss: 0.0128 | w=1.978, b=0.993

Epoch  50 | Loss: 0.0122 | w=1.987, b=0.997



训练完成:w ≈ 1.987(真实值 2.0),b ≈ 0.997(真实值 1.0)


Common API Quick Reference

API Purpose Common Scenarios
tensor.requires_grad_(True) Enable gradient tracking in place Enable Autograd on an already-created tensor
loss.backward() Backpropagation, computing gradients of all leaf nodes Each iteration in a training loop
tensor.grad Access a tensor's gradient value View or manually update parameters
tensor.grad.zero_() Clear gradients in place Must be called before every backward()
torch.no_grad() Context manager that disables gradient tracking Inference phase, manual parameter updates
tensor.detach() Returns a new tensor detached from the graph Convert to numpy, log values, freeze gradients
tensor.item() Convert a scalar tensor to a Python number Print loss values, record metrics
loss.backward(retain_graph=True) Keep the graph, allowing multiple backward passes Scenarios such as GAN training that need multiple backward passes

Common Issues and Notes

1. Leaf vs. Non-leaf Nodes

OnlyLeaf Node(tensors created directly by the user, not the result of an operation) have their gradients saved in .grad . Non-leaf nodes produced by intermediate operations do not keep gradients by default (to save memory). If you need to view an intermediate node's gradient, call .retain_grad():

Example

import

torch

x

=

torch.

tensor

(

2.0

,

requires_grad

=

True

)

 

Leaf Node

Intermediate node (non-leaf)

y

=

x **

2

     

y is an intermediate node

y.

retain_grad

(

)

Explicitly declare that y's gradient should be kept

z

=

y *

3

     

z is the final output

z.

backward

(

)

print

(

x.

grad

)

 

tensor(12.) <- leaf node, saved normally

print

(

y.

grad

)

 

tensor(3.) <- saved because of retain_grad()

An intermediate node without retain_grad() has .grad equal to None

2. In-place Operations May Break the Computational Graph

Performing in-place operations on tensors that require gradient tracking (such as +=, .add_()) may prevent Autograd from backpropagating correctly, so avoid them whenever possible:

Example

import

torch

x

=

torch.

tensor

(

[

1.0

,

2.0

]

,

requires_grad

=

True

)

Danger: performing an in-place operation on a leaf node

x += 1 # may raise an error: a leaf Variable that requires grad has been used in an in-place operation

Safe: use a non-in-place operation

y

=

x +

1

 

Create a new tensor without modifying x

In-place operations in a no_grad context are safe (e.g., parameter updates)

with

torch.

no_grad

(

)

:

    x +

=

0.01

 

Used for manual parameter updates, which is safe here

3. Only Floating-point Tensors Support Gradients

Integer types (such as torch.int64) do not support requires_grad=True; only floating-point types (float32, float64, float16) can participate in automatic differentiation.