PyTorch torch.no_grad function
PyTorch torch reference manual
torch.no_grad is a context manager in PyTorch used to disable gradient computation. Within a no_grad block, tensors created will not have gradients computed, which can significantly reduce memory consumption and improve inference speed.
This is essential during model inference and evaluation, greatly improving performance and saving memory.
Function definition
torch.no_grad()
Parameters:
- No parameters. This is a context manager.
Return Value:
- Returns a context manager in which gradient computation is disabled.
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
)
Compute within the no_grad context
with
torch.
no_grad
(
)
:
y
=
x *
2
(
"Inside no_grad:"
,
y.
requires_grad
)
Outside no_grad
z
=
x *
2
(
"Outside no_grad:"
,
z.
requires_grad
)
The output is:
在 no_grad 中: False
在 no_grad 外: True
Example 2: Model inference
Example
import
torch
import
torch.
nn
as
nn
Define a simple model
model
=
nn.
Linear
(
10
,
2
)
Create input data
x
=
torch.
randn
(
1
,
10
)
Use no_grad during inference
with
torch.
no_grad
(
)
:
output
=
model
(
x
)
(
"Output:"
,
output
)
No need to compute gradients
Or use a decorator
@torch.no_grad()
def predict(x):
return model(x)
The output is:
输出: tensor([[0.0920, 0.3557]])
Example 3: Evaluation mode
Example
import
torch
import
torch.
nn
as
nn
model
=
nn.
Sequential
(
nn.
Linear
(
10
,
5
)
,
nn.
ReLU
(
)
,
nn.
Linear
(
5
,
2
)
)
Switch to evaluation mode
model.
eval
(
)
Prepare test data
test_input
=
torch.
randn
(
5
,
10
)
Disable gradients during evaluation
with
torch.
no_grad
(
)
:
predictions
=
model
(
test_input
)
(
"Prediction result shape:"
,
predictions.
shape
)
The output is:
预测结果形状: torch.Size([5, 2])
Example 4: Compare memory usage
Example
import
torch
import
torch.
nn
as
nn
model
=
nn.
Linear
(
1000
,
1000
)
Create a large amount of input
inputs
=
[
torch.
randn
(
100
,
1000
)
for
_
in
range
(
100
)
]
Without no_grad (gradient history is recorded)
(
"Without no_grad:"
)
for
inp
in
inputs
[
:
5
]
:
_
=
model
(
inp
)
With no_grad (no gradient history recorded)
(
"With no_grad:"
)
with
torch.
no_grad
(
)
:
for
inp
in
inputs
[
:
5
]
:
_
=
model
(
inp
)
Use no_grad It can significantly reduce memory consumption because gradient information does not need to be stored for intermediate variables.
Related functions
torch.enable_grad(): Enable gradient computation (the opposite ofno_gradno_grad).torch.set_grad_enabled(grad): Enable or disable gradient computation based on an argument.torch.inference_mode(): A stricter inference mode that disables both gradient computation and autograd.
Notes
- During model inference and evaluation, always use
torch.no_grad()to save memory and improve speed. - If the file has been modified after the time specified in
no_gradVariables created inside a block that need to be used outside the block must be copied out manually. - The difference between
model.eval()It works best when used together.