PyTorch torch.is_grad_enabled function
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:
- No parameters.
Return Value:
- Returns a boolean: True if gradient computation is currently enabled,
True; otherwise it returnsFalse.
Usage examples
Example 1: Basic usage
Example
import
torch
By default, gradient computation is enabled
(
"Default state:"
,
torch.
is_grad_enabled
(
)
)
Inside the no_grad context
with
torch.
no_grad
(
)
:
(
"Inside no_grad:"
,
torch.
is_grad_enabled
(
)
)
Restored after exit
(
"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
(
"Current state:"
,
torch.
is_grad_enabled
(
)
)
Disable gradients
torch.
set_grad_enabled
(
False
)
(
"After disabling:"
,
torch.
is_grad_enabled
(
)
)
Enable gradients
torch.
set_grad_enabled
(
True
)
(
"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
(
)
:
(
"Enable gradient computation"
)
Backpropagation can be performed
y
=
x *
2
return
y
else
:
(
"Disable gradient computation"
)
Fast, memory-saving computation
y
=
x *
2
return
y
Test different states
x
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
]
)
(
"=== Gradients enabled ==="
)
result1
=
process_tensor
(
x
)
(
"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
(
)
:
(
"Training mode"
)
Compute normally during training
return
torch.
mm
(
x
,
self
.
weight
)
else
:
(
"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
torch.no_grad(): A context manager that disables gradient computation.torch.enable_grad(): A context manager that enables gradient computation.torch.set_grad_enabled(grad): Sets whether gradient computation is enabled.
Notes
is_grad_enabledis a read-only function and does not change any state.- It checks the global gradient computation state, not that of an individual tensor
requires_gradattribute. - When writing general-purpose code, you can use this function to apply different optimization strategies based on the current state.