test_index.py 2.03 KB
Newer Older
1
2
3
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
32
33
34
35
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
67
68
69
70
71
72
73
74
75
76
77
import dgl
import dgl.ndarray as nd
from dgl.utils import toindex
import numpy as np
import torch as th
from torch.utils import dlpack

def test_dlpack():
    # test dlpack conversion.
    def nd2th():
        ans = np.array([[1., 1., 1., 1.],
                        [0., 0., 0., 0.],
                        [0., 0., 0., 0.]])
        x = nd.array(np.zeros((3, 4), dtype=np.float32))
        dl = x.to_dlpack()
        y = dlpack.from_dlpack(dl)
        y[0] = 1
        assert np.allclose(x.asnumpy(), ans)

    def th2nd():
        ans = np.array([[1., 1., 1., 1.],
                        [0., 0., 0., 0.],
                        [0., 0., 0., 0.]])
        x = th.zeros((3, 4))
        dl = dlpack.to_dlpack(x)
        y = nd.from_dlpack(dl)
        x[0] = 1
        assert np.allclose(y.asnumpy(), ans)

    nd2th()
    th2nd()

def test_index():
    ans = np.ones((10,), dtype=np.int64) * 10
    # from np data
    data = np.ones((10,), dtype=np.int64) * 10
    idx = toindex(data)
    y1 = idx.tolist()
    y2 = idx.tousertensor().numpy()
    y3 = idx.todgltensor().asnumpy()
    assert np.allclose(ans, y1)
    assert np.allclose(ans, y2)
    assert np.allclose(ans, y3)

    # from list
    data = [10] * 10
    idx = toindex(data)
    y1 = idx.tolist()
    y2 = idx.tousertensor().numpy()
    y3 = idx.todgltensor().asnumpy()
    assert np.allclose(ans, y1)
    assert np.allclose(ans, y2)
    assert np.allclose(ans, y3)

    # from torch
    data = th.ones((10,), dtype=th.int64) * 10
    idx = toindex(data)
    y1 = idx.tolist()
    y2 = idx.tousertensor().numpy()
    y3 = idx.todgltensor().asnumpy()
    assert np.allclose(ans, y1)
    assert np.allclose(ans, y2)
    assert np.allclose(ans, y3)

    # from dgl.NDArray
    data = dgl.ndarray.array(np.ones((10,), dtype=np.int64) * 10)
    idx = toindex(data)
    y1 = idx.tolist()
    y2 = idx.tousertensor().numpy()
    y3 = idx.todgltensor().asnumpy()
    assert np.allclose(ans, y1)
    assert np.allclose(ans, y2)
    assert np.allclose(ans, y3)

if __name__ == '__main__':
    test_dlpack()
    test_index()