PyTorch degree with negative power produces error?

Viewed 186

I am getting a confusing error that I'm not sure why is occurring. This is the error I am getting:

torch.Size([24047])
tensor([1315, 1318, 1472, 1454, 1318, 1337, 1453, 1454, 1317, 1310])

Traceback (most recent call last):
    ...
    deg_inv = deg.pow(-1)
RuntimeError: Integers to negative integer powers are not allowed.

And this is part of the code:

from torch_scatter import scatter_add
from torch_geometric.utils import add_remaining_self_loops, add_self_loops, remove_self_loops
...
    if edge_weight ==None:
        edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype,
                                     device=edge_index.device)
    fill_value = 1
    edge_index, edge_weight = add_self_loops(
        edge_index, edge_weight, fill_value, num_nodes)  
    row, col = edge_index
    deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)

    print(deg.size())
    print(deg[:10])

    deg_inv = deg.pow(-1) 

I have not found anything related to this online. I'm not sure why this would be occurring?

1 Answers

Your deg tensor is stored as int type. Quite reasonably, if you do a binary operation between integer-type tensors, it is assumed that you should still get integer output. However, with pow, if the input is 2 and the power is -1, even though both operands are of integer type, the output 0.5 is not. And I guess pytorch simply forbids this.

To solve it, either turn the input deg to float first:

deg = deg.float()
deg_inv = deg.pow(-1)

or pass -1. in pow:

deg_inv = deg.pow(-1.)
Related