1// RUN: mlir-opt %s --sparse-compiler | \
2// RUN: mlir-cpu-runner \
3// RUN:  -e entry -entry-point-result=void  \
4// RUN:  -shared-libs=%mlir_integration_test_dir/libmlir_c_runner_utils%shlibext | \
5// RUN: FileCheck %s
6
7#SparseVector = #sparse_tensor.encoding<{ dimLevelType = [ "compressed" ] }>
8
9#trait_op = {
10  indexing_maps = [
11    affine_map<(i) -> (i)>   // X (out)
12  ],
13  iterator_types = ["parallel"],
14  doc = "X(i) = OP X(i)"
15}
16
17module {
18  // Performs zero-preserving math to sparse vector.
19  func.func @sparse_tanh(%vec: tensor<?xf64, #SparseVector>)
20                       -> tensor<?xf64, #SparseVector> {
21    %0 = linalg.generic #trait_op
22      outs(%vec: tensor<?xf64, #SparseVector>) {
23        ^bb(%x: f64):
24          %1 = math.tanh %x : f64
25          linalg.yield %1 : f64
26    } -> tensor<?xf64, #SparseVector>
27    return %0 : tensor<?xf64, #SparseVector>
28  }
29
30  // Dumps a sparse vector of type f64.
31  func.func @dump_vec_f64(%arg0: tensor<?xf64, #SparseVector>) {
32    // Dump the values array to verify only sparse contents are stored.
33    %c0 = arith.constant 0 : index
34    %d0 = arith.constant -1.0 : f64
35    %0 = sparse_tensor.values %arg0
36      : tensor<?xf64, #SparseVector> to memref<?xf64>
37    %1 = vector.transfer_read %0[%c0], %d0: memref<?xf64>, vector<32xf64>
38    vector.print %1 : vector<32xf64>
39    // Dump the dense vector to verify structure is correct.
40    %dv = sparse_tensor.convert %arg0
41        : tensor<?xf64, #SparseVector> to tensor<?xf64>
42    %3 = vector.transfer_read %dv[%c0], %d0: tensor<?xf64>, vector<32xf64>
43    vector.print %3 : vector<32xf64>
44    return
45  }
46
47  // Driver method to call and verify vector kernels.
48  func.func @entry() {
49    // Setup sparse vector.
50    %v1 = arith.constant sparse<
51       [ [0], [3], [11], [17], [20], [21], [28], [29], [31] ],
52         [ -1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100.0 ]
53    > : tensor<32xf64>
54    %sv1 = sparse_tensor.convert %v1
55         : tensor<32xf64> to tensor<?xf64, #SparseVector>
56
57    // Call sparse vector kernel.
58    %0 = call @sparse_tanh(%sv1) : (tensor<?xf64, #SparseVector>)
59                                 -> tensor<?xf64, #SparseVector>
60
61    //
62    // Verify the results (within some precision).
63    //
64    // CHECK: {{( -0.761[0-9]*, 0.761[0-9]*, 0.96[0-9]*, 0.99[0-9]*, 0.99[0-9]*, 0.99[0-9]*, 0.99[0-9]*, 0.99[0-9]*, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 )}}
65    // CHECK-NEXT {{( -0.761[0-9]*, 0, 0, 0.761[0-9]*, 0, 0, 0, 0, 0, 0, 0, 0.96[0-9]*, 0, 0, 0, 0, 0, 0.99[0-9]*, 0, 0, 0.99[0-9]*, 0.99[0-9]*, 0, 0, 0, 0, 0, 0, 0.99[0-9]*, 0.99[0-9]*, 0, 1 )}}
66    //
67    call @dump_vec_f64(%0) : (tensor<?xf64, #SparseVector>) -> ()
68
69    // Release the resources.
70    bufferization.dealloc_tensor %sv1 : tensor<?xf64, #SparseVector>
71    return
72  }
73}
74