PyTorch torch.enable_grad function
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:
- No parameters. This is a context manager.
Return Value:
- Returns a context manager in which gradient computation is enabled.
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
]
)
(
"Inside no_grad:"
,
x.
requires_grad
)
Use enable_grad to temporarily enable gradients
with
torch.
enable_grad
(
)
:
y
=
x *
2
(
"Inside enable_grad:"
,
y.
requires_grad
)
The no_grad state is restored after exit
z
=
x *
2
(
"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
)
(
"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
)
(
"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
)
(
"Loss:"
,
loss
)
(
"Requires gradient:"
,
loss.
requires_grad
)
The output is:
Loss: tensor(6.)
需要梯度: True
Related functions
torch.no_grad(): Disable gradient computation.torch.set_grad_enabled(grad): Enable or disable gradient computation based on an argument.torch.is_grad_enabled(): Check whether gradient computation is currently enabled.
Notes
enable_gradMainly used to temporarily enable gradient computation in ano_gradcontext.- If used in an environment where gradients are globally enabled
enable_grad, it has no effect. - It is recommended to use the
enable_graddecorator to ensure gradients are always enabled inside a function.