Repository navigation
Enable the linalg.mmt4d operation and add mmt4d microkernels for the riscv64 - #20263
Conversation
bjacob
left a comment
There was a problem hiding this comment.
Nice work! You have come very far along already and this feels very well integrated and the result of strong attention to detail already.
| if (hasFeature(config, "+v") && hasFeature(config, "+zvl256b")) { | ||
| return { | ||
| // Tile sizes tuned for VLEN=256 | ||
| TileMxNxK{7, 32, 1}, // Aim to use vfmacc, 100% register utilization. |
There was a problem hiding this comment.
There are two aspect about this {7, 32, 1} that would be interesting to discuss/justify here. I'm OK with just merging this as-is if it matters to you to stick with this shape, but I want to make sure that we are on the same page about the trade-offs here.
-
The first uncommon thing about this tile shape is how rectangular it is, with the aspect ratio 32/7 > 4. It means that the kernel has to load
32+7=41values from the LHS and RHS matrices, in order to perform32*7 = 224scalar multiply-adds. That yields an arithmetic intensity ratio (defined as the ratio of multiply-adds to loads) ofM*N/(M+N) = 224/41 ~= 5.46. Maximizing the arithmetic intensity ratio is not necessarily a goal, so it is fine if that is a conscious choice, but that is worth a comment. But it is generically the whole point of maxing out register space, like the comment mentions is being done here (it says100% register utilization). Arguably the arithmetic intensity ratio only matters up to the point where all your load instructions become free (thanks to dual-issuing with arithmetic instructions) and a ratio of 5x is maybe high enough on many CPUs. Just wanted to make sure that's intentional. By contrast, if you hadTileMxNxK{12, 16, 1}here, meaning M=12, N=16, that would give you a much higher arithmetic intensity ratio ofM*N/(M+N)=6.8x, while using fewer registers (28) and enjoying the convenience of avoiding the odd value 7, see next point. -
The other uncommon thing here is the odd value 7. It is not a requirement to stick to powers of two, so that is your choice entirely. But an odd value like 7 is always going to be a bit costlier in terms of the data layout transformations (the
packandunpackoperations). It means that these data layout transformations will need to use either masked load/stores if that is available on your target architecture, or have scalar load/stores for at least some of the values being copied. Like mentioned at the end of point 1., if you consider both points together, that might tip the scales towards a more square, more even tile shape.
Up to you, but some comments explaining the rationale will be appreciated.
There was a problem hiding this comment.
Thanks for the detailed feedback!
Actually, I tried out various tile sizes and got the best performance with {7, 32, 1}. We don't need any particular tile size. We are actually looking for the one that would result in the fastest kernel. So, I'll try out {12, 16, 1} as well and share performance numbers with you soon.
There was a problem hiding this comment.
@bjacob I implememted ukerenel with tile sizes {7,32,1} and {12,16,1} and benchmarked the following code for both tile sizes:
func.func @matmul_dynamic(%lhs: tensor<?x?xf32>, %rhs: tensor<?x?xf32>, %acc: tensor<?x?xf32>) -> tensor<?x?xf32> {
%result = linalg.matmul ins(%lhs, %rhs: tensor<?x?xf32>, tensor<?x?xf32>) outs(%acc: tensor<?x?xf32>) -> tensor<?x?xf32>
return %result: tensor<?x?xf32>
}
The following are the results (Single core results):
{7,32,1}
| Matrix Size | Time (ms) |
|---|---|
| 32x32 | 0.252 |
| 512x512 | 31 |
| 1024x1024 | 229 |
| 2048x2048 | 1661 |
| 4096x4096 | 12086 |
{12,16,1}
| Matrix Size | Time (ms) |
|---|---|
| 32x32 | 0.227 |
| 512x512 | 34.8 |
| 1024x1024 | 276 |
| 2048x2048 | 1894 |
| 4096x4096 | 13553 |
I used the following command to compile the code:
iree-compile --iree-llvmcpu-enable-ukernels="mmt4d" --mlir-print-ir-after-all --iree-hal-target-backends=llvm-cpu --iree-llvmcpu-target-triple=riscv64 --iree-llvmcpu-target-abi=lp64d --iree-llvmcpu-target-cpu-features="+m,+a,+f,+d,+zvl256b,+v" --riscv-v-fixed-length-vector-lmul-max=8 mlir/matmul.mlir -o vmfb/matmul_riscv64_kernel.vmfb > dump 2>&1
I used iree-benchmark-module to get these numbers:
iree-benchmark-module --device=local-task --module=matmul_riscv64_kernel.vmfb --function=matmul_dynamic --input=@lhs_32.npy --input=@rhs_32.npy --input="32x32xf32=0
Hardware: Board: MILK-V Jupiter, CPU: Spacemit(R) X60 1.6 GHZ, VLEN=256
These numbers show that {7, 32, 1} performs slightly better. Also, wouldn't {12,16,1} still need mask instructions for pack/unpack as 12 is still not a power of 2?
There was a problem hiding this comment.
Sounds good! Go with whichever tile size performs best. I'm glad though that it'll be backed up by strong experimental data.
i don't know your ISA, but 12 sounded like a nicer size than 7 to me, naively. What would matter is not being a power of 2, but being a multiple of the sizes that you have instructions for. It sounds like you ISA's preferred size is 8xi32, which does mean that 12 still is less than ideal, but I was expecting that you would still have a 4xi32 instruction to fall back on.
Maybe more relevant is the access patterns. I was unsure if there would be penalties for completely unaligned addresses like 7. Sounds like that's fine.
| return "mmt4d"; | ||
| } | ||
| if (isRISCV64(targetAttr)) { | ||
| return "mmt4d"; |
There was a problem hiding this comment.
Let's keep the defaults switch for a separate PR. Better iterate on the new ukernels in this PR, then later once that has settled change the defaults. In the interim, you can manually pass the ukernel flag/attribute.
| "${PROJECT_BINARY_DIR}/runtime/src/iree/schemas/cpu_data_headers_filegroup.stamp" | ||
| "internal_headers_filegroup.stamp" | ||
| SRCS | ||
| "fallback.c" |
There was a problem hiding this comment.
Yes, dropping this is part of how you make room for your optimized kernel code. (this comment is mostly a note to self - I hadn't looked at that code in a while).
| @@ -0,0 +1,72 @@ | |||
| # Copyright 2025 10xEngineers | |||
There was a problem hiding this comment.
Deferring to @ScottTodd , what is the copyright policy? I think but amn't certain that code here needs to be copyright "the IREE authors" like existing files, but 10xEngineers would get credited in other ways, including Git history (commit author identity) and maybe the AUTHORS file?
There was a problem hiding this comment.
yes, it must be # Copyright 2025 The IREE Authors in the files.
| IREE_UK_ASSERT(M0 >= 1 && M0 <= 7); | ||
| const float* IREE_UK_RESTRICT lhs_ptr = lhs_panel; | ||
| const float* IREE_UK_RESTRICT rhs_ptr = rhs_panel; | ||
| float* IREE_UK_RESTRICT out_ptr = out_tile; |
There was a problem hiding this comment.
We would need at least a basic (not necessarily fast) implementation to exist here before merging this PR, so that tests start passing and providing coverage.
There was a problem hiding this comment.
I'll push the complete ukernel implementation soon, once we finalize the tile size.
|
Hi @bjacob , |
@adeel10x , this PR looks good - yes, please just add a test which should be a simple matter of editing the Once it's ready, mark the PR ready for review. |
Yes, there is a QEMU RISC-V emulator CI runner. Being QEMU, there is a fair chance that it will support standard RVV extensions but I don't know if that will require a version upgrade or a config change. |
|
@adeel10x , when you feel that this is ready for review, please hit the 'Ready for review' button and hit the 'cycle' button next to reviewers in the reviewers list at the top too, so it shows in our review dashboards. |
Hi @bjacob, hope you're doing well. There's one thing still missing in the PR. The ukernel I wrote is specifically for a vector length (VLEN) of 256 bits, and the tile sizes are also tuned for that. It won’t work correctly if VLEN isn’t 256. So before running tests for this ukernel, we need to make sure the CPU's VLEN is 256 bits. We can use I’d add this to |
Hi @adeel10x , sorry that I hadn't seen your message earlier. Yes, the approach you suggest sounds good to me. Fixing a specific vector length is the right place to start and cpu.c is the place to implement the feature detection. And if the target is Linux and what you need is already exposed in the auxiliary vector then yes that is the preferred way of getting it. Feel free to allocate cpu-data field bits as you wish, such as allocating a bit to mean "VLEN == 256" or encoding the VLEN value itself in some way (if it is necessarily a power of 2 then you could encode its base-2 exponent). |
Hi @bjacob , I think a more graceful approach would be to make a single RISC-V ukernels work for all VLENs. How would this be done : If you look at the current kernel for This should be valid for all VLENs since the total number of registers would always be 32, just the number of bits per register is increasing. Using this formula, we can calculate tile sizes based on VLEN in This is what I had in mind for future PRs. RISC-V V extension supports 10 different VLENs and having a separate ukernel for each case won't be scalable. Please let me know what you think. I'll try to quickly test out this approach. |
|
Sounds great! If the only way in which the ukernel depends on the VLEN value is for a stride (that pointer increment amount in Key here, and that is probably why that wasn't obvious at the start of this discussion, is that as ukernels always get inlined into their callers, where parameters like the N0 tile size are always compile-time constants, we can pass values down to ukernels that look like runtime function parameters but that really are compile-time parameters as if we were writing C++ template parameters. Even if you needed different instructions to be generated for different values of these parameters, you could always have |
|
Hi @bjacob, |
| // If these extension are specified in target cpu feature, | ||
| // they can be used to determine VLEN. | ||
| size_t getRVVVlenFromCPUFeatures(DictionaryAttr config) { | ||
| // If +zvl* feature is not explicitly specified, |
There was a problem hiding this comment.
This function is assuming that the V feature is present. That should either be said in the comment, or guarded in the code (e.g. return 0 if V not present) - your choice.
| if (hasFeature(config, "+zvl65536b")) { | ||
| vlen = 65536; | ||
| } else if (hasFeature(config, "+zvl32768b")) { | ||
| vlen = 32768; | ||
| } else if (hasFeature(config, "+zvl16384b")) { |
There was a problem hiding this comment.
While theoretically possible, huge VLEN values raise the question: would we actually want to be using such a huge tile size, which would result in padding matrices to the next multiple of that huge value? I suppose that is only a theoretical concern for now so should not block this PR or generate much discussion. Only suggesting that you mention this in a comment.
|
|
||
| // Placeholder for now | ||
|
|
||
| #endif // foIREE_BUILTINS_UKERNEL_ARCH_RISCV_64_PACK_RISCV_64_INTERNAL_H_ No newline at end of file |
There was a problem hiding this comment.
Add newline at end of file.
| return (iree_uk_matmul_tile_sizes_t){.M = 7, .K = 1, .N = 16}; | ||
| } | ||
| #endif | ||
| return (iree_uk_matmul_tile_sizes_t){.M = 8, .K = 1, .N = 8}; |
There was a problem hiding this comment.
Add a comment clarifying that this final return is a generic fallback. People shouldn't try to make sense of those "8" as particularly meaningful values.
|
Looks good! Note, the DCO check requires all commits to be signed-off. Easiest to rebase-and-squash to just 1 commit (we would squash anyway on merging). For now, I launched the CI jobs as is. |
Ok. Once I debug the failing CI checks, I'll cherry-pick relevant commits and sign-off them as well. |
|
'Test RISC-V 64' check failed because clang-18 require 'v' feature to be specified using I have fixed this issue by enabling the v feature while compiling all files that include |
Yes, please do that. The problem with enabling the +v feature in common is that we are calling common code before the runtime feature check. |
…r riscv_64 target Signed-off-by: adeel10x <[email protected]>
Signed-off-by: adeel10x <[email protected]>
Signed-off-by: adeel10x <[email protected]>
…ypes f32xf32->f32, using tile Size {M0,N0,K0} = {1,32,1} to {7,32,1}
Signed-off-by: adeel10x <[email protected]>
…tiles {M0,N0,K0} = {1,32,1} to {7,32,1}
Signed-off-by: adeel10x <[email protected]>
Signed-off-by: adeel10x <[email protected]>
…b-65536b) for mmt4d ukernel (f32xf32->f32) for riscv_64 target Signed-off-by: adeel10x <[email protected]>
…riscv_64 matmul ukernel tile size querying function, and use suffix 'v' for V extension ukernels V, the standard vector extension for application processors is not included in the base ISA(https://five-embeddev.com/riscv-user-isa-manual/Priv-v1.12/intro.html#risc-v-isa-overview). So, suffix 'base' is replaced by 'v' Signed-off-by: adeel10x <[email protected]>
…hmarks
While compiling for RISC-V V extension, tile size for mmt4d is calculated based on the VLEN. Tile sizes of {7, 16, 1} correspondonds to the smallest possible VLEN for V extension: 128 bits. This tile sizes is chosen for ukernel tests so that tests passes on all cpus supporting V extension.
Signed-off-by: adeel10x <[email protected]>
…mCPUFeatures for clarity Signed-off-by: adeel10x <[email protected]>
Signed-off-by: adeel10x <[email protected]>
…re while compiling files that include <riscv_vector.h> header Signed-off-by: adeel10x <[email protected]>
…v_64/ Signed-off-by: adeel10x <[email protected]>
…riscv_64_v.c to prevent compilation error while using clang-18 Signed-off-by: adeel10x <[email protected]>
|
Hi @bjacob, |
…t4d_test.c files Signed-off-by: adeel10x <[email protected]>
|
@bjacob CI checks are passing now. Let me know if you want me to add anything else 😊. |
|
Looks great! Do you want me to merge this for you? |
Yes, you can merge this. |
|
Thanks @adeel10x for pushing through this. This is a great addition to IREE! |
…riscv64 (#20263) ## PR Summary This PR enables the `linalg.mmt4d` operation and adds mmt4d microkernels for the riscv64 target. ## Status This is a work in progress. The current microkernel implementation is a placeholder, and we would like to discuss the tiling and microkernel design strategy with IREE authors before proceeding further ## RISC-V Vector Considerations According to the RISC-V specification, the vector register length (VLEN) can range from VLEN = 32 to VLEN = 65,536. However, in real hardware, we've mostly observed VLEN ≤ 4096. Additionally, RISC-V Vector supports a vector register group multiplier (LMUL), which allows multiple vector registers to be grouped together at runtime. This enables a single vector instruction to operate on multiple registers. ## Tile Size Selection Strategy Currently, we are considering selecting a tile size based on VLEN. The maximum tile size {7,32,1} specified [here](https://github.com/iree-org/iree/pull/20263/files#:~:text=for%20VLEN%3D256-,TileMxNxK%7B7%2C%2032%2C%201%7D,-%2C%20//%20Aim) is optimized for VLEN = 256, achieving 100% vector register utilization in mmt4d ukernel when using the vfmacc instruction with LMUL = 4: - Result Accumulation: 7 × 4 = 28 registers - RHS Tile: 1 × 4 = 4 registers For this particular tile size, the mmt4d ukernel code would look something like this: ``` if (params->flags & IREE_UK_FLAG_MMT4D_ACCUMULATE) { acc0 = __riscv_vle32_v_f32m4(out_ptr, vlmax); acc1 = __riscv_vle32_v_f32m4(out_ptr + 32, vlmax); acc2 = __riscv_vle32_v_f32m4(out_ptr + 64, vlmax); acc3 = __riscv_vle32_v_f32m4(out_ptr + 96, vlmax); acc4 = __riscv_vle32_v_f32m4(out_ptr + 128, vlmax); acc5 = __riscv_vle32_v_f32m4(out_ptr + 160, vlmax); acc6 = __riscv_vle32_v_f32m4(out_ptr + 192, vlmax); } else { acc0 = __riscv_vfmv_v_f_f32m4(0.0, vlmax); acc1 = __riscv_vfmv_v_f_f32m4(0.0, vlmax); acc2 = __riscv_vfmv_v_f_f32m4(0.0, vlmax); acc3 = __riscv_vfmv_v_f_f32m4(0.0, vlmax); acc4 = __riscv_vfmv_v_f_f32m4(0.0, vlmax); acc5 = __riscv_vfmv_v_f_f32m4(0.0, vlmax); acc6 = __riscv_vfmv_v_f_f32m4(0.0, vlmax); } for (int k = 0; k < params->K; ++k) { vfloat32m4_t rhs = __riscv_vle32_v_f32m4(rhs_ptr, vlmax); rhs_ptr += 32; float lhs0 = *lhs_ptr++; float lhs1 = *lhs_ptr++; float lhs2 = *lhs_ptr++; float lhs3 = *lhs_ptr++; float lhs4 = *lhs_ptr++; float lhs5 = *lhs_ptr++; float lhs6 = *lhs_ptr++; acc0 = __riscv_vfmacc_vf_f32m4(acc0, lhs0, rhs, vlmax); acc1 = __riscv_vfmacc_vf_f32m4(acc1, lhs1, rhs, vlmax); acc2 = __riscv_vfmacc_vf_f32m4(acc2, lhs2, rhs, vlmax); acc3 = __riscv_vfmacc_vf_f32m4(acc3, lhs3, rhs, vlmax); acc4 = __riscv_vfmacc_vf_f32m4(acc4, lhs4, rhs, vlmax); acc5 = __riscv_vfmacc_vf_f32m4(acc5, lhs5, rhs, vlmax); acc6 = __riscv_vfmacc_vf_f32m4(acc6, lhs6, rhs, vlmax); } __riscv_vse32_v_f32m4(out_ptr, acc0, vlmax); __riscv_vse32_v_f32m4(out_ptr + 32, acc1, vlmax); __riscv_vse32_v_f32m4(out_ptr + 64, acc2, vlmax); __riscv_vse32_v_f32m4(out_ptr + 96, acc3, vlmax); __riscv_vse32_v_f32m4(out_ptr + 128, acc4, vlmax); __riscv_vse32_v_f32m4(out_ptr + 160, acc5, vlmax); __riscv_vse32_v_f32m4(out_ptr + 192, acc6, vlmax); ``` --------- Signed-off-by: adeel10x <[email protected]>
| // One concern that needs to be addressed here is that | ||
| // for larger VLENs tile sizes would be very large | ||
| // leading to a very high padding overhead | ||
| int N0 = vlen / 8; |
There was a problem hiding this comment.
@adeel10x If I'm not mistaken, N0 holds the vector size in bytes, where TileMxNxK have elements width, no? Shouldn't it be int N0 = vlen / elementBitWidth ?
There was a problem hiding this comment.
Specifying 8kbits vlen, it actually generates 32kbits vectors:
%1117 = llvm.intr.fmuladd(%1115, %1106, %1116) : (vector<1024xf32>,vector<1024xf32>,vector<1024xf32>) -> vector<1024xf32>
There was a problem hiding this comment.
We are calculating tile sizes here. N0 is the tile size for N dimension (Number of elements along N dimension of the tile). Here, we are expressing tile size for N dimension as a function of vlen.
There was a problem hiding this comment.
Specifying 8kbits vlen, it actually generates 32kbits vectors:
%1117 = llvm.intr.fmuladd(%1115, %1106, %1116) : (vector<1024xf32>,vector<1024xf32>,vector<1024xf32>) -> vector<1024xf32>
What is the assembly code for this? Does it set lmul=4 in the assembly? Also, if you're encountering performance issues, try enabling the ukernel instead.
There was a problem hiding this comment.
We are calculating tile sizes here. N0 is the tile size for N dimension (Number of elements along N dimension of the tile). Here, we are expressing tile size for N dimension as a function of vlen.
Perhaps I've got something wrong, my understanding is that:
vlen = hw_vector_length in bits
vlen / 8 = hw_vector_length in bytes <===
Given this code, if vlen = 256 bits:
N0 = vlen / 8 will set N dimension to 32 elements...
but if the element has a 32 bit width (f32 / i32), now your N dimension has 32 * 32 = 1024 bits (instead of 256 bits). So it takes 4 vector registers to hold it. For (f16/i16) case it will take 2 vector registers. Is that the expected behavior?
I would imagine you want to restrict the N dimension to use a single vector register by doing
N0 = vlen / element_bitwidth
?
Specifying 8kbits vlen, it actually generates 32kbits vectors:
%1117 = llvm.intr.fmuladd(%1115, %1106, %1116) : (vector<1024xf32>,vector<1024xf32>,vector<1024xf32>) -> vector<1024xf32>What is the assembly code for this? Does it set lmul=4 in the assembly? Also, if you're encountering performance issues, try enabling the ukernel instead.
This is during the ukernel lowering process.
Dumping the phases, we get, for a vlen = 8192:
mlp_down_proj_matmul.9.executable-configurations.mlir:
%16 = linalg.fill {lowering_config = #config1} ins(%cst : f32) outs(%15 : tensor<439x?x7x1024xf32>) -> tensor<439x?x7x1024xf32>
%17 = linalg.mmt4d {lowering_config = #config2} ins(%14, %13 : tensor<439x8192x7x1xf32>, tensor<?x8192x1024x1xf32>) outs(%16 : tensor<439x?x7x1024xf32>) -> tensor<439x?x7x1024xf32>
and at kernel call phase:
builtin.module attributes {llvm.data_layout = "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128", llvm.target_triple = "riscv64-unknown-unknown-eabi-elf"} {
llvm.func @iree_uk_unpack(!llvm.ptr, i64, i64, i64, !llvm.ptr, i64, i64, i64, i64, i64, i64, i64, i64, i64, i32, !llvm.ptr) -> i32 attributes {hal.import.bitcode = true, hal.import.fields = ["processor_data"], llvm.bareptr = true}
llvm.func @iree_uk_mmt4d(!llvm.ptr, i64, i64, !llvm.ptr, i64, i64, !llvm.ptr, i64, i64, i64, i64, i64, i32, i32, i32, i32, !llvm.ptr) -> i32 attributes {hal.import.bitcode = true, hal.import.fields = ["processor_data"], llvm.bareptr = true}
In the tensors you'll see the N dimension to be 1024 elements:
439x?x7x1024xf32 where I imagined it should be 439x?x7x256xf32 as 256 x 32 bits per element = vlen.
There was a problem hiding this comment.
What is the assembly code for this? Does it set lmul=4 in the assembly? Also, if you're encountering performance issues, try enabling the ukernel instead.
Sry, I don't have the hardware to run this just yet.
There was a problem hiding this comment.
RISC-V Vector allows operations on data larger than VLEN bits by specifying LMUL > 1. So, with VLEN=8192 bits, it is possible to operate on 1024xf32 = 32Kb data by setting LMUL=4 (8192 x 4 = 32Kb). Thus, tile sizes selected above shouldn't cause an issue.
There was a problem hiding this comment.
To view dispatch's assembly generated by IREE you can use --iree-hal-dump-executable-intermediates-to=<path> option.
PR Summary
This PR enables the
linalg.mmt4doperation and adds mmt4d microkernels for the riscv64 target.Status
This is a work in progress. The current microkernel implementation is a placeholder, and we would like to discuss the tiling and microkernel design strategy with IREE authors before proceeding further
RISC-V Vector Considerations
According to the RISC-V specification, the vector register length (VLEN) can range from VLEN = 32 to VLEN = 65,536. However, in real hardware, we've mostly observed VLEN ≤ 4096. Additionally, RISC-V Vector supports a vector register group multiplier (LMUL), which allows multiple vector registers to be grouped together at runtime. This enables a single vector instruction to operate on multiple registers.
Tile Size Selection Strategy
Currently, we are considering selecting a tile size based on VLEN. The maximum tile size {7,32,1} specified here is optimized for VLEN = 256, achieving 100% vector register utilization in mmt4d ukernel when using the vfmacc instruction with LMUL = 4:
For this particular tile size, the mmt4d ukernel code would look something like this: