PyTorch how to set the minimum value along each row of a tensor to zero?
We don't know the shape of the input tensor and we shouldn't use any loops. Only reduction and indexing operations. How do we set the minimum value of each row to zero?
For example:
input:
x = torch.tensor([[
      [10, 20, 30]
      [2, 5, 1]
    ]])

output:
torch.tensor([
  [0, 20, 30],
  [2, 5, 0]
])

I couldn't figure it out and couldn't find any related questions. I'm stuck.

One way to do so is to compute row-wise minimum x.min(dim=-1), get minimal values x.min(dim=-1).values (indices won't work in case of multiple minimal elements), get mask indicating locations of non-minimal elements using comparison and multiply by it:
axis = -1  # Minimum iterating over the last dimension
min_values = x.min(dim=axis).values  # Get minimal values
min_values_shape_corrected = min_values.unsqueeze(axis)  # Reshape the minimal values so we can compare it with `x`
mask = (x != min_values_shape_corrected)  # Get the mask of non-minimal elements
result = x * mask  # Multiplying by a boolean mask leaves only True elements and sets False ones to 0

Or in one line
x * (x != x.min(dim=axis).values.unsqueeze(axis))

