PyTorch torch.set_grad_enabled function
PyTorch torch reference manual
torch.set_grad_enabled is a function in PyTorch used to globally set whether gradient computation is enabled. It can dynamically enable or disable gradient computation. Unlike a context manager, it is a function that can change the global state.
This is very useful when gradient computation needs to be controlled dynamically based on conditions.
Function definition
torch.set_grad_enabled(mode)
Parameters:
mode(bool): ifTrue, enable gradient computation; ifFalse, disable gradient computation.
Return Value:
- Return a context manager that can be used to
withif statement.
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
)
Disable gradient computation
torch.
set_grad_enabled
(
False
)
y1
=
x *
2
(
"After disabling gradients:"
,
y1.
requires_grad
)
Enable gradient computation
torch.
set_grad_enabled
(
True
)
y2
=
x *
2
(
"After enabling gradients:"
,
y2.
requires_grad
)
The output is:
禁用梯度后: False
启用梯度后: True
Example 2: use as a context manager
Example
import
torch
x
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
]
,
requires_grad
=
True
)
Use a context manager
with
torch.
set_grad_enabled
(
False
)
:
y1
=
x *
2
(
"Inside the context manager:"
,
y1.
requires_grad
)
y2
=
x *
2
(
"Outside the context manager:"
,
y2.
requires_grad
)
The output is:
在上下文管理器内: False
在上下文管理器外: True
Example 3: dynamically control training and inference
Example
import
torch
import
torch.
nn
as
nn
model
=
nn.
Linear
(
10
,
2
)
def
forward_pass
(
x
,
training
=
True
)
:
"""Control gradients based on the training parameter"""
with
torch.
set_grad_enabled
(
training
)
:
output
=
model
(
x
)
(
f
"training={training}, requires_grad={output.requires_grad}"
)
return
output
Training mode
x
=
torch.
randn
(
5
,
10
)
forward_pass
(
x
,
training
=
True
)
Inference mode
forward_pass
(
x
,
training
=
False
)
The output is:
training=True, requires_grad=True
training=False, requires_grad=False
Example 4: save and restore gradient state
Example
import
torch
Initial state
(
"Initial state:"
,
torch.
is_grad_enabled
(
)
)
Create a context manager that restores the original state
old
=
torch.
is_grad_enabled
(
)
Temporarily disable gradients
with
torch.
set_grad_enabled
(
False
)
:
(
"Inside:"
,
torch.
is_grad_enabled
(
)
)
Automatic restore (but manual restore is needed here)
torch.
set_grad_enabled
(
old
)
(
"After restoring:"
,
torch.
is_grad_enabled
(
)
)
The output is:
初始状态: True
在内部: False
恢复后: True
Related functions
torch.no_grad(): A context manager that disables gradient computation.torch.enable_grad(): A context manager that enables gradient computation.torch.is_grad_enabled(): Check whether gradient computation is currently enabled.
Notes
set_grad_enabledIt can be called directly as a function to change the global state, or used as a context manager.- When called as a function, the original state must be restored manually, otherwise subsequent code will be affected.
- It is recommended to use the context manager approach to ensure the state is restored correctly.
- Be aware of the impact on global state and use it carefully in complex code.