test_topi_softmax.py 2.36 KB
Newer Older
1 2 3 4 5
"""Test code for softmax"""
import os
import numpy as np
import tvm
import topi
6
import topi.testing
7
import logging
8 9 10 11 12
from topi.util import get_const_tuple

def verify_softmax(m, n):
    A = tvm.placeholder((m, n), name='A')
    B = topi.nn.softmax(A)
13 14 15 16
    # confirm lower works
    s = tvm.create_schedule([B.op])
    tvm.lower(s, [A, B], simple_mode=True)

17 18 19 20
    a_np = np.random.uniform(size=get_const_tuple(A.shape)).astype(A.dtype)
    b_np = topi.testing.softmax_python(a_np)

    def check_device(device):
21 22
        ctx = tvm.context(device, 0)
        if not ctx.exist:
23 24
            print("Skip because %s is not enabled" % device)
            return
25
        print("Running on target: %s" % device)
26 27
        with tvm.target.create(device):
            s = topi.generic.schedule_softmax(B)
28

29 30 31 32 33 34
        a = tvm.nd.array(a_np, ctx)
        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), ctx)
        foo = tvm.build(s, [A, B], device, name="softmax")
        foo(a, b)
        np.testing.assert_allclose(b.asnumpy(), b_np, rtol=1e-5)

35
    for device in ['cuda', 'opencl', 'metal', 'rocm', 'vulkan']:
36
        check_device(device)
37 38 39

def test_softmax():
    verify_softmax(32, 10)
40
    verify_softmax(3, 4)
41 42


43 44 45 46 47 48 49 50 51 52
def verify_log_softmax(m, n):
    A = tvm.placeholder((m, n), name='A')
    B = topi.nn.log_softmax(A)
    # confirm lower works
    s = tvm.create_schedule([B.op])
    tvm.lower(s, [A, B], simple_mode=True)
    a_np = np.random.uniform(size=get_const_tuple(A.shape)).astype(A.dtype)
    b_np = topi.testing.log_softmax_python(a_np)

    def check_device(device):
53 54
        ctx = tvm.context(device, 0)
        if not ctx.exist:
55 56
            print("Skip because %s is not enabled" % device)
            return
57
        print("Running on target: %s" % device)
58 59
        with tvm.target.create(device):
            s = topi.generic.schedule_softmax(B)
60 61 62 63 64 65
        a = tvm.nd.array(a_np, ctx)
        b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), ctx)
        foo = tvm.build(s, [A, B], device, name="log_softmax")
        foo(a, b)
        np.testing.assert_allclose(b.asnumpy(), b_np, rtol=1e-5)

66
    for device in ["cuda", "opencl", "metal", "rocm", "vulkan"]:
67 68
        check_device(device)

69

70 71 72 73
def test_log_softmax():
    verify_log_softmax(32, 10)
    verify_log_softmax(3, 4)

74
if __name__ == "__main__":
75
    logging.basicConfig(level=logging.DEBUG)
76
    test_softmax()
77
    test_log_softmax()