Range limiting
Keep activations or model outputs within a numerically safe interval.
PyTorch · Function
Clamps every element of a tensor to a chosen lower and/or upper bound. Either bound can be omitted, and the bounds may be scalar values or tensors.
torch.clamp applies lower and upper bounds element-wise. Values below min become min, values above max become max, and values within the interval remain unchanged; either bound may be omitted with None.
torch.clamp(input, min=None, max=None, *, out=None) → Tensor| Name | Type | Description |
|---|---|---|
input | Tensor | Input tensor whose elements are bounded. |
min | Number or Tensor, optional | Optional lower bound; may be a number or tensor. |
max | Number or Tensor, optional | Optional upper bound; may be a number or tensor. |
out | Tensor, optional; keyword-only | Optional destination tensor. |
Tensor
import torch
x = torch.tensor([-2.0, 0.25, 3.0])
y = torch.clamp(x, min=-1.0, max=1.0)
print(y) # tensor([-1.0000, 0.2500, 1.0000])Bounds each element of the input tensor between -1 and 1.
Keep activations or model outputs within a numerically safe interval.
Apply a one-sided threshold without changing values on the other side.
Use tensor-valued bounds when limits vary by position.
It clamps each input element into the interval defined by min and max. An omitted min removes the lower bound, while an omitted max removes the upper bound.
Follow-up: What happens if min is greater than max? The result contains max at every position.
The input parameter is a tensor. min and max can each be a number or tensor, and out is an optional output tensor supplied as a keyword argument.
Follow-up: How can you apply only an upper bound? Pass max and leave min as None.
The function returns a Tensor whose elements satisfy the requested bounds. For each element, the operation is equivalent to first applying the lower bound and then the upper bound.
Follow-up: What is the in-place counterpart? torch.clamp_ provides the in-place version.
torch.clamp_torch.Tensor.clamptorch.foreach.clamp_max