Creating a tensor

Hi everybody,
I am banging my head around a seemingly naive issue: how to create tensors in MLIR?

The code snippet I have is as follows:

!type_out= type memref<512x512xf32
func @test() -> !type_out{
  // How can I do this?
  %tensor = tensor.allocate() : !type_out
  // ****
  return %tnsr : !type_out
}

Thanks for any help, as usual!

Giuseppe

Hi,

In MLIR, tensors and memory references are of 2 different data types (tensor<?x?xTy> and memref<?x?xTy>).

You can declare (and initialize) tensor types with linalg.init_tensor (and linalg.fill).
You can also declare a constant tensor :

  • %0 = constant dense<[[0, 1], [2, 3]]> : tensor<2x2xi32>

You can allocate (and initialize) memref types with memref.alloc or memref.alloca (and linalg.fill which also works with memref types).

I would advise looking for these operations in the llvm-project/mlir/test folder.
E.g:

  • llvm-project/mlir/test/Integration/Dialect/Linalg/CPU/test-conv-1d-call.mlir
  • llvm-project/mlir/test/Transforms/print-op-graph.mlir
  • llvm-project/mlir/test/Integration/Dialect/Linalg/CPU/test-comprehensive-bufferize.mlir

Cheers!

Hi @agostini01 ,
Thank you so much for you reply! The init_tensor + fill solution works like a charm :slight_smile:

I tried the way of a constant declaration, but my matrices are quite big and that was producing a huge LLVM-IR to fill the constant.

I am sharing here my clumsier way I found to obtain (possibly) the same result:

  %Cd = tensor.generate %m, %n {{
  ^bb0(%i : index, %j : index):
    %elem = arith.constant 1.0 : f32
    tensor.yield %elem : f32
  }} : tensor<?x?xf32>
  %C= tensor.cast %Cd : tensor<?x?xf32> to !tensor<512x512xf32>

Thank you once more,
Giuseppe