A difference between np.clamp and torch.clamp, any possible workaround?

In numpy, while using np.clamp(x, min, max) we can pass an array of min/max values but pytorch only accepts an integer.

>>> a = np.array([0.4, 10, 0.1])
>>> np.clip(a, [0.3, 0.4,0.5], [0.9, 0.99, 0.999])
array([0.4 , 0.99, 0.5 ])

>>> a = torch.tensor([0.4, 10, 0.1])
>>> torch.clamp(a, [0.3, 0.4,0.5], [0.9, 0.99, 0.999])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: clamp(): argument 'min' (position 2) must be Number, not list

Is there any way I can use torch directly to clamp the values using an array instead of converting the torch.tensor to numpy array and then use np.clip to clip the values and then reconverting them back to torch.tensor?

Or is there any method that would clip the elements of an array to a percentage value? For example, if I pass the value of 10, an element of array with value 100 will be clipped minimum of 90, maximum of 110.

I’m not aware of this functionality in PyTorch and torch.clamp as well as torch.clip (alias for clamp) expect single numbers as the min and max arguments.

CC @mruberry for numpy compatibility.

1 Like

Sorry, @hrushi, unfortunately I don’t think there’s a great workaround available today (at least not one better than you’re using). This is a popular request, and I’ve updated the Github issue tracking it (see Support `clamp()` with tensor min and max · Issue #2793 · pytorch/pytorch · GitHub) to be “high priority” so this functionality is provided quickly.