"vscode:/vscode.git/clone" did not exist on "c5a4a1faf3c430c11f09128a6e1dc40b4736e212"
test_index.py 2.5 KB
Newer Older
1
2
3
4
import dgl
import dgl.ndarray as nd
from dgl.utils import toindex
import numpy as np
5
import backend as F
6
7
8
9
10
11
12
13
14

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()
15
        y = F.zerocopy_from_dlpack(dl)
16
        y[0] = 1
17
18
        print(x)
        print(y)
19
20
21
22
23
24
        assert np.allclose(x.asnumpy(), ans)

    def th2nd():
        ans = np.array([[1., 1., 1., 1.],
                        [0., 0., 0., 0.],
                        [0., 0., 0., 0.]])
25
26
        x = F.zeros((3, 4))
        dl = F.zerocopy_to_dlpack(x)
27
28
        y = nd.from_dlpack(dl)
        x[0] = 1
29
30
        print(x)
        print(y)
31
32
        assert np.allclose(y.asnumpy(), ans)

33
    def th2nd_incontiguous():
34
        x = F.astype(F.tensor([[0, 1], [2, 3]]), F.int64)
35
36
37
38
39
40
        ans = np.array([0, 2])
        y = x[:2, 0]
        # Uncomment this line and comment the one below to observe error
        #dl = dlpack.to_dlpack(y)
        dl = F.zerocopy_to_dlpack(y)
        z = nd.from_dlpack(dl)
41
42
        print(x)
        print(z)
43
44
        assert np.allclose(z.asnumpy(), ans)

45
46
    nd2th()
    th2nd()
47
    th2nd_incontiguous()
48
49
50
51
52
53

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)
54
    y1 = idx.tonumpy()
55
    y2 = F.asnumpy(idx.tousertensor())
56
57
58
59
60
61
62
63
    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)
64
    y1 = idx.tonumpy()
65
    y2 = F.asnumpy(idx.tousertensor())
66
67
68
69
70
    y3 = idx.todgltensor().asnumpy()
    assert np.allclose(ans, y1)
    assert np.allclose(ans, y2)
    assert np.allclose(ans, y3)

71
    # from dl tensor
72
    data = F.ones((10,), dtype=F.int64) * 10
73
    idx = toindex(data)
74
    y1 = idx.tonumpy()
75
    y2 = F.asnumpy(idx.tousertensor())
76
77
78
79
80
81
82
83
    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)
84
    y1 = idx.tonumpy()
85
    y2 = F.asnumpy(idx.tousertensor())
86
87
88
89
90
91
92
93
    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()