Repository navigation
[MLIR] Add constant folder for xla_hlo.broadcast_in_dim op - #40745
bondhugula wants to merge 1 commit into
Conversation
|
Ping @sherhut |
sherhut
left a comment
There was a problem hiding this comment.
Thanks for adding this and apologies for not seeing this earlier. The ping helped :)
|
The test failures don't look like mine or I just can't tell. Any insights here? |
|
It is failing in the XLA-MLIR path, and it does not fail without this patch: I don't know if this patch is triggering the issue by lack of luck but it does not seem entirely unrelated to me. |
|
All test cases failures are like the ones above: the trace is opaque and isn't a FileCheck based one. Do these indicate that FileCheck based tests are missing somewhere? Any pointers on where to dig will help. Is it possible that a {0-d const + broadcast} being converted to {n-d const} is triggering failures elsewhere? For IR size and downstream opts, this would appear to only make things easier. @sherhut |
|
@bondhugula Can you please resolve conflicts? Thanks! |
9196527 to
7deaeb1
Compare
Resolved conflicts - but this revision is triggering failures at other places. It's not clear if the issue is with this optimization. |
|
I'll import it internally and see if I can get more helpful errors with ASAN/MSAN. |
|
Backtrace with assertion enabled: |
|
The offending case is |
Perhaps we are interpreting terminology in different ways. By materializing, you mean storing into a buffer, right? A 0-d const + broadcast will use a storage that is one element more than an n-d constant FWIW (+ 1 op less in the IR and no indirection for the const operand). How do you avoid materializing in the former case. With a simple no-opt scenario, the latter is better. My assumption earlier was that an n-d const op is always better than a 0-d const + broadcast - either if you don't optimize or if you optimize (in which case it's easier to optimize/rewrite with n-d const + another op).
Separate question: which existing test pass could this fit into? We could of course add it as an optional pattern. Or do we just add this pattern in a dedicate pass registered from the same file as say hlo_legalize_to_lhlo? But I'd like to have clarity on why this folding isn't always the best thing to do.
This is the part I'm still trying to understand. In both cases, you would be materializing the constant. If you aren't materializing in the |
Only if you run the IR op by op... A compiler (like XLA could generate code with accessors into the "small" buffer). (Otherwise I agree that the "splat" case seems like safe to fold as a subset of the general constant folding) |
But it won't do the same when the operand is a constant tensor? This goes back to my earlier point - is something simpler missing for operands that are constants that exists for operands that are the result of a broadcast? |
The question is how much of HLO a lowering needs to support. From the perspective of just HLO, this is a valid canonicalization, as it replaces an alternative IR encoding of a splat constant with just that. The problem, as I see it, is that the lowering is incomplete and does not support this part of HLO. It would also fail if I just wrote the corresponding input. What are HLO constants lowered to when lowering HLO to linalg? As there is not linalg constant, I assume to standard. Then linalg should learn how to deal with splat constants. Or we disallow splat constants in HLO (if that can be done?). @nicolasvasilache what is your take on this? |
I don't quite understand the question here? |
|
Hey Uday, sorry for the confusion! Let me try to explain in details so hopefully this helps to resolve your questions. :)
Let's consider the case where we have a large graph and we want to carve out different components of it to run on different accelerators. (I think this is the general direction we are heading for with the compiler-based holistic approach.) Then each component/subgraph/dispatch-region/whatever will be isolated out from the main graph and all the tensors crossing the boundary need to be materialized and to be backed by some buffers. If we have the original scalar constant and broadcast, I can cut the boundary just before the broadcast so the broadcast is put inside the dispatch-region. Then I just need to pass a single constant in. This is typically very cheap and we have quite some flexibility as to whether to sink the constant itself to the dispatch region or use some special hardware memory type or just use normal buffer or whatever. And we can even analyze different such isolated dispatch regions and may find that actually they are all the same and just starting with a different constant. Then we can deduplicate the dispatch regions and only keep one. Now if we constant fold the broadcast, all the flexibility are lost, unless one does analysis essentially to redo the constant folding and re-discover the original scalar. And constant folding has cascading effect: after this one kicked in, we might see lots of additional constant folding happening and that can create more and more large constants. These large constants, if to be backed by buffers, all need to cross the boundary. Because we need to match ABI (as you cannot just send in one scalar to GPU for example and claiming its size is 512x128x...; the ABI is mismatching there), it can potentially mean large amount of data sending across some bus. So this is why we think it's better to avoid aggressively constant folding broadcasts and it's better to leave the choice to each use cases. |
|
Related to this, Ben has a very nice summary of performance issues we've hit inside IREE due to broadcasts: iree-org/iree#1583. I think the general idea behind is to defer broadcast as much as possible to avoid the unnecessary cost. |
Adding a dedicated test pass sounds reasonable to me and we can at the same time expose a |
|
@antiagainst : it isn't clear to me how your argument applies to splat though (which the current patch is limited to right?) |
You can lower a HLO constant (and std.const) which are splat constants to a linalg.generic with no inputs and the yield returning the constant value. Thats what we did in IREE for a while, but there was some concern about a 0-input linalg.generic op (I am actually not sure why and it worked in practice). For now we rely on fusion of linalg.generic/linalg.indexed_generic with std.const here to handle splat constants. We didnt need to do anything more, but adding a lowering from HLO const/std.const for splat constants to linalg.generic would be great (and would also fix the issue at hand).
|
I already have a lowering for this (LHLO -> |
|
|
||
| // CHECK-LABEL: func @broadcast_in_dim_constant_fold_0d | ||
| func @broadcast_in_dim_constant_fold_0d() -> tensor<1x64x224x224xf32> { | ||
| %cst = mhlo.constant dense<0.000000e+00> : tensor<f32> |
There was a problem hiding this comment.
This one particularly is more than a splat: it is a splat into a 0d scalar tensor type (the splat is somewhat incidental?). By having this as a folding rule, I lose the ability to represent a scalar-constant broadcast in HLO (since it will always be folded to fully materialized). Having that structure (not unconditionally materializing scalar broadcasts) is fairly important from an analysis on tensors perspective as having this knowledge enables various size-sensitive optimizations.
I agree that this is a valid folding from a correctness perspective, but it limits what we can express in mhlo (since this is the current idiom for representing a scalar broadcast and is used quite extensively).
I'm struggling with an "HLO principles" reason why this folding should be disallowed and the following allowed, though. This may actually be pointing at a missing op (i.e. mhlo.broadcast_scalar) if this case is important to represent at this level.
There was a problem hiding this comment.
This one particularly is more than a splat: it is a splat into a 0d scalar tensor type (the splat is somewhat incidental?). By having this as a folding rule, I lose the ability to represent a scalar-constant broadcast in
@stellaraccident: this one is a splat! :-) (a trivial splat). Please see lines 550-551 in hlo_ops.cc where I'm explicitly checking for splat attributes. For the rest that you mention below, please see my post below on why having one form is important.
HLO (since it will always be folded to fully materialized). Having that structure (not unconditionally materializing scalar broadcasts) is fairly important from an analysis on tensors perspective as having this knowledge enables various size-sensitive optimizations.
I agree that this is a valid folding from a correctness perspective, but it limits what we can express in mhlo (since this is the current idiom for representing a scalar broadcast and is used quite extensively).
I'm struggling with an "HLO principles" reason why this folding should be disallowed and the following allowed, though. This may actually be pointing at a missing op (i.e. mhlo.broadcast_scalar) if this case is important to represent at this level.
There was a problem hiding this comment.
Thanks for bearing with me (and side note: I'm sorry to have triggered another round of review on such a simple PR -- I know how frustrating that can be).
Now re-reading this, I realize I was missing the syntactic distinction of the splat being preserved in this transformation (while more verbose, I did appreciate that we used to actually spell out "splat"). I had gotten used to keying off of the 0d-ness of the tensor as the distinguishing characteristic while treating the originating SplatElementsAttr as incidental. So you are right: this preserves the same information when considering the attribute type of the constant and as long as the splat is handled correctly all the way down, then this can be fine (modulo bugs).
As one of the things that we've found challenging in the past, the IREE team is a bit wired to see unnecessary constant expansions as problematic, and the bias there certainly kept me from seeing this alternative simplification.
Yes, this patch is only for splats. @antiagainst, thanks very much for all the detail. Clearly, there are several lower level issues and interactions, but I think I have the same question as @joker-eph. The whole point of canonicalization is to avoid having the downstream look at and deal with multiple things. If you allow both (Separately from the above, why are constants (even the single scalar constant) being passed across boundaries? One already knows they are constants and so they can be pulled in (replicated potentially) - I know one can still choose to not do that, but that's the price to pay for not having done that. ) |
In IREE we go from HLO to Linalg on tensors. linalg.fill doesnt operate on tensors. IREE doesnt use LHLO. Lowering from HLO/Std consts to linalg.generic on tensors will allow the fusion on tensors pass to fuse everything seemlessly. |
|
I just sync'd with several people offline, and we all made the same mis-read of this PR:
Given that a number of people made this mistake, we should probably lobby separately to consider some clearer syntax here that better reveals the structure. Also, since SplatElementsAttr extends DenseElementsAttr, we're somewhat concerned that a lack of care on related folders are easy to write the wrong way (and this is made worse by the spelling subtlety). However, none of that should related to this PR, which is sound. Really sorry for the tangent. |
|
We're pushing a local fix to the original bug and then will trigger submission of this PR. Stand by. |
Thanks @stellaraccident - no worries; it's good to be aware of the interactions and the impact this has downstream. I should perhaps update the commit title to reflect 'splat' but the summary already has it. I can add a few more lines to the summary. |
Imported from GitHub PR #40745 Fold broadcast_in_dim op if the operand is the result of a tensor splat. Copybara import of the project: -- 26c9f63 by Uday Bondhugula <[email protected]>: [MLIR] Add constant folder for xla_hlo.broadcast_in_dim op Fold broadcast_in_dim op if the operand is the result of a tensor splat. COPYBARA_INTEGRATE_REVIEW=#40745 from polymage-labs:broadcast_in_dim_fold 26c9f63 PiperOrigin-RevId: 320365164 Change-Id: Ia63a54ce57ede7de79c27baf9bf0b891ed1de3e1
FUTURE_COPYBARA_INTEGRATE_REVIEW=tensorflow/tensorflow#40745 from polymage-labs:broadcast_in_dim_fold 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 PiperOrigin-RevId: 320335415
FUTURE_COPYBARA_INTEGRATE_REVIEW=tensorflow/tensorflow#40745 from polymage-labs:broadcast_in_dim_fold 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 PiperOrigin-RevId: 320335415
FUTURE_COPYBARA_INTEGRATE_REVIEW=tensorflow/tensorflow#40745 from polymage-labs:broadcast_in_dim_fold 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 PiperOrigin-RevId: 320335415
FUTURE_COPYBARA_INTEGRATE_REVIEW=tensorflow/tensorflow#40745 from polymage-labs:broadcast_in_dim_fold 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 PiperOrigin-RevId: 320335415
Imported from GitHub PR tensorflow/tensorflow#40745 Fold broadcast_in_dim op if the operand is the result of a tensor splat. Copybara import of the project: -- 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 by Uday Bondhugula <[email protected]>: [MLIR] Add constant folder for xla_hlo.broadcast_in_dim op Fold broadcast_in_dim op if the operand is the result of a tensor splat. COPYBARA_INTEGRATE_REVIEW=tensorflow/tensorflow#40745 from polymage-labs:broadcast_in_dim_fold 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 PiperOrigin-RevId: 320365164
|
This landed in #40745. |
Imported from GitHub PR tensorflow/tensorflow#40745 Fold broadcast_in_dim op if the operand is the result of a tensor splat. Copybara import of the project: -- 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 by Uday Bondhugula <[email protected]>: [MLIR] Add constant folder for xla_hlo.broadcast_in_dim op Fold broadcast_in_dim op if the operand is the result of a tensor splat. COPYBARA_INTEGRATE_REVIEW=tensorflow/tensorflow#40745 from polymage-labs:broadcast_in_dim_fold 26c9f631448b8d6ffd20ece39ea8d4132b5550c7 PiperOrigin-RevId: 320365164
* 'master' of github.com:tensorflow/tensorflow: (302 commits) PR tensorflow#40745: [MLIR] Add constant folder for xla_hlo.broadcast_in_dim op compat: Update forward compatibility horizon to 2020-07-09 Update GraphDef version to 457. Remove the redundant lite/minimal_logging.h in NNAPI delegate tests. Make a V2 default strategy Add size test to flex delegate selective build Add type check for cases where a layer instance is called on invalid object types (non-tensor-like). Make a V2 default strategy Internal change Add support for tf.TPUPartitionedCall in shape inference pass. Move keras model related combinations and tests to keras/distribute. [tf.data] Change the structure of how `GetNext` function recording time in dataset.cc to improve data pipeline performance. Remove defined(__ANDROID__) in nnapi_delegate_provider as it's been handled by the NNAPI delegate implementation. Cleanup build rule names in compiler/mlir/hlo to remove the redundant/obsolete xla_ prefix Adding a comment to TFSavedModelAPI, and renaming to drop the Impl suffix. Add element tracing for parallel_interleave. Expose GetPerfEnvFromXPlane via header [XLA:CPU] [NFC] Extract a helper function for defining a function type and calling it Update README.md of TFLite benchmark tool for Flex delegate [TF/XLA] Simplify functions used for populating XlaTensors ...
Fold broadcast_in_dim op if the operand is the result of a tensor splat.