xref: /llvm-project/mlir/docs/Tutorials/transform/Ch4.md (revision 73fa6685c43ef61f5f5babb14f734097af6dc702)
1# Chapter 4: Matching Payload with Transform Operations
2
3**Check the continuously-tested version of MLIR files under
4[mlir/test/Examples/transform/Ch4](https://github.com/llvm/llvm-project/tree/main/mlir/test/Examples/transform/Ch4).**
5
6Up until now, we were applying transform dialect scripts under the assumption
7that specific payload operations are identified by the caller when the transform
8dialect interpreter is invoked. This may be seen as contrary to the idea of
9driving transformations from a dialect since the transformation targets must be
10identified through mechanisms external to the transform dialect interpreter, for
11example, when invoking the interpreter programmatically in C++ or through pass
12arguments as seen in previous chapters. It also adds practical overhead due to
13increased interaction with the interpreter in C++, and cognitive overhead of
14manipulating two interfaces at once. To remedy this, Transform dialect proposes
15a subset of operations for _matching_ payload operations that need to be
16transformed.
17
18_Match_ operations are simply transform operations with some additional
19guarantees. In particular, they are not expected to modify the payload IR and
20are expected to fail if their operands (typically payload operation handles) are
21not associated with payload IR objects having desired properties, such as
22operation names or kinds of arguments. Using simple combinator operations, it
23becomes possible to set up a higher-level match and rewrite infrastructure
24directly within the transform dialect.
25
26
27## Simple match
28
29Let us reconsider the “fully connected layer” example from [Chapter
301](Ch1.md/#chaining-transformations-with-handles), reproduced below for
31convenience.
32
33
34```mlir
35// Original function to optimize.
36func.func @fc_relu(%lhs: tensor<512x512xf32>, %rhs: tensor<512x512xf32>,
37                   %bias: tensor<512x512xf32>, %output: tensor<512x512xf32>)
38                   -> tensor<512x512xf32> {
39  // Matrix-matrix multiplication.
40  %matmul = linalg.matmul
41            ins(%lhs, %rhs: tensor<512x512xf32>, tensor<512x512xf32>)
42            outs(%output: tensor<512x512xf32>) -> tensor<512x512xf32>
43
44  // Elementwise addition.
45  %biased = linalg.elemwise_binary { fun = #linalg.binary_fn<add> }
46    ins(%matmul, %bias : tensor<512x512xf32>, tensor<512x512xf32>)
47    outs(%output : tensor<512x512xf32>) -> tensor<512x512xf32>
48
49  // Elementwise max with 0 (ReLU).
50  %c0f = arith.constant 0.0 : f32
51  %relued = linalg.elemwise_binary { fun = #linalg.binary_fn<max_signed> }
52    ins(%biased, %c0f : tensor<512x512xf32>, f32)
53    outs(%output : tensor<512x512xf32>) -> tensor<512x512xf32>
54  func.return %relued : tensor<512x512xf32>
55}
56
57```
58
59
60In Chapter 1, we were calling the test transform interpreter pass with
61additional arguments, `bind-first-extra-to-ops=linalg.matmul
62bind-second-extra-to-ops=linalg.elemwise_binary`, to provide initial
63associations for operation handles. Instead, we can use match operations to
64discover relevant operations in the payload IR. Match operations can be combined
65with “regular” transform operations using, e.g., the
66`transform.collect_matching` combinator operation that leverages the concept of
67named sequences to organize matchers.
68
69
70```mlir
71// The module containing named sequences must have an attribute allowing them
72// to enable verification.
73module @transforms attributes { transform.with_named_sequence } {
74  // Entry point. This takes as the only argument the root operation (typically
75  // pass root) given to the transform interpreter.
76  transform.named_sequence @__transform_main(
77      %root: !transform.any_op {transform.readonly}) {
78    // Collect operations that match the criteria specified in named sequence.
79    // If the named sequence fails with a silenceable failure, silences it (the
80    // message is forwarded to the debug stream). If the named sequence
81    // succeeds, appends its results to the results of this operation.
82    %elemwise = transform.collect_matching @match_elemwise in %root
83      : (!transform.any_op) -> !transform.any_op
84    %matmul = transform.collect_matching @match_matmul in %root
85      : (!transform.any_op) -> !transform.any_op
86    transform.include @print_elemwise failures(propagate)  (%elemwise)
87      : (!transform.any_op) -> ()
88    transform.include @print_matmul failures(propagate)  (%matmul)
89      : (!transform.any_op) -> ()
90
91    transform.yield
92  }
93
94  // This is a matcher sequence. It is given an operation to match and the
95  // match is considered successful unless any nested operation produces a
96  // failure. The values yielded by this operation will be forwarded to the
97  // rewriter sequence on success.
98  transform.named_sequence @match_elemwise(
99      %entry: !transform.any_op {transform.readonly}) -> !transform.any_op {
100    transform.match.operation_name %entry ["linalg.elemwise_binary"]
101      : !transform.any_op
102    transform.yield %entry : !transform.any_op
103  }
104  transform.named_sequence @match_matmul(
105      %entry: !transform.any_op {transform.readonly}) -> !transform.any_op {
106    transform.match.operation_name %entry ["linalg.matmul"] : !transform.any_op
107    transform.yield %entry : !transform.any_op
108  }
109
110  // This is a rewriter sequence.
111  transform.named_sequence @print_elemwise(
112      %elemwise_binary: !transform.any_op {transform.readonly}) {
113    transform.debug.emit_remark_at
114      %elemwise_binary, "elementwise binary" : !transform.any_op
115    transform.yield
116  }
117  transform.named_sequence @print_matmul(
118      %matmul: !transform.any_op {transform.readonly}) {
119    transform.debug.emit_remark_at %matmul, "matmul" : !transform.any_op
120    transform.yield
121  }
122}
123
124```
125
126
127This script can be executed using the non-test interpreter pass running on the
128root operation of the translation unit without additional flags: `mlir-opt
129--transform-interpreter`. It will emit corresponding remarks at
130`linalg.elemwise_binary` and `linalg.matmul` operations. In debug builds, the
131infrastructure provides a convenient method to understand the matching process
132by passing `-debug-only=transform-matcher` to `mlir-opt` or a derived tool. It
133will print the silenceable failure messages produced by the match operations
134into the debug stream, for example:
135
136
137```
138<...>
139[transform-matcher] matching %0 = linalg.matmul ins(%arg0, %arg1 : tensor<512x512xf32>, tensor<512x512xf32>) outs(%arg3 : tensor<512x512xf32>) -> tensor<512x512xf32> @0x5622eee08410
140[transform-matcher] matcher match_elemwise failed: wrong operation name
141<...>
142```
143
144
145This is now sufficient to run the rest of the transform script from Chapter 1,
146substituting `%arg1` with `%matmul` and `%arg2` with `%elemwise`.
147
148
149## Matching Chains of Operations
150
151The matcher above remains naive as it matches _all_ operations of the certain
152kind under the payload root. These operations may or may not be related, and
153may, for example, belong to different functions. Even if they are in a single
154function, if there are multiple groups of such operations, we wouldn’t be able
155to differentiate them with this approach. In reality, we want to match a
156specific group of operations where a `matmul` operation produces a result that
157is used by an elementwise operation, which in turn feeds another elementwise
158operation in a similar way.
159
160This can be achieved using the following matcher sequence.
161
162
163```mlir
164// This is also a matcher sequence. It is similarly given an operation to
165// match and nested operations must succeed in order for a match to be deemed
166// successful. It starts matching from the last operation in the use-def chain
167// and goes back because each operand (use) has exactly one definition.
168transform.named_sequence @match_matmul_elemwise(
169    %last: !transform.any_op {transform.readonly})
170    -> (!transform.any_op, !transform.any_op, !transform.any_op) {
171  // The last operation must be an elementwise binary.
172  transform.match.operation_name %last ["linalg.elemwise_binary"]
173    : !transform.any_op
174  // Its first operand must be defined by another operation, to which we
175  // will get a handle here. We are guaranteed that the first operand exists
176  // because we know the operation is binary, but even in absence of such a
177  // guarantee, this operation would have produced a silenceable failure when
178  // `%last` does not have enough operands.
179  %middle = transform.get_producer_of_operand %last[0]
180    : (!transform.any_op) -> !transform.any_op
181  // The defining operation must itself be an elementwise binary.
182  transform.match.operation_name %middle ["linalg.elemwise_binary"]
183    : !transform.any_op
184  // And the first operand of that operation must be defined by yet another
185  // operation.
186  %matmul = transform.get_producer_of_operand %middle[0]
187    : (!transform.any_op) -> !transform.any_op
188  // And that operation is a matmul.
189  transform.match.operation_name %matmul ["linalg.matmul"] : !transform.any_op
190  // We will yield the handles to the matmul and the two elementwise
191  // operations separately.
192  transform.yield %matmul, %middle, %last
193    : !transform.any_op, !transform.any_op, !transform.any_op
194}
195```
196
197This matcher is applicable in presence of other `elemwise` and `matmul`
198operations and will return the triple of _related_ operations rather than
199operations in the order in which they are found. It can be exercised similarly
200to the previous incarnation, as follows.
201
202```mlir
203// Alternative entry point.
204transform.named_sequence @__transform_main(
205    %root: !transform.any_op {transform.readonly}) {
206  // Collect groups of operations that match the criteria specified in the
207  // named sequence.
208  %matmul, %el1, %el2 = transform.collect_matching @match_matmul_elemwise in %root
209    : (!transform.any_op) -> (!transform.any_op, !transform.any_op, !transform.any_op)
210  %elemwise = transform.merge_handles %el1, %el2 : !transform.any_op
211
212  transform.include @print_elemwise failures(propagate)  (%elemwise)
213    : (!transform.any_op) -> ()
214  transform.include @print_matmul failures(propagate)  (%matmul)
215    : (!transform.any_op) -> ()
216
217  transform.yield
218}
219```
220
221
222## Defining Match Operations
223
224The matcher of a chain of operations is correct in presence of other operations,
225but is still insufficiently robust for many cases of interest. In particular,
226using `transform.get_producer_of_operand %last[0]` requires that the _first_
227operand of elementwise operations is produced by another operation. The same
228transformation strategy may however apply regardless of the operand position:
229many binary operations are associative. Let us use this opportunity to introduce
230a new match operation. Specifically, we would like this operation to succeed if
231_any_ of the operands satisfies certain conditions that can be expressed as
232other match operations. We also want it to return some of the state and the
233position of the matched operand in the operand list.
234
235Match operations are defined similarly to other transform operations, with the
236only difference of additionally implementing the `MatchOpInterface`. Note that
237this interface has _no additional methods_ (though it may add some eventually)
238and is only used as a verification contract that the operation is intended for
239matching and will not attempt to transform the payload. The minimal definition
240of our operation is as follows.
241
242
243```tablegen
244// Define the new operation. By convention, prefix its name with `match`
245// followed by the name of the dialect extension.
246def HasOperandSatisfyingOp : TransformDialectOp<"match.my.has_operand_satisfying",
247    [DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
248     DeclareOpInterfaceMethods<TransformOpInterface>,
249     // Indicate that the operation implements MatchOpInterface in addition to
250     // the TransformOpInterface. This interface is only used as a tag at this
251     // point and has no methods that are mandatory to implement.
252     MatchOpInterface,
253     SingleBlockImplicitTerminator<"::mlir::transform::YieldOp">]> {
254  let summary = "Succeed if any of the operands matches all nested criteria";
255  let arguments = (ins TransformHandleTypeInterface:$op);
256  let results = (outs TransformParamTypeInterface:$position,
257                      Variadic<Transform_AnyHandleOrParamType>:$results);
258
259  // Match operations can be arbitrarily complex, e.g., containing regions.
260  let regions = (region SizedRegion<1>:$body);
261  let hasVerifier = 1;
262  let assemblyFormat = [{
263    $op `:` functional-type($op, results) attr-dict-with-keyword $body
264  }];
265}
266```
267
268
269It takes as argument the handle associated with the payload operations whose
270operands it will match, has an associated single-block region containing the
271match criteria, and returns the position of the matched operand as well as any
272other transform value yielded from the body on the successful match.
273
274The matching logic is implemented in the `apply` method of the
275`TransformOpInterface` and is easily composable with other transform operations.
276All facilities for managing the interpreter state and recursively entering the
277blocks are available in the same way as they are for “regular” transform
278operations. Match operations are expected to return a silenceable failure to
279indicate failure to match, and to immediately propagate definite failures. If
280they have nested operations, they are expected to handle and, in most cases,
281silence the silenceable failures produced when applying those operations. For
282our operation, the matching is essentially a loop iterating over all operands of
283the (single) payload operation and applying nested transform ops until they all
284succeed for one of the operands.
285
286
287```cpp
288// Matcher ops implement `apply` similarly to other transform ops. They are not
289// expected to modify payload, but use the tri-state result to signal failure or
290// success to match, as well as potential irrecoverable errors.
291mlir::DiagnosedSilenceableFailure
292mlir::transform::HasOperandSatisfyingOp::apply(
293    mlir::transform::TransformRewriter &rewriter,
294    mlir::transform::TransformResults &results,
295    mlir::transform::TransformState &state) {
296  // For simplicity, only handle a single payload op. Actual implementations
297  // can use `SingleOpMatcher` trait to simplify implementation and document
298  // this expectation.
299  auto payloadOps = state.getPayloadOps(getOp());
300  if (!llvm::hasSingleElement(payloadOps))
301    return emitSilenceableError() << "expected single payload";
302
303  // Iterate over all operands of the payload op to see if they can be matched
304  // using the body of this op.
305  Operation *payload = *payloadOps.begin();
306  for (OpOperand &operand : payload->getOpOperands()) {
307    // Create a scope for transform values defined in the body. This corresponds
308    // to the syntactic scope of the region attached to this op. Any values
309    // associated with payloads from now on will be automatically dissociated
310    // when this object is destroyed, i.e. at the end of the iteration.
311    // Associate the block argument handle with the operand.
312    auto matchScope = state.make_region_scope(getBody());
313    if (failed(state.mapBlockArgument(getBody().getArgument(0),
314                                      {operand.get()}))) {
315      return DiagnosedSilenceableFailure::definiteFailure();
316    }
317
318    // Iterate over all nested matchers with the current mapping and see if they
319    // succeed.
320    bool matchSucceeded = true;
321    for (Operation &matcher : getBody().front().without_terminator()) {
322      // Matcher ops are applied similarly to any other transform op.
323      DiagnosedSilenceableFailure diag =
324          state.applyTransform(cast<TransformOpInterface>(matcher));
325
326      // Definite failures are immediately propagated as they are irrecoverable.
327      if (diag.isDefiniteFailure())
328        return diag;
329
330      // On success, keep checking the remaining conditions.
331      if (diag.succeeded())
332        continue;
333
334      // Report failure-to-match for debugging purposes and stop matching this
335      // operand.
336      assert(diag.isSilenceableFailure());
337      DEBUG_MATCHER(DBGS_MATCHER()
338                    << "failed to match operand #" << operand.getOperandNumber()
339                    << ": " << diag.getMessage());
340      (void)diag.silence();
341      matchSucceeded = false;
342      break;
343    }
344    // If failed to match this operand, try other operands.
345    if (!matchSucceeded)
346      continue;
347
348    // If we reached this point, the matching succeeded for the current operand.
349    // Remap the values associated with terminator operands to be associated
350    // with op results, and also map the parameter result to the operand's
351    // position. Note that it is safe to do here despite the end of the scope
352    // as `results` are integrated into `state` by the interpreter after `apply`
353    // returns rather than immediately.
354    SmallVector<SmallVector<MappedValue>> yieldedMappings;
355    transform::detail::prepareValueMappings(
356        yieldedMappings, getBody().front().getTerminator()->getOperands(),
357        state);
358    results.setParams(getPosition().cast<OpResult>(),
359                      {rewriter.getI32IntegerAttr(operand.getOperandNumber())});
360    for (auto &&[result, mapping] : llvm::zip(getResults(), yieldedMappings))
361      results.setMappedValues(result, mapping);
362    return DiagnosedSilenceableFailure::success();
363  }
364
365  // If we reached this point, none of the operands succeeded the match.
366  return emitSilenceableError()
367         << "none of the operands satisfied the conditions";
368}
369
370```
371
372
373By convention, operations implementing `MatchOpInterface` must not modify
374payload IR and must therefore specify that they only read operand handles and
375payload as their effects.
376
377
378```cpp
379void transform::CollectMatchingOp::getEffects(
380    SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
381  onlyReadsHandle(getRoot(), effects);
382  producesHandle(getResults(), effects);
383  onlyReadsPayload(effects);
384}
385```
386
387
388This operation can now be included in a transform dialect extension, loaded and
389used in our matcher. Specifically, we will use it to indicate that either of the
390operands of the “max” elementwise operation in our example can be produced by
391the previous elementwise operation. The previous operation will still require
392the matmul to produce the first operand for simplicity. The updated matcher
393sequence looks as follows.
394
395
396```mlir
397transform.named_sequence @match_matmul_elemwise(
398    %last: !transform.any_op {transform.readonly})
399    -> (!transform.any_op, !transform.any_op, !transform.any_op,
400        !transform.param<i32>) {
401  // The last operation must be an elementwise binary.
402  transform.match.operation_name %last ["linalg.elemwise_binary"]
403    : !transform.any_op
404
405  // One of its operands must be defined by another operation, to which we
406  // will get a handle here. This is achieved thanks to a newly defined
407  // operation that tries to match operands one by one using the match
408  // operations nested in its region.
409  %pos, %middle = transform.match.my.has_operand_satisfying %last
410      : (!transform.any_op) -> (!transform.param<i32>, !transform.any_op) {
411  ^bb0(%operand: !transform.any_value):
412    // The operand must be defined by an operation.
413    %def = transform.get_defining_op %operand
414      : (!transform.any_value) -> !transform.any_op
415    // The defining operation must itself be an elementwise binary.
416    transform.match.operation_name %def ["linalg.elemwise_binary"]
417      : !transform.any_op
418    transform.yield %def : !transform.any_op
419  }
420
421  // And the first operand of that operation must be defined by yet another
422  // operation.
423  %matmul = transform.get_producer_of_operand %middle[0]
424    : (!transform.any_op) -> !transform.any_op
425  // And that operation is a matmul.
426  transform.match.operation_name %matmul ["linalg.matmul"] : !transform.any_op
427  // We will yield the handles to the matmul and the two elementwise
428  // operations separately.
429  transform.yield %matmul, %middle, %last, %pos
430    : !transform.any_op, !transform.any_op, !transform.any_op,
431      !transform.param<i32>
432}
433```
434
435
436This achieves the desired effect and matches both `max(add(matmul(...), bias),
4370)` and `max(0, add(matmul(...), bias))` in the same values. The `%pos` value is
438a transform dialect _parameter_, which is used to store lists of entities known
439to be constant throughout the transform application. Most often, parameters are
440numeric values, but they can generally be any MLIR attributes.
441
442In order to demonstrate that groups of operations are matched independently of
443each other, let us use the `transform.foreach_match` operation that allows one
444to implement a simple high-level pattern rewriting approach within the transform
445dialect (for advanced or lower-level pattern rewriting, consider PDL(L) or C++
446rewriting APIs). It maps a matcher named sequence to an action named sequence,
447and the latter gets invoked whenever the former succeeds.
448
449
450```mlir
451// Traverses the payload IR associated with the operand handle, invoking
452// @match_matmul_elemwise on each of the operations. If the named sequence
453// succeeds, i.e., if none of the nested match (transform) operations
454// produced a silenceable failure, invokes @print_matmul_elemwise and
455// forwards the values yielded as arguments of the new invocation. If the
456// named sequence fails with a silenceable failure, silences it (the message
457// is forwarded to the debug stream). Definite failures are propagated
458// immediately and unconditionally, as usual.
459transform.foreach_match in %root
460  @match_matmul_elemwise -> @print_matmul_elemwise
461  : (!transform.any_op) -> !transform.any_op
462```
463
464
465The `@print_matmul_elemwise` named sequence, available in `multiple.mlir`, will
466use the parameter with the position of the operand to differentiate the two
467groups.
468
469
470## Matchers for Inferred Features
471
472The matcher sequences described above, although useful to drive transformations
473from within the transform dialect interpreter, are rather basic since they
474mostly rely on operation names and use-def chains. Alternative implementations
475using APIs or various declarative rewrite rules are barely less expressive and
476sometimes more concise. The real power of transform dialect matcher ops lies in
477the possibility to define matchers of _inferred properties_ of payloads, i.e.,
478properties that are not directly accessible as an attribute of an operation or
479any straightforward relation between IR components.
480
481The utility of such matchers can be easily demonstrated by slightly modifying
482our original example. If matrix multiplication is expressed as a special case of
483tensor contraction using `linalg.generic` instead of `linalg.matmul`, the
484operation name-based matcher no longer applies. Yet such a representation is
485very common and can appear both in the original input and during the course of
486transformation, e.g., where a higher-dimensional contraction is decomposed into
487loops around a matrix multiplication.
488
489In order to be a (potentially transposed) matrix multiplication, the
490`linalg.generic` operation must have the following features:
491
492
493
494*   Total rank of 3.
495*   Two inputs accessed as projected permutation of iteration dimensions.
496*   One output accessed as projected permutation of iteration dimensions.
497*   Iteration dimensions can be subdivided into LHS parallel, RHS parallel and reduction dimensions.
498*   The body block consists of a multiplication and an addition.
499
500Most of these features can be derived from the properties of the operation,
501e.g., the total rank corresponds to the number of entries in the `iterators`
502attribute, but almost none of them are immediately accessible in the IR or in
503any declarative form, which is usually limited to checking the presence or the
504exact match of an attribute or a type.  The transform dialect allows these
505features to be implemented in the `apply` method of a matcher op and reused
506across multiple matching cases. For structured linear algebra payload
507operations, many such match operations are readily available in the `structured`
508extension. They are sufficient to implement a matrix multiplication matcher
509using the features listed above almost verbatim.
510
511
512```mlir
513transform.named_sequence @match_generic_matmul(
514    %candidate: !transform.any_op {transform.readonly}) -> !transform.any_op {
515  // Match a structured linear algebra operation.
516  transform.match.structured %candidate : !transform.any_op {
517  ^bb0(%c: !transform.any_op):
518    // With a rank equal to 3.
519    %rank = transform.match.structured.rank %c
520      : (!transform.any_op) -> !transform.param<i64>
521    %c3 = transform.param.constant 3 : i64 -> !transform.param<i64>
522    transform.match.param.cmpi eq %rank, %c3 : !transform.param<i64>
523
524    // With 2 inputs.
525    %n_ins = transform.match.structured.num_inputs %c
526      : (!transform.any_op) -> !transform.param<i64>
527    %c2 = transform.param.constant 2 : i64 -> !transform.param<i64>
528    transform.match.param.cmpi eq %n_ins, %c2 : !transform.param<i64>
529
530    // With 1 output (note that structured ops in destination passing style
531    // has as many inits as outputs).
532    %n_inits = transform.match.structured.num_inits %c
533      : (!transform.any_op) -> !transform.param<i64>
534    %c1 = transform.param.constant 1 : i64 -> !transform.param<i64>
535    transform.match.param.cmpi eq %n_inits, %c1 : !transform.param<i64>
536
537    // All inputs and inits are accessed with a projected permutation.
538    transform.match.structured.input %c[all] {projected_permutation}
539      : !transform.any_op
540    transform.match.structured.init %c[0] {projected_permutation}
541      : !transform.any_op
542
543    // The body is a mulf/addf contraction with appropriate dimensions.
544    transform.match.structured.body %c
545      { contraction = ["arith.mulf", "arith.addf"] } : !transform.any_op
546    %batch, %lhs, %rhs, %reduction =
547    transform.match.structured.classify_contraction_dims %c
548      : (!transform.any_op)
549      -> (!transform.param<i64>, !transform.param<i64>, !transform.param<i64>,
550          !transform.param<i64>)
551
552
553    // There is one of lhs, rhs and reduction dimensions and zero batch
554    // dimensions.
555    %n_batch = transform.num_associations %batch
556      : (!transform.param<i64>) -> !transform.param<i64>
557    %n_lhs = transform.num_associations %lhs
558      : (!transform.param<i64>) -> !transform.param<i64>
559    %n_rhs = transform.num_associations %rhs
560      : (!transform.param<i64>) -> !transform.param<i64>
561    %n_reduction = transform.num_associations %reduction
562      : (!transform.param<i64>) -> !transform.param<i64>
563    %c0 = transform.param.constant 0 : i64 -> !transform.param<i64>
564    transform.match.param.cmpi eq %n_batch, %c0 : !transform.param<i64>
565    transform.match.param.cmpi eq %n_lhs, %c1 : !transform.param<i64>
566    transform.match.param.cmpi eq %n_rhs, %c1 : !transform.param<i64>
567    transform.match.param.cmpi eq %n_reduction, %c1 : !transform.param<i64>
568  }
569  transform.yield %candidate : !transform.any_op
570}
571```
572
573
574While this example leverages the contraction-specific matchers that have a
575rather non-trivial C++ implementation, the transform dialect is sufficiently
576flexible to implement this reasoning directly if desired. One could, for
577example, obtain the access map of each input as a parameter and extract the
578accessed dimensions as other parameters that can be compared with each other to
579ensure the subscripts are `m,k` for LHS, `k,n` for RHS and `m,n` for the
580init/result given the `m,n,k` notation for loops.
581
582## Appendix: Autogenerated Documentation
583
584[include "Tutorials/transform/MyExtensionCh4.md"]
585
586