array.py 1.92 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
import migraphx, struct, array, sys
try:
    from functools import reduce
except:
    pass
Paul's avatar
Paul committed
6
7
8
9
10
11
12
13
14
15

def assert_eq(x, y):
    if x == y:
        pass
    else:
        raise Exception(str(x) + " != " + str(y))

def read_float(b, index):
    return struct.unpack_from('f', b, index*4)[0]

Paul's avatar
Paul committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def write_float(b, index):
    struct.pack_into('f', b, index*4)

def nelements(lens):
    return reduce(lambda x,y: x*y,lens, 1)

def create_buffer(t, data):
    a = array.array(t, data)
    if sys.version_info >= (3, 0):
        m = memoryview(a.tobytes())
        return m.cast(t)
    else:
        m = memoryview(a.tostring())
        return m

def check_argument(a):
Paul's avatar
Paul committed
32
33
    l = a.tolist()
    for i in range(len(l)):
Paul's avatar
Paul committed
34
        assert_eq(l[i], read_float(a, i))
Paul's avatar
Paul committed
35

Paul's avatar
Paul committed
36
37
38
39
40
41
42
43
def check_shapes(r, m):
    lens = list(m.shape)
    strides = [s/m.itemsize for s in m.strides]
    elements = nelements(lens)
    assert_eq(r.get_shape().elements(), elements)
    assert_eq(r.get_shape().lens(), lens)
    assert_eq(r.get_shape().strides(), strides)

Paul's avatar
Paul committed
44
45
46
47
48
49
50
def run(p):
    params = {}
    for key, value in p.get_parameter_shapes().items():
        params[key] = migraphx.to_gpu(migraphx.generate_argument(value))

    return migraphx.from_gpu(p.run(params))

Paul's avatar
Paul committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def test_input():
    data = list(range(4))
    m = create_buffer('f', data)
    if sys.version_info >= (3, 0):
        a = migraphx.argument(m)
        check_shapes(a, m)
        assert_eq(a.tolist(), data)
    else:
        a1 = migraphx.argument(m)
        a2 = migraphx.argument(bytearray(a1))
        check_shapes(a2, m)
        assert_eq(a1.tolist(), m.tolist())


def test_output():
    p = migraphx.parse_onnx("conv_relu_maxpool.onnx")
    p.compile(migraphx.get_target("gpu"))
68

Paul's avatar
Paul committed
69
70
71
72
    r1 = run(p)
    r2 = run(p)
    assert_eq(r1, r2)
    assert_eq(r1.tolist(), r2.tolist())
73

Paul's avatar
Paul committed
74
75
    check_argument(r1)
    check_argument(r2)
Paul's avatar
Paul committed
76

Paul's avatar
Paul committed
77
78
    m1 = memoryview(r1)
    m2 = memoryview(r2)
Paul's avatar
Paul committed
79

Paul's avatar
Paul committed
80
81
    check_shapes(r1, m1)
    check_shapes(r2, m2)
Paul's avatar
Paul committed
82

83

Paul's avatar
Paul committed
84
85
test_input()
test_output()