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

PyTorch torch.enable_grad function

PyTorch torch.enable_grad function


PyTorch torch reference manual PyTorch torch reference manual

torch.enable_grad is a PyTorch context manager for enabling gradient computation. It is the opposite of torch.no_grad and is used to explicitly enable gradient computation in code blocks that need gradients.

This is useful when a model needs temporary training within inference code, or when gradient computation needs to be enabled in a local region.

Function definition

torch.enable_grad()

Parameters:

Return Value:


Usage examples

Example 1: Basic usage

Example

import

torch

By default, inside a no_grad context

with

torch.

no_grad

(

)

:

    x

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

]

)

   

print

(

"Inside no_grad:"

,

x.

requires_grad

)

   

Use enable_grad to temporarily enable gradients

   

with

torch.

enable_grad

(

)

:

        y

=

x *

2

       

print

(

"Inside enable_grad:"

,

y.

requires_grad

)

   

The no_grad state is restored after exit

    z

=

x *

2

   

print

(

"After exit:"

,

z.

requires_grad

)

The output is:

在 no_grad 中: False

在 enable_grad 中: True

退出后: False

Example 2: Mixing training and inference

Example

import

torch

import

torch.

nn

as

nn

model

=

nn.

Linear

(

10

,

2

)

Inference mode

with

torch.

no_grad

(

)

:

    x

=

torch.

randn

(

5

,

10

)

    output1

=

model

(

x

)

   

print

(

"Inference output:"

,

output1.

shape

)

   

If some parameters need temporary training during inference

   

with

torch.

enable_grad

(

)

:

       

Create a tensor that requires gradients for computation

        temp_weight

=

torch.

randn

(

10

,

10

,

requires_grad

=

True

)

        temp_output

=

torch.

mm

(

x

,

temp_weight

)

       

print

(

"Gradients temporarily enabled:"

,

temp_output.

requires_grad

)

The output is:

推理输出: torch.Size([5, 2])

临时启用梯度: True

Example 3: Use in a decorator

Example

import

torch

@

torch.

enable_grad

(

)

def

train_step

(

x

,

y

)

:

   

"""Simulated training step"""

   

This function enables gradient computation internally

    loss

=

(

x - y

)

.

sum

(

)

   

return

loss

Called inside a no_grad context

with

torch.

no_grad

(

)

:

    x

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

]

)

    y

=

torch.

tensor

(

[

0.0

,

0.0

,

0.0

]

)

   

The decorator ensures gradient computation is enabled

    loss

=

train_step

(

x

,

y

)

   

print

(

"Loss:"

,

loss

)

   

print

(

"Requires gradient:"

,

loss.

requires_grad

)

The output is:

Loss: tensor(6.)

需要梯度: True


Related functions


Notes


PyTorch torch reference manual PyTorch torch reference manual