Why is torch.Tensor.fill_() not named torch.Tensor.fill()?

I’m curious why this API is named with a trailing underscore, how do we know whether there should be a trailing underscore or not without referring to the documentation? Curious what is the convention here

Hi,

There is a tensor.function_ for every tensor.function. The difference is that first one is in-place operation while the latter is not. Both of them use same operations.
In this page (and some others), you will find similar functions.

For instance,

x = torch.tensor([1,2,3])
print(x)  # tensor([1, 2, 3])
print(x.add(1)) # tensor([2, 3, 4])
print(x)  # tensor([1, 2, 3])
print(x.add_(1))  # tensor([2, 3, 4])  -> inplace operation, changes the value of x in memory
print(x)  # tensor([2, 3, 4])

Bests

1 Like