Repository navigation
Description
HLO can only represent tensors, meaning that values that should not be tensors are still wrapped in them and operated on just as if they were real dense data. This is most easily visible with loops and conditionals, where the loop iterator initialization, increment, and condition are all in tensors. This results in host readbacks and a bunch of other extraneous work when really these should just be modeled as simple primitive values (i32/index, etc).
For example, this input loop:
func @main() -> tensor<i32> attributes {iree.module.export} {
%cst = constant dense<1> : tensor<i32>
%cst_0 = constant dense<3> : tensor<i32>
%0 = iree.do_not_optimize(%cst) : tensor<i32>
%1 = iree.do_not_optimize(%cst_0) : tensor<i32>
%2 = "xla_hlo.while"(%0) ( {
^bb0(%arg0: tensor<i32>): // no predecessors
%3 = "xla_hlo.compare"(%arg0, %1) {comparison_direction = "LT"} : (tensor<i32>, tensor<i32>) -> tensor<i1>
"xla_hlo.return"(%3) : (tensor<i1>) -> ()
}, {
^bb0(%arg0: tensor<i32>): // no predecessors
%3 = xla_hlo.add %arg0, %arg0 : tensor<i32>
"xla_hlo.return"(%3) : (tensor<i32>) -> ()
}) : (tensor<i32>) -> tensor<i32>
return %2 : tensor<i32>
}is turned into the following CFG:
func @main() -> tensor<i32> attributes {iree.module.export} {
%cst = constant dense<1> : tensor<i32>
%cst_0 = constant dense<3> : tensor<i32>
%0 = iree.do_not_optimize(%cst) : tensor<i32>
%1 = iree.do_not_optimize(%cst_0) : tensor<i32>
br ^bb1(%0 : tensor<i32>)
^bb1(%2: tensor<i32>): // 2 preds: ^bb0, ^bb2
%3 = "xla_hlo.compare"(%2, %1) {comparison_direction = "LT"} : (tensor<i32>, tensor<i32>) -> tensor<i1>
%4 = extract_element %3[] : tensor<i1>
cond_br %4, ^bb2(%2 : tensor<i32>), ^bb3(%2 : tensor<i32>)
^bb2(%5: tensor<i32>): // pred: ^bb1
%6 = xla_hlo.add %5, %5 : tensor<i32>
br ^bb1(%6 : tensor<i32>)
^bb3(%7: tensor<i32>): // pred: ^bb1
return %7 : tensor<i32>
}Which then after lowering through flow has the condition dispatched to the device and the condition read back (via flow.tensor.load):
func @main() -> tensor<i32> attributes {iree.module.export} {
%cst = constant dense<1> : tensor<i32>
%cst_0 = constant dense<3> : tensor<i32>
%cst_1 = constant dense<1> : vector<3xi32>
%0 = iree.do_not_optimize(%cst) : tensor<i32>
%1 = iree.do_not_optimize(%cst_0) : tensor<i32>
br ^bb1(%0 : tensor<i32>)
^bb1(%2: tensor<i32>): // 2 preds: ^bb0, ^bb2
%3 = flow.ex.stream.fragment(%arg0 = %cst_1 : vector<3xi32>, %arg1 = %2 : tensor<i32>, %arg2 = %1 : tensor<i32>) -> tensor<i1> {
%8 = flow.dispatch @main_ex_dispatch_0::@main_ex_dispatch_0[%arg0 : vector<3xi32>](%arg1, %arg2) : (tensor<i32>, tensor<i32>) -> tensor<i1>
flow.return %8 : tensor<i1>
}
%4 = flow.tensor.load %3 : tensor<i1>
cond_br %4, ^bb2(%2 : tensor<i32>), ^bb3(%2 : tensor<i32>)
^bb2(%5: tensor<i32>): // pred: ^bb1
%6 = flow.ex.stream.fragment(%arg0 = %cst_1 : vector<3xi32>, %arg1 = %5 : tensor<i32>) -> tensor<i32> {
%8 = flow.dispatch @main_ex_dispatch_1::@main_ex_dispatch_1[%arg0 : vector<3xi32>](%arg1) : (tensor<i32>) -> tensor<i32>
flow.return %8 : tensor<i32>
}
br ^bb1(%6 : tensor<i32>)
^bb3(%7: tensor<i32>): // pred: ^bb1
return %7 : tensor<i32>
}If instead we found these host-only values (even if only scalar tensors to start) we could run the whole loop in the host VM and avoid the readback.
This is also visible in inputs that have dynamic update slices (translated through to flow.tensor.update), where the current loop iterator value is needed to know where to update the tensor (mapping back to which timestep is being processed, etc). These updates need to be recorded into the command buffer on the host which means that we perform a readback to effectively compute an offset and then throw it back to the device.
Other enhancements around indirect dispatch and dynamic flow.tensor.update (#1160) will make some of these cases not so bad when device->host data dependencies really do exist, however if we can remove all of the trivial cases without relying on that we'll have much more readable IR and much lower overhead at runtime.
Metadata
Metadata
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
benvanik commentedon Nov 22, 2020
This is still critically important and will become moreso next quarter. Tagging @silvasean as we've talked about it before in case he knows someone who may be willing to work on this (it'd be useful upstream in MLIR for IREE as well as anything routing through MHLO/TOSA/etc).
[-]Tensor-to-primitive HLO conversion[/-][+]Tensor-to-primitive/detensoring HLO conversion[/+]ergawy commentedon Dec 21, 2020
Hi @benvanik ,
I have been contributing to MLIR (specially the
spvdialect, with a lot of help from @antiagainst 😄) for a while (https://reviews.llvm.org/people/revisions/14762/). I would love to contribute to IREE as well.Is this issue still something that needs to be picked up?
I had a quick look and got the gist of what needs to be done. If it's still fine work on that, I will inspect it in more detail.
benvanik commentedon Dec 21, 2020
Yeah! It'd be useful to sketch out the full pipeline of
MHLO|TOSA->linalg-on-tensors-> IREE'sflowand see where this may be able to be upstreamed (if at all). Brainstorming a bit:Since we are migrating to linalg-on-tensors as our input dialect over the next few months it's possible that something could be done there which would let such an analysis/pass happen after MHLO/TOSA/etc such that it can be shared across all of them. This may also help solve a lot of the corner cases and avoid needing to specialize things to any other input dialect - such as handling broadcasting behavior. Instead of having specific patterns for converting mhlo.add to std.addi, for example, we let the existing patterns for linalg do that and instead perform the simplification on linalg.generic/indexed_generic ops (and those may literally be the only two ops we deal with, which is why it would be so nice!).
The major work that then happens could be a parameterized analysis pass that goes through IR and determines which values chains should be detensored. The pass would be looking for which values flowed between other tensor ops vs. those that were extracted out into scalars, and maybe in the future have parameters like "limit detensoring to ops producing a tensor of <= 4/16/32 elements" (so we could pull out vector<4xi32> for example). If a value is determined to be detensored the conversion should be fairly straightforward then and may just be the addition of a helper method in linalg that takes the body of a linalg.generic/indexed_generic and clones it out.
For example:
The analysis would look at the extract_element's source
%tensor, note that it was a candidate for detensoring (single element, etc), and then clone out the op:The nice thing here is that if that was applied greedily then if whatever was producing
%Aor%Bcould be detensored then the next step would do that too all the way up the chain. If the transformation was done cloning then if there were other users of the value that couldn't be detensored the op would still remain for those uses (if%tensorwas used by other actual tensor operations/etc).This may end up just being some canonicalizations on linalg ops looking for this kind of thing - then the greedy application is taken care of by MLIR's canonicalization pass. For example, a pattern on linalg.generic that checked to see if any user of the result was extract_element and if so cloned the body out/updated usage may be the entirety of it! If more control was desired then
mlir::applyOpPatternsAndFoldwould let this happen outside of canonicalization (useful for example if we wanted to use analysis results).An alternative to all of this is to do something specific to HLO - which has the advantage of being something that would work today in IREE but is more difficult to do as each of the dozens of MHLO ops would need to be supported. You'd still be performing the analysis but then instead of touching linalg ops you'd be mapping things like
mhlo.add : tensor<i32>->std.addi : i32directly. It could also be hacked together under integrations/tensorflow/compiler/ before seeing how it may be upstreamed into tensorflow's repo.This may even be useful as an experiment before doing something like the above linalg approach as it'll help identify where the transformation is useful and act as a verification for whether the linalg-based one is performing well. Iterating in the simpler scope here on what the analysis pass looks like before then working to upstream and apply it to linalg may help to get the design in a good state for broader review on MLIR's discourse.
Writing additional MHLO->std patterns in addition to the ones already being written for converting to linalg-on-tensors feels like a lot of work and code to maintain, though, so even if it takes a little time for IREE's linalg-on-tensor support to come online it could still help others looking to use linalg-on-tensors today and then be extremely reusable for all MLIR users in the future (even if they are not using IREE).
Happy to chat more about this on discord or here!
ergawy commentedon Dec 23, 2020
Thanks a lot for the detailed response. This all sounds really exciting and I am eager to contribute.
I am a newbie so please excuse any possible misunderstanding/not-really-getting-it.
From your description, it seems that the more immediate course of action would be to do detensoring exclusively to HLO (the 2nd alternative above). This might not be as general and useful as doing so for linalg on tensors but would serve as a good experiment that can later on guide a similar effort but within linalg on tensors.
From my side, I don't mind working on something specific to HLO that might be reverted later and replaced with a more general/useful implementation. In any case, it will be a wonderful learning experience and I can help with "porting" those optimizations to linalg on tensors later on.
Based on that, my naive understanding is that the first concrete steps would be the following:
stdops that work with scalar types.canBeDetensored. And for ops with this field set to true, an<op>::getDetensoringPattern.Does that make sense to you?
benvanik commentedon Dec 23, 2020
Makes sense! Starting small with simple cases likely to be encountered from normal tensorflow code will help prevent the need for an exhaustive MHLO pattern mapping. For example, using the simple test linked in the description means you only need to support compare and add ops. If you take the tblgen approach like you mention then the initial work may mostly be setting up the new td files and build system goo :)
A larger, more realistic example would be https://github.com/google/iree/blob/473186214a19447932b02bc78d9cf47a332b2dc3/iree%2Ftest%2Fe2e%2Fmodels%2Funidirectional_lstm.mlir#L100 - probably a good goal for initial proof of concept as the source
tf.whileends up as thatmhlo.whileand supporting that case will enable almost anything usingtf.whileto work.A larger representative example will also help flush out any issues that may be discovered: I suspect there are cases where we'll need to carry along information through the CFG and getting some concrete examples will help figure out next steps. A particular gotcha will be cases where there's no unidirectional flow (so not host -> device or device -> host but instead device -> host -> device or some other kind of sandwich). Crossing that bridge when we come to it is fine and anything you were able to get together would be really valuable in informing that follow-on work!
72 remaining items
allieculp commentedon Aug 17, 2022
@GMNGeoffrey @ScottTodd Stale P1 item here, please take a look when you get a chance and update or deprioritize!
ScottTodd commentedon Aug 17, 2022
I think @rsuderman was going to look at getting this work over the finish line.
[MLIR][LinAlg] Start detensoring implementation.
[MLIR][LinAlg] Detensorize interal function control flow.
[MLIR][Linalg] Extend detensoring control flow model.
[MLIR][LinAlg] Start detensoring implementation.
[MLIR][LinAlg] Detensorize interal function control flow.
[MLIR][Linalg] Extend detensoring control flow model.