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

PyTorch torch.is_grad_enabled function

PyTorch torch.is_grad_enabled function


PyTorch torch reference manual PyTorch torch reference manual

torch.is_grad_enabled A function in PyTorch for checking whether gradient computation is currently enabled. It returns a boolean indicating whether PyTorch's gradient computation is enabled or disabled.

This is very useful when writing code that needs to execute different logic based on the gradient state.

Function definition

torch.is_grad_enabled()

Parameters:

Return Value:


Usage examples

Example 1: Basic usage

Example

import

torch

By default, gradient computation is enabled

print

(

"Default state:"

,

torch.

is_grad_enabled

(

)

)

Inside the no_grad context

with

torch.

no_grad

(

)

:

   

print

(

"Inside no_grad:"

,

torch.

is_grad_enabled

(

)

)

Restored after exit

print

(

"After exiting no_grad:"

,

torch.

is_grad_enabled

(

)

)

The output is:

默认状态: True

在 no_grad 中: False

退出 no_grad 后: True

Example 2: Use with set_grad_enabled

Example

import

torch

Check the current state

print

(

"Current state:"

,

torch.

is_grad_enabled

(

)

)

Disable gradients

torch.

set_grad_enabled

(

False

)

print

(

"After disabling:"

,

torch.

is_grad_enabled

(

)

)

Enable gradients

torch.

set_grad_enabled

(

True

)

print

(

"After enabling:"

,

torch.

is_grad_enabled

(

)

)

The output is:

当前状态: True

禁用后: False

启用后: True

Example 3: Use in conditional statements

Example

import

torch

def

process_tensor

(

x

)

:

   

"""Process tensors based on gradient state"""

   

if

torch.

is_grad_enabled

(

)

:

       

print

(

"Enable gradient computation"

)

       

Backpropagation can be performed

        y

=

x *

2

       

return

y

   

else

:

       

print

(

"Disable gradient computation"

)

       

Fast, memory-saving computation

        y

=

x *

2

       

return

y

Test different states

x

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

]

)

print

(

"=== Gradients enabled ==="

)

result1

=

process_tensor

(

x

)

print

(

"n=== Gradients disabled ==="

)

with

torch.

no_grad

(

)

:

    result2

=

process_tensor

(

x

)

The output is:

=== 启用梯度 ===

启用梯度计算



=== 禁用梯度 ===

禁用梯度计算

Example 4: Use in a custom layer

Example

import

torch

import

torch.

nn

as

nn

class

CustomLayer

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

weight

=

nn.

Parameter

(

torch.

randn

(

10

,

10

)

)

   

def

forward

(

self

,

x

)

:

       

Check the gradient state to handle things differently

       

if

torch.

is_grad_enabled

(

)

:

           

print

(

"Training mode"

)

           

Compute normally during training

           

return

torch.

mm

(

x

,

self

.

weight

)

       

else

:

           

print

(

"Inference mode"

)

           

An optimized version can be used during inference

           

with

torch.

no_grad

(

)

:

               

return

torch.

mm

(

x

,

self

.

weight

)

layer

=

CustomLayer

(

)

x

=

torch.

randn

(

5

,

10

)

Training

layer.

train

(

)

output1

=

layer

(

x

)

Inference

layer.

eval

(

)

with

torch.

no_grad

(

)

:

    output2

=

layer

(

x

)

The output is:

训练模式

推理模式


Related functions


Notes


PyTorch torch reference manual PyTorch torch reference manual