1# RUN: SUPPORT_LIB=%mlir_runner_utils_dir/libmlir_c_runner_utils%shlibext \
2# RUN:   %PYTHON %s | FileCheck %s
3
4import ctypes
5import numpy as np
6import os
7import sys
8
9from mlir import ir
10from mlir import runtime as rt
11from mlir import execution_engine
12
13from mlir.dialects import sparse_tensor as st
14from mlir.dialects import builtin
15from mlir.dialects import func
16from mlir.dialects.linalg.opdsl import lang as dsl
17
18_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
19sys.path.append(_SCRIPT_PATH)
20from tools import sparse_compiler
21
22@dsl.linalg_structured_op
23def matmul_dsl(
24    A=dsl.TensorDef(dsl.T, dsl.S.M, dsl.S.K),
25    B=dsl.TensorDef(dsl.T, dsl.S.K, dsl.S.N),
26    C=dsl.TensorDef(dsl.T, dsl.S.M, dsl.S.N, output=True)):
27  C[dsl.D.m, dsl.D.n] += A[dsl.D.m, dsl.D.k] * B[dsl.D.k, dsl.D.n]
28
29
30def build_SpMM(attr: st.EncodingAttr):
31  """Build SpMM kernel.
32
33  This method generates a linalg op with for matrix multiplication using
34  just the Python API. Effectively, a generic linalg op is constructed
35  that computes C(i,j) += A(i,k) * B(k,j) for annotated matrix A.
36  """
37  module = ir.Module.create()
38  f64 = ir.F64Type.get()
39  a = ir.RankedTensorType.get([3, 4], f64, attr)
40  b = ir.RankedTensorType.get([4, 2], f64)
41  c = ir.RankedTensorType.get([3, 2], f64)
42  arguments = [a, b, c]
43  with ir.InsertionPoint(module.body):
44
45    @func.FuncOp.from_py_func(*arguments)
46    def spMxM(*args):
47      return matmul_dsl(args[0], args[1], outs=[args[2]])
48
49  return module
50
51
52def boilerplate(attr: st.EncodingAttr):
53  """Returns boilerplate main method.
54
55  This method sets up a boilerplate main method that takes three tensors
56  (a, b, c), converts the first tensor a into s sparse tensor, and then
57  calls the sparse kernel for matrix multiplication. For convenience,
58  this part is purely done as string input.
59  """
60  return f"""
61func @main(%ad: tensor<3x4xf64>, %b: tensor<4x2xf64>, %c: tensor<3x2xf64>) -> tensor<3x2xf64>
62  attributes {{ llvm.emit_c_interface }} {{
63  %a = sparse_tensor.convert %ad : tensor<3x4xf64> to tensor<3x4xf64, {attr}>
64  %0 = call @spMxM(%a, %b, %c) : (tensor<3x4xf64, {attr}>,
65                                  tensor<4x2xf64>,
66                                  tensor<3x2xf64>) -> tensor<3x2xf64>
67  return %0 : tensor<3x2xf64>
68}}
69"""
70
71
72def build_compile_and_run_SpMM(attr: st.EncodingAttr, support_lib: str,
73                               compiler):
74  # Build.
75  module = build_SpMM(attr)
76  func = str(module.operation.regions[0].blocks[0].operations[0].operation)
77  module = ir.Module.parse(func + boilerplate(attr))
78
79  # Compile.
80  compiler(module)
81  engine = execution_engine.ExecutionEngine(
82      module, opt_level=0, shared_libs=[support_lib])
83
84  # Set up numpy input and buffer for output.
85  a = np.array(
86      [[1.1, 0.0, 0.0, 1.4], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 3.3, 0.0]],
87      np.float64)
88  b = np.array([[1.0, 2.0], [4.0, 3.0], [5.0, 6.0], [8.0, 7.0]], np.float64)
89  c = np.zeros((3, 2), np.float64)
90
91  mem_a = ctypes.pointer(ctypes.pointer(rt.get_ranked_memref_descriptor(a)))
92  mem_b = ctypes.pointer(ctypes.pointer(rt.get_ranked_memref_descriptor(b)))
93  mem_c = ctypes.pointer(ctypes.pointer(rt.get_ranked_memref_descriptor(c)))
94  # Allocate a MemRefDescriptor to receive the output tensor.
95  # The buffer itself is allocated inside the MLIR code generation.
96  ref_out = rt.make_nd_memref_descriptor(2, ctypes.c_double)()
97  mem_out = ctypes.pointer(ctypes.pointer(ref_out))
98
99  # Invoke the kernel and get numpy output.
100  # Built-in bufferization uses in-out buffers.
101  # TODO: replace with inplace comprehensive bufferization.
102  engine.invoke('main', mem_out, mem_a, mem_b, mem_c)
103
104  # Sanity check on computed result.
105  expected = np.matmul(a, b);
106  c = rt.ranked_memref_to_numpy(mem_out[0])
107  if np.allclose(c, expected):
108    pass
109  else:
110    quit(f'FAILURE')
111
112
113def main():
114  support_lib = os.getenv('SUPPORT_LIB')
115  assert support_lib is not None, 'SUPPORT_LIB is undefined'
116  if not os.path.exists(support_lib):
117    raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), support_lib)
118
119  # CHECK-LABEL: TEST: testSpMM
120  print('\nTEST: testSpMM')
121  with ir.Context() as ctx, ir.Location.unknown():
122    count = 0
123    # Loop over various ways to compile and annotate the SpMM kernel with
124    # a *single* sparse tensor. Note that we deliberate do not exhaustively
125    # search the full state space to reduce runtime of the test. It is
126    # straightforward to adapt the code below to explore more combinations.
127    par = 0
128    vec = 0
129    vl = 1
130    e = False
131    opt = (f'parallelization-strategy={par} '
132           f'vectorization-strategy={vec} '
133           f'vl={vl} enable-simd-index32={e}')
134    levels = [[st.DimLevelType.dense, st.DimLevelType.dense],
135              [st.DimLevelType.dense, st.DimLevelType.compressed],
136              [st.DimLevelType.compressed, st.DimLevelType.dense],
137              [st.DimLevelType.compressed, st.DimLevelType.compressed]]
138    orderings = [
139        ir.AffineMap.get_permutation([0, 1]),
140        ir.AffineMap.get_permutation([1, 0])
141    ]
142    bitwidths = [0]
143    for level in levels:
144      for ordering in orderings:
145        for pwidth in bitwidths:
146          for iwidth in bitwidths:
147            attr = st.EncodingAttr.get(level, ordering, pwidth, iwidth)
148            compiler = sparse_compiler.SparseCompiler(options=opt)
149            build_compile_and_run_SpMM(attr, support_lib, compiler)
150            count = count + 1
151    # CHECK: Passed 8 tests
152    print('Passed ', count, 'tests')
153
154
155if __name__ == '__main__':
156  main()
157