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

PyTorch torch.no_grad function

PyTorch torch.no_grad function


PyTorch torch reference manual PyTorch torch reference manual

torch.no_grad is a context manager in PyTorch used to disable gradient computation. Within a no_grad block, tensors created will not have gradients computed, which can significantly reduce memory consumption and improve inference speed.

This is essential during model inference and evaluation, greatly improving performance and saving memory.

Function definition

torch.no_grad()

Parameters:

Return Value:


Usage examples

Example 1: Basic usage

Example

import

torch

Create a tensor that requires gradients

x

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

]

,

requires_grad

=

True

)

Compute within the no_grad context

with

torch.

no_grad

(

)

:

    y

=

x *

2

   

print

(

"Inside no_grad:"

,

y.

requires_grad

)

Outside no_grad

z

=

x *

2

print

(

"Outside no_grad:"

,

z.

requires_grad

)

The output is:

在 no_grad 中: False

在 no_grad 外: True

Example 2: Model inference

Example

import

torch

import

torch.

nn

as

nn

Define a simple model

model

=

nn.

Linear

(

10

,

2

)

Create input data

x

=

torch.

randn

(

1

,

10

)

Use no_grad during inference

with

torch.

no_grad

(

)

:

    output

=

model

(

x

)

   

print

(

"Output:"

,

output

)

   

No need to compute gradients

Or use a decorator

@torch.no_grad()

def predict(x):

    return model(x)

The output is:

输出: tensor([[0.0920, 0.3557]])

Example 3: Evaluation mode

Example

import

torch

import

torch.

nn

as

nn

model

=

nn.

Sequential

(

    nn.

Linear

(

10

,

5

)

,

    nn.

ReLU

(

)

,

    nn.

Linear

(

5

,

2

)

)

Switch to evaluation mode

model.

eval

(

)

Prepare test data

test_input

=

torch.

randn

(

5

,

10

)

Disable gradients during evaluation

with

torch.

no_grad

(

)

:

    predictions

=

model

(

test_input

)

   

print

(

"Prediction result shape:"

,

predictions.

shape

)

The output is:

预测结果形状: torch.Size([5, 2])

Example 4: Compare memory usage

Example

import

torch

import

torch.

nn

as

nn

model

=

nn.

Linear

(

1000

,

1000

)

Create a large amount of input

inputs

=

[

torch.

randn

(

100

,

1000

)

for

_

in

range

(

100

)

]

Without no_grad (gradient history is recorded)

print

(

"Without no_grad:"

)

for

inp

in

inputs

[

:

5

]

:

    _

=

model

(

inp

)

With no_grad (no gradient history recorded)

print

(

"With no_grad:"

)

with

torch.

no_grad

(

)

:

   

for

inp

in

inputs

[

:

5

]

:

        _

=

model

(

inp

)

Use no_grad It can significantly reduce memory consumption because gradient information does not need to be stored for intermediate variables.


Related functions


Notes


PyTorch torch reference manual PyTorch torch reference manual