This is an archive of the discontinued LLVM Phabricator instance.

[mlir][tensor] ExtractSliceFromReshape: handle collapsing of unit dim edge cases
ClosedPublic

Authored by christopherbate on Oct 11 2022, 4:22 PM.

Details

Summary

Prior to this change, the "ExtractSliceFromReshape" pattern would transform

%collapsed = tensor.collapse_shape %input [[0, 1], [2]]
                : tensor<1x11x100xf32> into tensor<11x100xf32>
%slice = tensor.extract_slice %collapsed [%offt, 0] [%size, 100] [1, 1]
                : tensor<11x100xf32> to tensor<?x100xf32>

into a loop that iterated over the range %size - %offt, that pieces
together multiple sub-slices of %input along the first dimension. This
is correct but obviously inefficient. The technical condition is that
collapsing at-most-one non-unit dimension of %src will not result in a
subsequent slice along the corresponding dimension of %collapsed
mapping across discontinuities in the index space of %src. Thus, the
definition of a "linearized dimension" (from the perspective of
tensor.collapse_shape) is updated to reflect this condition.

The transform will now generate

%slice = tensor.extract_slice %input [0, %offt, 0][1, %size, 100] [1, 1]
            : tensor<1x11x100xf32> to tensor<1x?x100xf32>
%result = tensor.collapse_shape [[0, 1], [2]]
            : tensor<1x?x100xf32> to tensor<?x100xf32>

which can be further canonicalized.

Additional tests are added to check this family of edge cases.

Diff Detail

Event Timeline

christopherbate requested review of this revision.Oct 11 2022, 4:22 PM

This feels like a special case that will push us further into more collapse/expand special cases.
Have you considered adding/using expand/collapse of 1s -> rank-reducing extract/insert rewrites?
These generally compose nicer all the way down to vector load/store.

I implemented the suggestion today, and it works well, but will put up the cleaned up version early next week.

Address comment, use strategy of rank-reducing extract slice op on the source of the collapse shape.

ThomasRaoux accepted this revision.Oct 18 2022, 8:48 AM

LGTM

mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp
442–443

nit: would this be more clear?

newReassociationIndices.push_back(reassociation);
reassociation.clear();
This revision is now accepted and ready to land.Oct 18 2022, 8:48 AM
mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp
442–443

Yeah I can change that. I picked up this style from elsewhere in the code base, but I agree it's not super intuitive

Address comments