Skip to content

Enable the linalg.mmt4d operation and add mmt4d microkernels for the riscv64 - #20263

Merged
bjacob merged 15 commits into
iree-org:mainfrom
10x-Engineers:main
Jun 16, 2025
Merged

bjacob merged 15 commits into
iree-org:mainfrom
10x-Engineers:main

Conversation

@adeel10x

@adeel10x adeel10x commented Mar 15, 2025 •

Copy link
Copy Markdown
Contributor

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 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);

@adeel10x adeel10x changed the title Enable the linalg.mmt4d operation and add mmt4d, pack, and unpack microkernels for the riscv64 target Enable the linalg.mmt4d operation and add mmt4d, pack, and unpack microkernels for the riscv64 Mar 15, 2025
@adeel10x
adeel10x marked this pull request as draft March 15, 2025 12:43
@bjacob
bjacob self-requested a review March 15, 2025 14:16

@bjacob bjacob left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bjacob bjacob Mar 18, 2025 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. 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=41 values from the LHS and RHS matrices, in order to perform 32*7 = 224 scalar multiply-adds. That yields an arithmetic intensity ratio (defined as the ratio of multiply-adds to loads) of M*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 says 100% 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 had TileMxNxK{12, 16, 1} here, meaning M=12, N=16, that would give you a much higher arithmetic intensity ratio of M*N/(M+N)=6.8x, while using fewer registers (28) and enjoying the convenience of avoiding the odd value 7, see next point.

  2. 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 pack and unpack operations). 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@adeel10x adeel10x Mar 19, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll push the complete ukernel implementation soon, once we finalize the tile size.

@adeel10x

Copy link
Copy Markdown
Contributor Author

Hi @bjacob ,
I wanted to kindly check in on this PR and ask if there’s anything more I should do to move it toward merging. Would you like me to add any specific tests? Also, I was wondering—do you typically use QEMU to run the tests for RISC-V, or is there another preferred method?

@bjacob

bjacob commented Apr 23, 2025

Copy link
Copy Markdown
Collaborator

Hi @bjacob , I wanted to kindly check in on this PR and ask if there’s anything more I should do to move it toward merging. Would you like me to add any specific tests? Also, I was wondering—do you typically use QEMU to run the tests for RISC-V, or is there another preferred method?

@adeel10x , this PR looks good - yes, please just add a test which should be a simple matter of editing the mmt4d_test.c and other _test.c files under ukernel/ to add lines like the existing ones for x86, to ensure that he new RISC-V cases are being covered. You may also need to edit void iree_uk_make_cpu_data_for_features(const char* cpu_features, ...) in util.c to allow specifying your new RVV features there.

Once it's ready, mark the PR ready for review.

@bjacob

bjacob commented Apr 23, 2025

Copy link
Copy Markdown
Collaborator

@adeel10x ,

Also, I was wondering—do you typically use QEMU to run the tests for RISC-V, or is there another preferred method?

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.

@benvanik
benvanik removed their request for review April 28, 2025 17:12
@bjacob

bjacob commented May 5, 2025

Copy link
Copy Markdown
Collaborator

@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.

@adeel10x

adeel10x commented May 6, 2025

Copy link
Copy Markdown
Contributor Author

@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 getauxval to check if the Vector extension is supported, but unfortunately, it doesn’t give us the actual VLEN.
I’m thinking of using a RISC-V vector intrinsic to get the VLEN at runtime, like this:

#include <riscv_vector.h>
size_t getVlen() {
  size_t vl = __riscv_vsetvlmax_e32m1();
  return vl * 32;
}

I’d add this to runtime/src/iree/base/internal/cpu.c. Does that sound reasonable to you, or would you suggest a different approach?

@adeel10x
adeel10x marked this pull request as ready for review May 25, 2025 20:00
@adeel10x
adeel10x requested a review from hanhanW as a code owner May 25, 2025 20:00
@adeel10x
adeel10x requested review from benvanik and bjacob May 25, 2025 20:00
@bjacob

bjacob commented May 26, 2025

Copy link
Copy Markdown
Collaborator

I’d add this to runtime/src/iree/base/internal/cpu.c. Does that sound reasonable to you, or would you suggest a different approach?

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).

@adeel10x

adeel10x commented Jun 1, 2025 •

Copy link
Copy Markdown
Contributor Author

I’d add this to runtime/src/iree/base/internal/cpu.c. Does that sound reasonable to you, or would you suggest a different approach?

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 ,
So I tried getting VLEN info using the RISC-V vector intrinsic as described in my previous comment. The issue with that approach is that we need 'V' extension enabled while compiling runtime/src/iree/base/internal/cpu.c, to be able to use RVV intrinsic call.

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 f32xf32->f32, the optimal tile size is selected as follows:

{M,N,K} = {7, VLEN/8, 1}

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 compiler/src/iree/compiler/Codegen/ExternalInterfaces/CPUEncodingExternalModels.cpp
The ukernel would be modified so that it handles all tile sizes of the form: {1, VLEN/8, 1} to {7, VLEN/8, 1}. I think the only change in the kernel code would be that the rhs_ptr+=32 would get replaced by rhs_ptr+=N0. This way it would be able to cater to all VLENs without compromising performance.

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.

@bjacob

bjacob commented Jun 2, 2025

Copy link
Copy Markdown
Collaborator

Sounds great! If the only way in which the ukernel depends on the VLEN value is for a stride (that pointer increment amount in rhs_ptr+=N0) then you could simply pass that VLEN value as an additional ukernel parameter. Moreover, since, if I understand correctly, that VLEN value is equal to the N0 tile size parameter that is already passed to the mmt4d ukernel, no additional information is needed, and that means that the need to specialize the ukernel for a specific VLEN value was never real?

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 if statements inside your ukernel based on these parameters, and these would all get resolve during compilation after the constant values have propagated.

@adeel10x

adeel10x commented Jun 6, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @bjacob,
This PR is ready for review.
For mmt4d ukernel, I have added a test for the tile {7, 16, 1} which corresponds to VLEN = 128 (the smallest VLEN for V extension). The idea was that tests should pass on any CPU that supports V extension.
Also, I have enabled compilation of uKernels using system toolchains.

// 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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +341 to +356
if (hasFeature(config, "+zvl65536b")) {
vlen = 65536;
} else if (hasFeature(config, "+zvl32768b")) {
vlen = 32768;
} else if (hasFeature(config, "+zvl16384b")) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bjacob

bjacob commented Jun 6, 2025 •

Copy link
Copy Markdown
Collaborator

Hi @bjacob, This PR is ready for review.

Thanks @adeel10x , looking good! Just a couple very minor comments.

Also, the DCO check failed, blocking CI - you need to git commit -s to generate Signed-Off-By tags.

@bjacob

bjacob commented Jun 9, 2025

Copy link
Copy Markdown
Collaborator

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.

@adeel10x

adeel10x commented Jun 9, 2025

Copy link
Copy Markdown
Contributor Author

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.

@adeel10x

Copy link
Copy Markdown
Contributor Author

'Test RISC-V 64' check failed because clang-18 require 'v' feature to be specified using -march even if just the riscv_vector.h header is included.
This isn't the case with clang-19.

I have fixed this issue by enabling the v feature while compiling all files that include riscv_vector.h. Another solution could be to include riscv_vector.h directly in .c files and remove it from common_riscv_64.h.

@bjacob

bjacob commented Jun 10, 2025

Copy link
Copy Markdown
Collaborator

@adeel10x

Another solution could be to include riscv_vector.h directly in .c files and remove it from common_riscv_64.h.

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.

@adeel10x adeel10x changed the title Enable the linalg.mmt4d operation and add mmt4d, pack, and unpack microkernels for the riscv64 Enable the linalg.mmt4d operation and add mmt4d microkernels for the riscv64 Jun 11, 2025
adeel10x added 14 commits June 11, 2025 16:31
…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]>
Signed-off-by: adeel10x <[email protected]>
…re while compiling files that include <riscv_vector.h> header

Signed-off-by: adeel10x <[email protected]>
…riscv_64_v.c to prevent compilation error while using clang-18

Signed-off-by: adeel10x <[email protected]>
@adeel10x

Copy link
Copy Markdown
Contributor Author

Hi @bjacob,
Could you please rerun the pre-commit check? I'm not 100% sure about what caused the failure, but it seems like an issue with the npm service (https://status.npmjs.org/)

@adeel10x

Copy link
Copy Markdown
Contributor Author

@bjacob CI checks are passing now. Let me know if you want me to add anything else 😊.

@bjacob

bjacob commented Jun 16, 2025

Copy link
Copy Markdown
Collaborator

Looks great! Do you want me to merge this for you?

@adeel10x

Copy link
Copy Markdown
Contributor Author

Looks great! Do you want me to merge this for you?

Yes, you can merge this.

@bjacob
bjacob merged commit 9620fa3 into iree-org:main Jun 16, 2025
@bjacob

bjacob commented Jun 16, 2025

Copy link
Copy Markdown
Collaborator

Thanks @adeel10x for pushing through this. This is a great addition to IREE!

AWoloszyn pushed a commit that referenced this pull request Dec 1, 2025
…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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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 ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Specifying 8kbits vlen, it actually generates 32kbits vectors:

  %1117 = llvm.intr.fmuladd(%1115, %1106, %1116) : (vector<1024xf32>,vector<1024xf32>,vector<1024xf32>) -> vector<1024xf32>

@adeel10x adeel10x Dec 10, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@adeel10x adeel10x Dec 10, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@adeel10x adeel10x Dec 15, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To view dispatch's assembly generated by IREE you can use --iree-hal-dump-executable-intermediates-to=<path> option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants