Skip to content

torch.clamp kills gradients at the border #7002

@SevenBlocks

Description

@SevenBlocks

Issue description

torch.clamp() should only affect gradients for values outside the min and max range, but it also appears to affect values equal to the min or max. I.e. clamping the value 0 to min=0, max=1 should have no effect on the gradient for that value, but it does--the gradient is being set to 0.

Code example

a=Variable(torch.tensor([0.0]), requires_grad=True)

# Normal result, gradient of a with respect to a is 1
> torch.autograd.grad(a, a)
(tensor([ 1.]),)

# Incorrect result
> torch.autograd.grad(torch.clamp(a, 0, 1), a)
(tensor([ 0.]),)

# Setting the min just below 0 also produces the correct result
> torch.autograd.grad(torch.clamp(a, -0.1, 1), a)
(tensor([ 1.]),)

System Info

Collecting environment information...
PyTorch version: 0.4.0
Is debug build: No
CUDA used to build PyTorch: 8.0.61

OS: Ubuntu 16.04.4 LTS
GCC version: (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
CMake version: version 3.5.1

Python version: 3.5
Is CUDA available: Yes
CUDA runtime version: 9.0.176
GPU models and configuration:
GPU 0: GeForce GTX 980 Ti
GPU 1: GeForce GTX TITAN X

Nvidia driver version: 384.111
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.7.0.5
/usr/local/cuda-8.0/targets/x86_64-linux/lib/libcudnn.so.5.1.5
/usr/local/cuda-8.0/targets/x86_64-linux/lib/libcudnn.so.6.0.21
/usr/local/cuda-8.0/targets/x86_64-linux/lib/libcudnn_static.a

Versions of relevant libraries:
[pip3] numpy (1.14.1)
[pip3] torch (0.4.0)
[pip3] torchvision (0.2.0)
[conda] Could not collect

  • PyTorch or Caffe2:
  • How you installed PyTorch (conda, pip, source): pip
  • Build command you used (if compiling from source):
  • OS:
  • PyTorch version:
  • Python version:
  • CUDA/cuDNN version:
  • GPU models and configuration:
  • GCC version (if compiling from source):
  • CMake version:
  • Versions of any other relevant libraries:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions