[mlir][One-Shot Bufferizer] Customizable tensor <-> memref conversions

Hello,

Our downstream recently started to migrate to one-shot bufferization and the existing design (LLVM 17 for us but main seems to be affected as well) doesn’t really work for us.
The topic of this discussion is around the conversions from tensors to memrefs and from memrefs to tensors. From what I can tell, the existing conversion logic is very limited and extremely rigid. Our downstream has the following:

  • custom tensors and custom memrefs (and they do not inherit respective MLIR-native types)
  • mlir::RankedTensorType with custom encoding attribute
  • mlir::MemRefType with custom layout attribute

Problem 1: so far it looks like custom types are out of the question completely: operations like bufferization.to_tensor, bufferization.to_memref (and probably others) would complain that our types are not “mlir::TensorType” / “mlir::BaseMemRefType”.

Problem 2: Then, there is no way to convert encoding to layout and layout to encoding, nor there’s a way to customize the general MLIR-native tensor → memref / memref → tensor conversions.

With some upstream patching (see this discussion) - making base tensor / memref types into interfaces - we actually managed to partially solve problem 1. Now we’re trying to deal with the problem 2 in various shapes and forms: generally, we’d want to be able to completely customize the way tensor → memref conversion happens (as well as memref → tensor because apparently it is also necessary). The issue with this is that some conversion functionality is implemented as free-standing functions.

The major questions from us would be:

  • Do you envision that tensor → memref conversion route should carry on any user-specified / standard transformations? For instance:
    • preserve layout during “memref → tensor → memref” roundtrip (according to this, no?)
    • preserve encoding during “tensor → memref → tensor” roundtrip
  • Do you have some ideas as to how to introduce the customization points for conversions?
    • One idea that I have is via MLIRContext (which seems to be the only available object that could be fetched in free-standing functions) - having a FuncRef inside of it for getTensorFromMemref / getMemrefFromTensor (with default implementations as they are now) should work in theory
    • Another idea that we’re currently running with internally is to introduce a special “conversion” interface to tensor and memref with getMemrefFromTensor and getTensorFromMemref interface methods respectively + make it possible to replace basic interface implementation with a custom one (seems like it is possible in a dirty way already via Type::attachInterface<>() mechanism)

Needless to say, we plan to push our patches to upstream but this would only really work out if there’s at least some consensus w.r.t. custom tensors / memrefs support and related functionality.

Thanks in advance for help and suggestions.

CC @matthias-springer

The MLIR bufferization was not designed with custom tensor/memref types in mind, but I think it could be generalized. I haven’t thought about this in detail yet, but here are some thoughts.

You can think of bufferization.to_memref and bufferization.to_tensor as special versions of unrealized_conversion_cast. If an entire program is bufferized, these ops are transitory and will fold away. This design allows users to dump the IR throughout the bufferization process or to partially bufferize a program.

There shouldn’t be too many places in the bufferization infrastructure where we expect a to_tensor or to_memref op. They mostly appear in BufferizableOpInterface::bufferize implementations. It should be possible add buildToTensorFn and buildToMemrefFn lambdas to BufferizationOptions, which would let users customize which ops are generated by BufferizableOpInterface implementations. (These implementations, e.g., the scf.for implementation, would have to call the lambda in the BufferizationOptions instead of directly building to_tensor/to_memref ops.) You could then provide a lambda that builds unrealized_conversion_cast, which would work with arbitrary types.

This approach is somewhat risky because you get less verification / safety checks. E.g., bufferization.to_tensor is allowed in input programs only if the restrict attribute is set. We don’t have such attributes on unrealized_conversion_cast.

The function that you linked (getTensorTypeFromMemRefType) is mainly used for the verification of to_tensor/to_memref ops. The relevant function in the bufferization infrastructure is bufferization::getBufferType. This function either queries BufferizableOpInterface::getBufferType or calls getMemRefType, which could be customized to call into a lambda defined in BufferizationOptions. (We have BufferizationOptions::functionArgTypeConverterFn and BufferizationOptions::unknownTypeConverterFn at the moment, this could be generalized.) This entire infrastructure is currently hard-coded to BaseMemRefType/MemRefType. It should be possible to replace everything with Type, but it would be nice to be able to assert that a certain type is a buffer type (to guard against programming mistakes).

As far as I know, we don’t usually have to compute tensor types from buffer types, apart from when a to_tensor op is built.

The bufferization infrastructure is currently also hard-coded to MLIR tensor types. E.g., we skip all ops that do not have at least one tensor operand or result. Also in the bufferization analysis (OneShotAnalysis.cpp), certain data structures are maintained only for values of type TensorType. All of this could probably be changed to Type, but we would still need a way to query whether a type is a tensor for bufferization purposes, i.e., whether a given type is one that the bufferization should bufferize.

The test case that you linked (Bufferization/Transforms/finalizing-bufferize.mlir) is a leftover the old dialect conversion-based bufferization framework. We are reusing some of their infrastructure, e.g., the to_tensor/to_memref ops. Don’t focus too much on this test file. The specific test cast that you referred to is essentially a cast from memref<?xf32, strided<[1], offset: ?>> to memref<?xf32> and -finalizing-bufferize is a pass that folds away to_tensor/to_memref ops. In this example, that is only possible by allocating a new buffer. to_memref does preserve layout maps if both input and output buffer have the same layout map.

We ignore tensor encodings at the moment because they are not used in upstream MLIR outside of the sparse compiler. We could extend the various getBufferType functions / interface methods to take it into account.

Do you have some ideas as to how to introduce the customization points for conversions?

These should go into BufferizationOptions, which should be available in most places during bufferization. (If not, we can pass it to functions when it’s missing.)

Aha, I see. So instead of bending the ToTensorOp / ToMemrefOp you propose to just add “own version” of these and then use these custom ops instead. This might work, but so far we actually liked the ToTensorOp / ToMemrefOp semantics since it allows out-of-the-box folding of these (it seems they mostly appear during bufferization so many times there are to_memref(to_tensor(x)) that just disappear after the pass).

I also agree with the design choice of using mlir::TensorType and mlir::BaseMemRefType. Being able to distinguish two classes of mlir::Types feels much less bug-prone. In fact, I’d rather have these to be interface types, then we can have a proper tensor / memref types in place while also not limiting them to MLIR-native tensors / memrefs (at least not at this level). This is actually one of the culprits: thus far, mlir::TensorType just mandates that it is, in fact, a mlir::{Ranked, Unranked}TensorType - same is true for mlir::BaseMemRefType. Relaxing this makes 50% of the work done it seems.

By the way, we scope the usage of the custom types to our own custom dialect (operations). Then these get bufferized using BufferizableOpInterface::bufferize provided by us into our own buffer-domain dialect (so the transition is CustomTensorDomainDialect -> CustomMemrefDomainDialect). And then all MLIR-native stuff is supposed to just use MLIR-provided one-shot bufferization facilities. An exception so far is FuncOp because we noticed problems with bufferizing arguments / outputs of functions (but maybe this is nowadays covered by BufferizationOptions::functionArgTypeConverterFn that you mention).

I meant things like %x = bufferization.to_memref %y : tensor<> -> memref<>. In this case, there’s currently no way to propagate layout information from tensor to memref. Right now we do this ourselves by having a custom getBufferType function that bufferizes all types including mlir::RankedTensorType -> mlir::MemRefType (and this is where we do custom encoding → layout transformation). Apparently, it doesn’t work in all cases.

The major roadblocks so far seem to be:

  • No sane way to make a custom tensor a mlir::TensorType (+ same for memrefs)
  • Hard-coded logic for MLIR-native types - which is likely fine in most places, but the lack of tensor -> memref conversion customization infrastructure bites us hard

In the end, we’d like to reuse as much of the MLIR functionality as possible. Re-writing everything just means a lot of maintenance burden and questionable long-term benefits.

The places I know of that don’t follow this is Op verifiers. They simply don’t accept anything except maybe MLIRContext. Then there is type inference which is also similar. These two make it hard to squeeze custom types into MLIR bufferization-dialect operations (albeit it could be by design). But this is a rather challenging topic to discuss right now, I need to collect proper evidence or have a reproducer. Otherwise, I’ll be just too detached from what really happens and how.

We could rename to_memref to to_buffer. But then we would still need a type interface for buffer / tensor types, as you mentioned. Sounds like an interesting idea. But would probably best be discussed in an RFC.

MemRefType has a layout map. But you’re right, tensor types can have an encoding, in which you can store arbitrary information. This may not be representable in a memref type (which has no “encoding”).

In the end, I think it is really a restriction of the existing types and not to_memref/to_tensor. These ops only verify that the element type and shape matches. Everything else (including layout maps on memrefs) can be arbitrary.

This makes sense, but esp. things like turning tensor/buffer types into type interfaces would be a pretty big change and require clear justification to convince the community. (And comparison with alternatives, etc.)

I think that’s by design. Ops verification cannot be customized. (I think it will also not be necessary in your case.)

Yup. In our case, we usually pass down some information from tensor’s encoding to memref’s layout (e.g. tensor layout such as NCHW or NHWC is utilized in both tensor world and memref world in our case and we propagate this information throughout the bufferization). So having some control over the conversion (hence the name of the thread) is something we’d want to have ultimately.

You’re correct about the problem being generally in the way tensor/memref base types are coded in MLIR. Actually, “these ops only verify that the element type and shape matches” - is a very interesting idea! Perhaps, one alternative to having a complex, user-configurable tensor → memref mapping is to change the way TableGen performs the checks for bufferization ops. Currently, it does roughly the following:

// to_tensor:
auto tensorType = getResult(0).getType();
auto memrefType = getOperand(0).getType();
auto tensorFromMemrefType = mlir::getTensorFromMemRef(memrefType); // remains "as is"
if (tensorType != tensorFromMemrefType) // changes
{ /* fail */ }

Instead of doing the tensorType != tensorFromMemrefType, we could check for e.g. tensorType.getShape() != tensorFromMemrefType.getShape() || tensorType.getElementType() != tensorFromMemrefType.getElementType(). This should actually cover what bufferization needs and have sufficient room for squeezing our custom types in (since what fails is tensorType.getEncoding() == tensorFromMemrefType.getEncoding()).

Regarding changing base types to type interfaces: this actually looks like a fairly minor thing currently. In the current implementation, base tensor type does effectively the following:

Type TensorType::getElementType() const {
  return llvm::TypeSwitch<TensorType, Type>(*this)
      .Case<RankedTensorType, UnrankedTensorType>(
          [](auto type) { return type.getElementType(); });
}

And this repeats for all other methods as well. So, effectively, it IS a type interface already. But because it isn’t in practice, there’s no way to actually add a new tensor type without modifying the MLIR’s builtins. (Honestly, my gut feeling tells me that this was done this way a very long time ago, perhaps before interfaces were introduced - seems to be the case for ShapedType which is now a type interface itself).