1// RUN: mlir-opt %s \
2// RUN:   --sparsification --sparse-tensor-conversion \
3// RUN:   --convert-vector-to-scf --convert-scf-to-std \
4// RUN:   --func-bufferize --tensor-constant-bufferize --tensor-bufferize \
5// RUN:   --std-bufferize --finalizing-bufferize  \
6// RUN:   --convert-vector-to-llvm --convert-memref-to-llvm --convert-std-to-llvm | \
7// RUN: mlir-cpu-runner \
8// RUN:  -e entry -entry-point-result=void  \
9// RUN:  -shared-libs=%mlir_integration_test_dir/libmlir_c_runner_utils%shlibext | \
10// RUN: FileCheck %s
11
12#CSR = #sparse_tensor.encoding<{ dimLevelType = [ "dense", "compressed" ] }>
13
14#trait_scale = {
15  indexing_maps = [
16    affine_map<(i,j) -> (i,j)>   // X (out)
17  ],
18  iterator_types = ["parallel", "parallel"],
19  doc = "X(i,j) = X(i,j) * 2"
20}
21
22//
23// Integration test that lowers a kernel annotated as sparse to actual sparse
24// code, initializes a matching sparse storage scheme from a dense tensor,
25// and runs the resulting code with the JIT compiler.
26//
27module {
28  //
29  // A kernel that scales a sparse matrix A by a factor of 2.0.
30  //
31  func @sparse_scale(%argx: tensor<8x8xf32, #CSR>
32                     {linalg.inplaceable = true}) -> tensor<8x8xf32, #CSR> {
33    %c = constant 2.0 : f32
34    %0 = linalg.generic #trait_scale
35      outs(%argx: tensor<8x8xf32, #CSR>) {
36        ^bb(%x: f32):
37          %1 = mulf %x, %c : f32
38          linalg.yield %1 : f32
39    } -> tensor<8x8xf32, #CSR>
40    return %0 : tensor<8x8xf32, #CSR>
41  }
42
43  //
44  // Main driver that converts a dense tensor into a sparse tensor
45  // and then calls the sparse scaling kernel with the sparse tensor
46  // as input argument.
47  //
48  func @entry() {
49    %c0 = constant 0 : index
50    %f0 = constant 0.0 : f32
51
52    // Initialize a dense tensor.
53    %0 = constant dense<[
54       [1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0],
55       [0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
56       [0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0],
57       [0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0],
58       [0.0, 1.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0],
59       [0.0, 1.0, 1.0, 0.0, 0.0, 6.0, 0.0, 0.0],
60       [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 7.0, 1.0],
61       [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 8.0]
62    ]> : tensor<8x8xf32>
63
64    // Convert dense tensor to sparse tensor and call sparse kernel.
65    %1 = sparse_tensor.convert %0 : tensor<8x8xf32> to tensor<8x8xf32, #CSR>
66    %2 = call @sparse_scale(%1)
67      : (tensor<8x8xf32, #CSR>) -> tensor<8x8xf32, #CSR>
68
69    // Print the resulting compacted values for verification.
70    //
71    // CHECK: ( 2, 2, 2, 4, 6, 8, 2, 10, 2, 2, 12, 2, 14, 2, 2, 16 )
72    //
73    %m = sparse_tensor.values %2 : tensor<8x8xf32, #CSR> to memref<?xf32>
74    %v = vector.transfer_read %m[%c0], %f0: memref<?xf32>, vector<16xf32>
75    vector.print %v : vector<16xf32>
76
77    return
78  }
79}
80