test_local_gemm.py 1.98 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
17
import tvm
18
from tvm import te
19 20 21
import numpy as np

def test_local_gemm():
22
    if not tvm.runtime.enabled("opengl"):
23
        return
24
    if not tvm.runtime.enabled("llvm"):
25 26
        return

27
    nn = 1024
28 29
    n = te.var('n')
    n = tvm.runtime.convert(nn)
30 31
    m = n
    l = n
32 33 34 35
    A = te.placeholder((n, l), name='A', dtype='int32')
    B = te.placeholder((m, l), name='B', dtype='int32')
    k = te.reduce_axis((0, l), name='k')
    C = te.compute((n, m), lambda ii, jj: te.sum(A[ii, k] * B[jj, k], axis=k),
36 37
                    name='CC')

38
    s = te.create_schedule(C.op)
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
    s[C].opengl()
    print(tvm.lower(s, [A, B, C], simple_mode=True))

    f = tvm.build(s, [A, B, C], "opengl", name="gemm")
    print("------opengl code------")
    print(f.imported_modules[0].get_source(fmt="gl"))

    ctx = tvm.opengl()
    n, m, l = nn, nn, nn
    a_np = np.random.uniform(low=0, high=10, size=(n, l)).astype(A.dtype)
    b_np = np.random.uniform(low=0, high=10, size=(m, l)).astype(B.dtype)
    a = tvm.nd.array(a_np, ctx)
    b = tvm.nd.array(b_np, ctx)
    c = tvm.nd.array(np.zeros((n, m), dtype=C.dtype), ctx)
    f(a, b, c)

55
    tvm.testing.assert_allclose(c.asnumpy(), np.dot(a_np, b_np.T))
56 57 58

if __name__ == "__main__":
    test_local_gemm()