[mlir][vector] Switch from vector.multi_reduction to vector.contract
Hi folks,
MLIR’s Vector dialect includes two operations with overlapping use cases:
Historically, the lowering path from linalg.matmul to vector.contract went through vector.multi_reduction. In #147296, @adam-smnk added a direct path from linalg.matmul to vector.contract.
As a next step, I would like to clarify the boundary between these operations: when should Linalg vectorization produce vector.contract, and when is vector.multi_reduction needed? My goal is to identify more cases that can lower directly to vector.contract and address any gaps in the existing lowering.
Could you share concrete examples where vector.contract cannot be used in place of vector.multi_reduction? Small IR examples, together with a brief explanation of the limitation, would be particularly helpful.
Thank you, Andrzej
PRs
- https://github.com/llvm/llvm-project/pull/237709
- https://github.com/llvm/llvm-project/pull/240796
@llvm/issue-subscribers-mlir
Author: Andrzej Warzyński (banach-space)
MLIR’s Vector dialect includes two operations with overlapping use cases:
Historically, the lowering path from linalg.matmul to vector.contract went through vector.multi_reduction. In #147296, @adam-smnk added a direct path from linalg.matmul to vector.contract.
As a next step, I would like to clarify the boundary between these operations: when should Linalg vectorization produce vector.contract, and when is vector.multi_reduction needed? My goal is to identify more cases that can lower directly to vector.contract and address any gaps in the existing lowering.
Could you share concrete examples where vector.contract cannot be used in place of vector.multi_reduction? Small IR examples, together with a brief explanation of the limitation, would be particularly helpful.
Thank you, Andrzej
@llvm/issue-subscribers-mlir-vectorops
Author: Andrzej Warzyński (banach-space)
MLIR’s Vector dialect includes two operations with overlapping use cases:
Historically, the lowering path from linalg.matmul to vector.contract went through vector.multi_reduction. In #147296, @adam-smnk added a direct path from linalg.matmul to vector.contract.
As a next step, I would like to clarify the boundary between these operations: when should Linalg vectorization produce vector.contract, and when is vector.multi_reduction needed? My goal is to identify more cases that can lower directly to vector.contract and address any gaps in the existing lowering.
Could you share concrete examples where vector.contract cannot be used in place of vector.multi_reduction? Small IR examples, together with a brief explanation of the limitation, would be particularly helpful.
Thank you, Andrzej
Here is one case. It comes from the fused-attention payload in llvm/lighthouse (lighthouse/ingress/mlir_gen/gpu_attention_payload.py). Softmax needs the row max of the scores, and later the row sum of exp(s - max). Each is a plain reduction with one input (simplified to 2-D here):
%row_max = linalg.generic {
indexing_maps = [affine_map<(d0, d1) -> (d0, d1)>, affine_map<(d0, d1) -> (d0)>],
iterator_types = ["parallel", "reduction"]}
ins(%scores : tensor<128x64xf32>) outs(%init : tensor<128xf32>) {
^bb0(%s: f32, %acc: f32):
%m = arith.maximumf %s, %acc : f32
linalg.yield %m : f32
} -> tensor<128xf32>
Linalg vectorization turns it into:
%r = vector.multi_reduction <maximumf>, %s, %acc [1] : vector<128x64xf32> to vector<128xf32>
There is no multiplication, so this is not a contraction. Only the named contraction ops implement ContractionOpInterface, and the vectorizer takes the vectorizeAsLinalgContraction path only for them (and only with createNamedContraction). To write it as a vector.contract we would need a second operand of all ones and a multiply by it, which a later pass would then have to remove.
A transform dialect test:
Thanks for looking into this, @banach-space and @mshahneo!
I ran into these aspects while reviewing #233546, because it wasn't entirely clear to me either, for the reasons you raised here, Andrzej. Below is what I could gather from a quick look. I may be missing cases, so please correct me where I am wrong.
Premise: see this table for the terminology used here.
vector.contract is reduce<kind>(lhs * rhs) over at least one contracting pair, see the verifier.
multi_reduction reduces an already computed vector, see the op def.
- Reduction of a single operand:
%r = vector.multi_reduction <add>, %src, %acc [1] : vector<4x8xf32> to vector<4xf32>
multi_reduction has a single source, so there is nothing to pair. The contract below has two operands, but no reduction dim shared by lhs and rhs, and it is rejected:
// lhs: (i, k) -> (i, k), rhs: (i, k) -> (i), acc: (i, k) -> (i)
vector.contract ... %a, %b, %acc : vector<4x8xf32>, vector<4xf32> into vector<4xf32>
// error: 'vector.contract' op expected at least one contracting dimension pair
As far as I can tell, it could be emulated with a splat-of-ones rhs, but that adds a dummy operand.
- Elementwise op other than
mulbefore the reduction:
%s = arith.addf %a, %b : vector<4x16x8xf32>
%r = vector.multi_reduction <minimumf>, %s, %acc [2] : vector<4x16x8xf32> to vector<4x16xf32>
vector.contract always computes reduce<kind>(lhs * rhs). Here the computation is reduce<minimumf>(a + b), so I don't see how the elementwise addf could be expressed.
Regarding "My goal is to identify more cases that can lower directly to vector.contract and address any gaps in the existing lowering", here is what I noticed. I only tried a handful of Linalg ops with create_named_contraction.
- The direct path is opt-in. It is only used with
create_named_contraction(see the dispatch), so by default evenlinalg.matmulends up inmulti_reduction. linalg.dotwith the flag seems to generate invalid IR. Fixed with #234638 in place ;)linalg.genericops are never considered, as documented here. A generic that is justmulf+addfstill givesmulti_reduction, and so do the variants I tried withextfin the body ormaximumfas combiner. Maybelinalg::isaContractionOpInterfacecould be used to detect them, but I haven't checked.- Dims that only appear in the output are rejected by this check, same as in the contract verifier (see here). The comment there says broadcasts should be decomposed before vectorization.
I did not look into masked or scalable contracts, so I can't say whether the points above also hold there.
Just a suggestion that we can follow (I can take care of it):
- Let
linalg.genericops that are contractions take the direct path. - Only after that, think about making it the default.
Well, the way I see, vector.contract is an einsum with two arguments, while both vector.reduction and vector.multi_reduction are just the reducing parts for 1D and ND. To match them to vector.contract we'd have to accept single operand and make the necessary changes, which is doable, but motivation is still murky.
First, I don't think we need two reduction operations. To me, vector.reduction could very well be ND and we don't need the other one. This looks like left-over from previous migrations... So there's already motivation to reduce the number of operations already here.
Second, contraction has two operations: the elementwise and the reduction. For matmul, that's multiply and sum, but it could be anything for non-matmul contractions, including simple reductions. If we allow single operand in vector.contract, then the elementwise operation disappears, and we're left with the reduction operation only, which is "what we want" (if we want it).
The key thing here, regardless of the option we pick, is that we should always vectorize / canonicalize to the most appropriate / simplest form.
Options:
- Leave all as is.
- Leave
contractas is (two operands), mergereductionandmulti_reduction(single operand). - Change contract to allow single operand, merge reductions into it.
Merging into contract will need not only allow single operand, but also expose and extend both elementwise and contraction operations, possibly make mul and add the defaults to avoid churn. We can add the functionality first, then deprecated the others. We can also create wrappers called reduction and multi_reduction like we did with linalg.matmul_transpose_a|b.
This will definitely need an RFC...
Thank you @rengolin, this is a great POV. Overall, strong +1 for this!
Now, this matches what I ran into, and the two gaps I listed above are what your option 3 should cover, IIUC. I.e., a single operand (no contracting pair) and an elementwise op other than mul (e.g., min-plus, reduce<minimumf>(a + b)).
Regarding merging reduction into multi_reduction, the multi_reduction docs already say: "a scalar when k == n", so the 1-D case is covered. AFAICS, the optional accumulator and fastmath are gaps - but easily fixable at a glance.
For option 3, which I really like, with a single operand the elementwise step disappears, as you say. With two operands, the RFC would need to decide whether using something like the same set as CombiningKind or an arbitrary region. For mul + add, I agree that they should remain as defaults.
I agree this needs an RFC. I'm happy to take care of it, but we can definitely wait for @banach-space, since maybe he prefers to do it himself.
Hi folks, thank you for your comments, and apologies for the delay in replying!
When I posted this, I was a bit too fixated on why matrix multiplication (either as linalg.matmul or linalg.generic) was being vectorized into vector.multi_reduction instead of vector.contract. I missed the bigger picture!
Leave contract as is (two operands), merge reduction and multi_reduction (single operand).
Strong +1.
IMO, we should work towards Ops with clearly orthogonal functionality. Ops that are "Swiss Army knives" tend to be confusing, tricky to implement and easy to get wrong in edge cases.
Also, I currently see no good reason to keep vector.reduction and vector.multi_reduction separate.
The key thing here, regardless of the option we pick, is that we should always vectorize / canonicalize to the most appropriate / simplest form.
+1.
For option 3, which I really like, with a single operand the elementwise step disappears, as you say.
I know that my initial post effectively suggested Option 3 from Renato's post, but, as I said above, I missed the wider context. With that in mind, I am much more in favour of Option 2: keeping vector.contract as a two-input Op and merging the two reduction Ops.
I propose the following action items:
- [x] Disallow "pure reduction" dims in
vector.contract- that's a task forvector.multi_reduction(see my Discourse PSA). - [ ] Make the Linalg vectorizer default to
vector.contractfor matrix multiplications - that's a much more natural and intuitive target. - [ ] Merge
vector.reductionandvector.multi_reduction, unless prototyping reveals good reasons to keep them separate.
I'd prefer to keep these changes lightweight and use PSAs where possible. For the reduction Op merge, let's see what prototyping reveals before deciding whether it needs an RFC 😅
I agree this needs an RFC. I'm happy to take care of it, but we can definitely wait for @banach-space, since maybe he prefers to do it himself.
Thanks for volunteering, we can co-ordinate offline!
Thanks again,
-Andrzej
Thanks for this overview. I believe the plan proposed here is well-defined and would resolve the inconsistency we are currently encountering.
Thanks for offering to help—we can coordinate separately!
Perfect. Just to be clear: I’m more than happy to contribute to the implementation of this solution, Andrzej :D
A quick side note: with option 3, I was thinking of behavior similar to that of linalg.generic, with the addition of named ops. But we can hold off on that discussion for now, as it's not a priority.
Just to keep track.
Disallow "pure reduction" dims in vector.contract: https://github.com/llvm/llvm-project/pull/237709
// Leave contract as is (two operands), merge reduction and multi_reduction (single operand).
Strong +1.
Thanks for the efforts cleaning up the vector op definition!
Based on the discussion in
- https://github.com/llvm/llvm-project/pull/236855,
I will also add the following as the proposed differentiating factor between vector.contract and vector.multi_reduction:
- "contraction" (e.g.
linalg.contract+vector.contract) means "mul" -> "add", while - "reduction" (e.g.
linalg.reduce+vector.reduction) is the more "flexible" sibling that allows any combining Op.
Quick scan of various frameworks mostly confirms that:
- PyTorch: torch.einsum
- TensorFlow: tf.einsum
- JAX: jax.lax.dot
- JAX: jax.lax.dot_general
- ONNX: Einsum
- Triton: tl.dot
- Triton: tl.reduce
-Andrzej
- "contraction" (e.g.
linalg.contract+vector.contract) means "mul" -> "add", while
caveat that for binary types, this is and and or instead of mul and add. But otherwise, I agree.
See https://github.com/llvm/llvm-project/pull/236855#issuecomment-6656658464
Reporting from #239589: "should linalg.reduce be unary?".
If unary means a single reduced operand, I agree that's the right boundary with contractions: a reduction folds one operand with any combiner, while anything that combines two operands elementwise before reducing (e.g. reduce<minimumf>(a + b)) is contraction territory.
However, linalg.reduce today is variadic: N inputs, N outs, and one combiner that sees all N accumulators (see variadic_reduce in roundtrip.mlir). This allows argmax in a single pass:
%max, %idx = linalg.reduce
ins(%values, %indices : tensor<128xf32>, tensor<128xi64>)
outs(%init_max, %init_idx : tensor<f32>, tensor<i64>)
dimensions = [0]
(%v: f32, %i: i64, %acc_v: f32, %acc_i: i64) {
%gt = arith.cmpf ogt, %v, %acc_v : f32
%new_v = arith.select %gt, %v, %acc_v : f32
%new_i = arith.select %gt, %i, %acc_i : i64
linalg.yield %new_v, %new_i : f32, i64
}
A unary reduce would need a second pass plus a tie-breaking rule. The same semantics can be expressed differently, but making linalg.reduce unary would be a breaking change to the op, so it is worth deciding explicitly.
CC: @adam-smnk
If unary means a single reduced operand, I agree that's the right boundary with contractions: a reduction folds one operand with any combiner, while anything that combines two operands elementwise before reducing (e.g.
reduce<minimumf>(a + b)) is contraction territory.
Right, but currently, contract is just reduce<add>(a * b). So there's currently no way to represent your example other than a generic. To be clear, I think this is perfectly fine. We don't have to have all variations (this adds complexity).
A unary reduce would need a second pass plus a tie-breaking rule. The same semantics can be expressed differently, but making
linalg.reduceunary would be a breaking change to the op, so it is worth deciding explicitly.
Another perfectly valid usage of the reduce operation, and one that we can expand the specialization I add in #239589. The decision to keep "unary for the sake of generalization" is an cost-benefit one: this is mostly used for pattern matching (for example, softmax) while the argmax example you give still needs one to descend into the operation region to see what the semantics is.
There isn't a huge benefit, from a pattern-matching PoV, to go from a generic with that code in the region to a reduce with the same code.
Thank you, Renato!
I agree that argmax should continue to be expressed solely using linalg.generic or other combinations of ops.
Just to be clear, I was just playing devil's advocate, because the fact that it breaks existing code is important from my POV.
I was just wondering why the number of ins should be the same as the number of outs, but since we agree that it is no more variadic, I'd say we can drop the topic. Right?
Finally, AFAIC, it's a +1 that reduce takes only one operand and works with any combining operator.
I will also add the following as the proposed differentiating factor between
vector.contractandvector.multi_reduction:
- "contraction" (e.g.
linalg.contract+vector.contract) means "mul" -> "add", while- "reduction" (e.g.
linalg.reduce+vector.reduction) is the more "flexible" sibling that allows any combining Op.Quick scan of various frameworks mostly confirms that:
- PyTorch: torch.einsum
- TensorFlow: tf.einsum
- JAX: jax.lax.dot
- JAX: jax.lax.dot_general
- ONNX: Einsum
- Triton: tl.dot
- Triton: tl.reduce
-Andrzej
I need to backtrack a bit on this item. While my analysis of the framework APIs "above" Linalg + Vector stands, I should've also looked at things "below" Vector.
Basically, mul + add (and + or for i1) seems to cover the framework contraction APIs we looked at. However, ISAs also support related operations, e.g. SME's FMOPS, which subtracts an outer product from the accumulator. See my comment on #239589.
IIUC, we are all on the same page. I just wanted to note in this ticket that I won't be restricting vector.contract to mul + add. However, I intend to make mul + add more visible as the default.
SME's FMOPS, which subtracts an outer product from the accumulator.
Perhaps also need to look into vector.outerproduct.
SME's FMOPS, which subtracts an outer product from the accumulator.
Perhaps also need to look into
vector.outerproduct.
Indeed, it was vector.outerproduct that brought me here, see this test (It lowers vector.contract to vector.outerproduct, preserving maxnumf as the combining Op): https://github.com/llvm/llvm-project/blob/9bf625d4a938166bd7d043212e98effa3360e346/mlir/test/Dialect/Vector/vector-contract-to-outerproduct-matvec-transforms.mlir?plain=1#L171-L187
In essence, vector.contract and vector.outerproduct are tightly coupled and need to move in lockstep when it comes to the supported combining Ops.