test_jit.py 2.25 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
2
import torch

rusty1s's avatar
rusty1s committed
3
from torch_sparse import SparseStorage, SparseTensor
rusty1s's avatar
rusty1s committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

from typing import Dict, Any

# class MyTensor(dict):
#     def __init__(self, rowptr, col):
#         self['rowptr'] = rowptr
#         self['col'] = col

# def rowptr(self: Dict[str, torch.Tensor]):
#     return self['rowptr']


@torch.jit.script
class Foo:
    rowptr: torch.Tensor
    col: torch.Tensor

    def __init__(self, rowptr: torch.Tensor, col: torch.Tensor):
        self.rowptr = rowptr
        self.col = col


class MyCell(torch.nn.Module):
    def __init__(self):
        super(MyCell, self).__init__()
        self.linear = torch.nn.Linear(2, 4)

    # def forward(self, x: torch.Tensor, ptr: torch.Tensor) -> torch.Tensor:
rusty1s's avatar
rusty1s committed
32
33
34
35
    def forward(self, x: torch.Tensor, adj: SparseTensor) -> torch.Tensor:
        out, _ = torch.ops.torch_sparse_cpu.spmm(adj.storage.rowptr(),
                                                 adj.storage.col(), None, x,
                                                 'sum')
rusty1s's avatar
rusty1s committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        return out


#         ind = torch.ops.torch_sparse_cpu.ptr2ind(ptr, ptr[-1].item())
#         # ind = ptr2ind(ptr, E)
#         x_j = x[ind]
#         out = self.linear(x_j)
#         return out


def test_jit():
    my_cell = MyCell()

    # x = torch.rand(3, 2)
    # ptr = torch.tensor([0, 2, 4, 6])
    # out = my_cell(x, ptr)
    # print()
    # print(out)

    # traced_cell = torch.jit.trace(my_cell, (x, ptr))
    # print(traced_cell)
    # out = traced_cell(x, ptr)
    # print(out)

    x = torch.randn(3, 2)

    # adj = torch.randn(3, 3)
    # adj = SparseTensor.from_dense(adj)
    # adj = Foo(adj.storage.rowptr, adj.storage.col)
    # adj = adj.storage

rusty1s's avatar
repr  
rusty1s committed
67
68
    rowptr = torch.tensor([0, 1, 4, 7])
    col = torch.tensor([0, 0, 1, 2, 0, 1, 2])
rusty1s's avatar
rusty1s committed
69

rusty1s's avatar
rusty1s committed
70
    adj = SparseTensor(rowptr=rowptr, col=col)
rusty1s's avatar
repr  
rusty1s committed
71
72
73
74
    # scipy = adj.to_scipy(layout='csr')
    # mat = SparseTensor.from_scipy(scipy)
    print()
    print(adj)
rusty1s's avatar
rusty1s committed
75
76
77
78
    # adj = t(adj)
    adj = adj.t()
    print(adj)
    # print(adj.t)
rusty1s's avatar
rusty1s committed
79
80
81
82
83
84
85
86
87
88

    # adj = {'rowptr': mat.storage.rowptr, 'col': mat.storage.col}
    # foo = Foo(mat.storage.rowptr, mat.storage.col)
    # adj = MyTensor(mat.storage.rowptr, mat.storage.col)

    traced_cell = torch.jit.script(my_cell)
    print(traced_cell)
    out = traced_cell(x, adj)
    print(out)
    # # print(traced_cell.code)