Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

PyTorch · Function

torch.clamp

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.

How it works

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.

Syntax

torch.clamp(input, min=None, max=None, *, out=None) → Tensor

Parameters

NameTypeDescription
inputTensorInput tensor whose elements are bounded.
minNumber or Tensor, optionalOptional lower bound; may be a number or tensor.
maxNumber or Tensor, optionalOptional upper bound; may be a number or tensor.
outTensor, optional; keyword-onlyOptional destination tensor.

Returns

Tensor

Key points

  • The operation processes every element and restricts it to the specified interval.
  • Set min to None when only an upper limit is needed.
  • Set max to None when only a lower limit is needed.
  • The lower bound may be a scalar number or a tensor.
  • The upper bound may be a scalar number or a tensor.
  • An optional output tensor can receive the result through the keyword-only out argument.

Common mistakes

  • When min exceeds max, every input element is replaced by max rather than producing an error.

Example: Clamp tensor values to an interval

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.

When to use it

Range limiting

Keep activations or model outputs within a numerically safe interval.

One-sided clipping

Apply a one-sided threshold without changing values on the other side.

Element-specific bounds

Use tensor-valued bounds when limits vary by position.

Interview questions

QWhat does torch.clamp do when both bounds are provided?

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.

QWhat types can the bounds have?

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.

QWhat does torch.clamp return?

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.clamp
  • torch.foreach.clamp_max

Source: torch.clamp — PyTorch 2.13 documentation. Checked 2026-10-16.