Skip to content

[LLVMCPU][RISCV] Add RVV int8 vector-contract custom kernels for widening i8*i8->i32 matmul - #23734

Merged
egebeysel merged 4 commits into
iree-org:mainfrom
ucb-bar:agustin/riscv-rvv-int8-kernels-23730
Jun 8, 2026
Merged

egebeysel merged 4 commits into
iree-org:mainfrom
ucb-bar:agustin/riscv-rvv-int8-kernels-23730

Conversation

@copparihollmann

Copy link
Copy Markdown
Contributor

Fixes #23730

This PR adds RVV custom vector-contract kernel support for widening i8*i8->i32 matmul on RISC-V.

It updates:

  • CPU encoding tile enumeration for RVV int8->i32 matmul
  • LLVMCPU kernel dispatch RVV vector sizes
  • VectorContractCustomKernels with an RVV intrinsic-based int8 path
  • lit tests for vector-contract custom kernels and mmt4d vector lowering

Something I would like some feedback on is what would be your preferred way to test this e2e. So far I compile it and run it on the Banana-pi SpacemiT X60.

Assisted-by: ChatGPT

Copilot AI review requested due to automatic review settings March 11, 2026 02:15
@copparihollmann
copparihollmann requested a review from jtuyls as a code owner March 11, 2026 02:15

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Adds a RISC-V RVV-based custom kernel path for widening int8 matmul (i8×i8→i32) by generating RVV LLVM intrinsics instead of inline asm, and wires the relevant tiling/dispatch heuristics and tests.

Changes:

  • Add RVV i8×i8→i32 custom kernels implemented via llvm.riscv.vwmul + llvm.riscv.vwadd.w intrinsics.
  • Register RVV kernel shapes derived from VLEN (+zvl*) and add MLIR tests validating the intrinsic-based lowering.
  • Extend RISC-V matmul tiling heuristics/encoding enumeration to recognize widening i8→i32 matmul patterns.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
compiler/src/iree/compiler/Codegen/LLVMCPU/VectorContractCustomKernels.cpp Introduces RVV intrinsic kernel generation + pattern registration based on VLEN.
compiler/src/iree/compiler/Codegen/LLVMCPU/test/vector_contract_to_riscv_rvv_intrinsics.mlir New test ensuring vector.contract is replaced with RVV intrinsics for widening int8 matmul shapes.
compiler/src/iree/compiler/Codegen/LLVMCPU/test/riscv64_rvv_vector_lowering.mlir New tests covering RVV vector-lowering behavior and kernel enable/disable toggles.
compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp Adds widening i8→i32 matmul recognition and updates RISC-V vector tiling heuristic.
compiler/src/iree/compiler/Codegen/ExternalInterfaces/CPUEncodingExternalModels.cpp Extends riscv64 matmul tile enumeration to include widening i8×i8→i32.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +287 to +299
MMTKernel kernel;
kernel.lhsType = MMTKernel::ScalarType::I8;
kernel.rhsType = MMTKernel::ScalarType::I8;
kernel.accType = MMTKernel::ScalarType::I32;
kernel.m0 = static_cast<int16_t>(m0);
kernel.k0 = 1;
kernel.n0 = static_cast<int16_t>(n0);
kernel.lhsRegSize = static_cast<int16_t>(m0);
kernel.rhsRegSize = static_cast<int16_t>(n0);
kernel.accRegSize = static_cast<int16_t>(n0);
kernel.lhsRegs = 1;
kernel.rhsRegs = 1;
kernel.accRegs = static_cast<int16_t>(m0);

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

MMTKernel fields (m0/n0/lhsRegSize/rhsRegSize/accRegSize/accRegs) are int8_t, but this constructor assigns values via int16_t casts. For larger RVV VLENs (e.g. +zvl2048b => n0=128, +zvl4096b => n0=256), these will truncate/overflow, breaking validate() invariants and generating invalid kernels. Please either clamp the derived n0 to the representable range (and avoid registering kernels that don't fit), or widen the MMTKernel dimension/register-size fields to a larger integer type and validate bounds explicitly.

Suggested change
MMTKernel kernel;
kernel.lhsType = MMTKernel::ScalarType::I8;
kernel.rhsType = MMTKernel::ScalarType::I8;
kernel.accType = MMTKernel::ScalarType::I32;
kernel.m0 = static_cast<int16_t>(m0);
kernel.k0 = 1;
kernel.n0 = static_cast<int16_t>(n0);
kernel.lhsRegSize = static_cast<int16_t>(m0);
kernel.rhsRegSize = static_cast<int16_t>(n0);
kernel.accRegSize = static_cast<int16_t>(n0);
kernel.lhsRegs = 1;
kernel.rhsRegs = 1;
kernel.accRegs = static_cast<int16_t>(m0);
// Clamp dimensions and register sizes to the range representable by the
// underlying MMTKernel fields (int8_t), to avoid truncation/overflow.
auto clampToInt8 = [](int64_t v) -> int16_t {
if (v > 127)
return static_cast<int16_t>(127);
if (v < -128)
return static_cast<int16_t>(-128);
return static_cast<int16_t>(v);
};
int16_t m0Clamped = clampToInt8(m0);
int16_t n0Clamped = clampToInt8(n0);
MMTKernel kernel;
kernel.lhsType = MMTKernel::ScalarType::I8;
kernel.rhsType = MMTKernel::ScalarType::I8;
kernel.accType = MMTKernel::ScalarType::I32;
kernel.m0 = m0Clamped;
kernel.k0 = 1;
kernel.n0 = n0Clamped;
kernel.lhsRegSize = m0Clamped;
kernel.rhsRegSize = n0Clamped;
kernel.accRegSize = n0Clamped;
kernel.lhsRegs = 1;
kernel.rhsRegs = 1;
kernel.accRegs = m0Clamped;

Copilot uses AI. Check for mistakes.
Comment on lines +263 to +284
static size_t getRISCVVVlenFromCPUFeatures(DictionaryAttr config) {
if (hasFeature(config, "+zvl65536b")) {
return 65536;
} else if (hasFeature(config, "+zvl32768b")) {
return 32768;
} else if (hasFeature(config, "+zvl16384b")) {
return 16384;
} else if (hasFeature(config, "+zvl8192b")) {
return 8192;
} else if (hasFeature(config, "+zvl4096b")) {
return 4096;
} else if (hasFeature(config, "+zvl2048b")) {
return 2048;
} else if (hasFeature(config, "+zvl1024b")) {
return 1024;
} else if (hasFeature(config, "+zvl512b")) {
return 512;
} else if (hasFeature(config, "+zvl256b")) {
return 256;
}
return 128;
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

This file introduces a local getRISCVVVlenFromCPUFeatures() helper, but the same feature-parsing logic already exists in Codegen/ExternalInterfaces/CPUEncodingExternalModels.cpp. Duplicating the exact zvl* chain increases the risk of the two drifting (e.g. when new zvl sizes are added). Consider moving this helper to a shared header/utility (or reusing the existing one) so RVV VLEN derivation stays consistent across codegen components.

Suggested change
static size_t getRISCVVVlenFromCPUFeatures(DictionaryAttr config) {
if (hasFeature(config, "+zvl65536b")) {
return 65536;
} else if (hasFeature(config, "+zvl32768b")) {
return 32768;
} else if (hasFeature(config, "+zvl16384b")) {
return 16384;
} else if (hasFeature(config, "+zvl8192b")) {
return 8192;
} else if (hasFeature(config, "+zvl4096b")) {
return 4096;
} else if (hasFeature(config, "+zvl2048b")) {
return 2048;
} else if (hasFeature(config, "+zvl1024b")) {
return 1024;
} else if (hasFeature(config, "+zvl512b")) {
return 512;
} else if (hasFeature(config, "+zvl256b")) {
return 256;
}
return 128;
}
// Defer to the shared RVV VLEN derivation helper defined in the external
// CPU encoding models implementation, to keep zvl* feature parsing logic
// centralized and consistent across codegen components.
size_t getRISCVVVlenFromCPUFeatures(DictionaryAttr config);

Copilot uses AI. Check for mistakes.
Comment on lines +1295 to +1302
if (isRISCV(targetConfig) && hasFeature(targetConfig, "+v")) {
int64_t vlen = static_cast<int64_t>(getRISCVVVlenFromCPUFeatures(targetConfig));
int64_t n0 = vlen / 16;

// Follow the existing RVV tiling style: primary shape plus truncations.
patterns.add<MMTCustomKernelPattern>(context, MMTKernel_RVV_i8i8i32(8, n0));
patterns.add<MMTCustomKernelPattern>(context, MMTKernel_RVV_i8i8i32(7, n0));
patterns.add<MMTCustomKernelPattern>(context, MMTKernel_RVV_i8i8i32(4, n0));

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

n0 is derived as vlen/16 and then used to build MMTKernel instances, but MMTKernel stores n0/rhsRegSize/accRegSize as int8_t. For VLEN >= 2048b this produces n0 >= 128, which will overflow/truncate and may register nonsensical kernels for such targets. Please add an explicit bound check here (and skip pattern registration when n0 is out of range) or widen the MMTKernel dimension fields so this computation is safe for all supported zvl* values.

Copilot uses AI. Check for mistakes.
Comment on lines +1640 to +1644
// use K = 1 and derive N from the accumulator width.
int64_t maxNumberElementsForLMUL4 =
(nativeVectorSize * 2 * kByteSizeInBits) / kAccumulatorBitWidth;

sizes.assign({8, maxNumberElementsForLMUL4, 1});

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

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

The widening i8i8->i32 path computes maxNumberElementsForLMUL4 as (nativeVectorSize * 2 * 8) / 32, which corresponds to LMUL4 when nativeVectorSize is already based on LMUL=2 (per the comment). However, the RVV custom kernels / encoding tiling added in this PR use N0 = VLEN/16 (i32 LMUL2), not VLEN/8 (i32 LMUL4). With typical configs where native_vector_size = VLEN2/8, this heuristic will pick an N tile that is 2x larger than the available custom kernel shapes and may also cause excessive register pressure. Please align this calculation with the chosen kernel/encoding tiling (e.g. derive N from LMUL2 here, or update the kernel/encoding tiling to match LMUL4 if that’s the intent).

Suggested change
// use K = 1 and derive N from the accumulator width.
int64_t maxNumberElementsForLMUL4 =
(nativeVectorSize * 2 * kByteSizeInBits) / kAccumulatorBitWidth;
sizes.assign({8, maxNumberElementsForLMUL4, 1});
// use K = 1 and derive N from the accumulator width. Here we derive
// the number of i32 accumulator elements for LMUL=2, matching the
// RVV custom kernel / encoding tiling (e.g. N0 = VLEN/16).
int64_t maxNumberElementsForLMUL2 =
(nativeVectorSize * kByteSizeInBits) / kAccumulatorBitWidth;
sizes.assign({8, maxNumberElementsForLMUL2, 1});

Copilot uses AI. Check for mistakes.
@copparihollmann
copparihollmann force-pushed the agustin/riscv-rvv-int8-kernels-23730 branch from df64237 to 02c68e0 Compare March 11, 2026 02:32
@hanhanW
hanhanW requested a review from bjacob March 11, 2026 02:47
@bjacob
bjacob requested a review from egebeysel March 11, 2026 02:59
@bjacob

ghost commented Mar 11, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the PR. Just some context as I will be OOO for a week (March 12-22).

VectorContractCustomKernels is the most ancient form of microkernels, dating back to 2021. Handling only a vector.contract op and not a whole loop, it is inherently limited in what it can do. In particular, it has to operate on the linear layout vectors, it has nowhere to hide layout changes and that tends to severely limit its ability to achieve peak performance outside of simple cases. This is mentioned here as the original motivation for whole-loop microkernels (which became the current mmt4d microkernels):

// What's with the horrendous shuffles (zip, uzp instructions) ?
// The smmla instruction works with a 2x2 accumulator tile.
// So at the moment, given the MMT vector.contract representation of
// the basic block, we have to perform this re-tiling to 2x2 tiles.
//
// This is not really optimized -- just provided to help shape the next
// stage of the discussion, which will be how we change the abstractions
// to resolve this.
//
// For instance, if we compiled a whole loop at once, we would only need
// to do so at the start and at the end of the loop. Or even without
// handing the whole loop to asm, we could make the vector.contract
// higher-dimensional to allow representing this nested tiled layout.
// One thing that we should keep in mind though is that this unusual
// 2x2 tiled layout is specific to matrix multiplication instructions.
// If the matmul kernel were fused into consumer ops, those would probably
// prefer not to deal with a 2x2 tiled layout.
//
// We also can't easily generalize from this to what will be ARMv9+SME.
// There, the matmul instruction will also produce a 2D matrix tile,
// but that will be much wider, 16x16, and itself row-major, so that when
// store it back to NEON/SVE registers, each of those will be contained
// within one row. Even if we put multiple such 16x16 tiles side-by-side
// in the overall kernel, that will still be at a scale larger than
// individual NEON/SVE registers.
//
// Rows 0-1 of the 8x8 accumulator tile

It's only incidental that VectorContractCustomKernels hasn't been removed yet.

But now the timing is that even mmt4d microkernels are becoming legacy as I'm trying to import more modern techniques that we developed on the GPU side, into the CPU side: https://hackmd.io/ti1_aQYbQK2rn0YUM1lFKQ

So I don't really want to tell you to do mmt4d microkernels instead now, as that's what I'm trying to make legacy.

So I'm OK with merging this, seeing that it's not very big. Just know that this is assuming that this is a one-off: we wouldn't want too much more of this.

Regarding testing:

  • The current form of this PR already does the right thing in terms of lit-tests.
  • Regarding e2e testing, this would be handled by tests/e2e/matmul/. Edit the BUILD.bazel file there and run bazel_to_cmake.py. This is how we create tests with specific CPU features enabled:
    # LLVMCPU, data-tiling, data-tiling + ukernels.
    [iree_generated_e2e_runner_test(
    name = "e2e_matmul_cpu_dt%s_%s_%s" % (
    ("_uk" if use_uk else ""),
    lhs_rhs_type,
    acc_type,
    ),
    compiler_flags = [
    "--iree-opt-data-tiling",
    ] + [
    "--iree-llvmcpu-enable-ukernels=%s" % ("all" if use_uk else "none"),
    ] + (["--iree-input-demote-f64-to-f32=false"] if acc_type == "f64" else []),
    generator = ":generate_e2e_matmul_tests",
    generator_args = [
    "--lhs_rhs_type=%s" % lhs_rhs_type,
    "--acc_type=%s" % acc_type,
    ] + (["--shapes=small"] if acc_type == "f64" else []),
    tags = ([
    # f16/bf16 trigger internal LLVM assertion errors on riscv and wasm.
    "noriscv",
    "nowasm",
    ] if (lhs_rhs_type == "f16" or lhs_rhs_type == "bf16") else []),
    target_backends_and_drivers = [
    ("llvm-cpu", "local-task"),
    ],
    target_cpu_features_variants = ["generic"] +
    ([
    "arm_64:dotprod:+dotprod",
    "arm_64:i8mm:+i8mm",
    "x86_64:avx512vnni:" + ",".join(X86_64_AVX512_VNNI),
    ] if lhs_rhs_type == "i8" and acc_type == "i32" else [
    "x86_64:avx2:" + ",".join(X86_64_AVX2),
    "x86_64:avx512:" + ",".join(X86_64_AVX512),
    ] if lhs_rhs_type == "f32" and acc_type == "f32" else [
    "x86_64:avx2:" + ",".join(X86_64_AVX2),
    "x86_64:avx512:" + ",".join(X86_64_AVX512),
    "arm_64:fullfp16:+fullfp16",
    ] if lhs_rhs_type == "f16" and acc_type == "f16" else [
    "x86_64:avx2:" + ",".join(X86_64_AVX2),
    "x86_64:avx512:" + ",".join(X86_64_AVX512),
    "arm_64:fp16fml:+fp16fml",
    ] if lhs_rhs_type == "f16" and acc_type == "f32" else [
    "x86_64:avx2:" + ",".join(X86_64_AVX2),
    "x86_64:avx512:" + ",".join(X86_64_AVX512),
    "x86_64:avx512bf16:" + ",".join(X86_64_AVX512_BF16),
    "arm_64:bf16:+bf16",
    ] if lhs_rhs_type == "bf16" and acc_type == "bf16" else [
    "x86_64:avx2:" + ",".join(X86_64_AVX2),
    "x86_64:avx512:" + ",".join(X86_64_AVX512),
    "x86_64:avx512bf16:" + ",".join(X86_64_AVX512_BF16),
    "arm_64:bf16:+bf16",
    ] if lhs_rhs_type == "bf16" and acc_type == "f32" else []),
    test_runner = "//tools/testing/e2e:iree-e2e-matmul-test",
    test_type = "matmul",
    ) for use_uk in [
    False,
    True,
    ] for (lhs_rhs_type, acc_type) in (
    [
    ("i8", "i32"),
    ("f32", "f32"),
    ("f64", "f64"),
    ("f16", "f16"),
    ("f16", "f32"),
    ("bf16", "bf16"),
    ("bf16", "f32"),
    ]
    )]

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

Approving to unblock as I'll be OOO but:

  • Wait for @egebeysel 's review on RISC-V aspects
  • Read my other comment.
  • e2e testing for this is optional.

@copparihollmann

ghost commented Mar 11, 2026

Copy link
Copy Markdown
Contributor Author

Actually, based on what you pointed me to, I would be open to putting in the effort and taking inspiration from what you just linked. Ideally, I would like to follow your latest practices.

I will have a read to what you just sent. I actually ended up here after what we discussed regarding the mmt4d ukernel and mlir ukernels, when you mentioned about moving things to the compiler and doing proper data tiling.

We can still merge it if you think is good. But in any case, I will definitely do my best to move things to how you are trying to implement now things moving forward @bjacob

@bjacob

ghost commented Mar 11, 2026

Copy link
Copy Markdown
Collaborator

So the problem though is that we are in the early stages of a transition where the existing framework (mmt4d) will soon be legacy and the new framework (inner_tiled) isn't available (for CPU) just yet. That's why I'm OK if you just want to merge this. Up to you.

@copparihollmann

ghost commented Mar 11, 2026

Copy link
Copy Markdown
Contributor Author

Okay I see, then in that case it would be lovely to merge it if possible :)

Is there any way to help on the inner tile approach?

Or parallelly while you design it start getting ready some RVV approach for it?

@bjacob

ghost commented Mar 12, 2026

Copy link
Copy Markdown
Collaborator

Okay I see, then in that case it would be lovely to merge it if possible :)

Retryign the bazel build to see if the failure was temporary.

Is there any way to help on the inner tile approach?

Probably not at first as I need to lay the foundation. Yes in later stages I'll work with you and other stakeholders to port your existing kernels to the new framework.

Or parallelly while you design it start getting ready some RVV approach for it?

Yes, I'm talking with @egebeysel and others to ensure alignment.

@copparihollmann
copparihollmann force-pushed the agustin/riscv-rvv-int8-kernels-23730 branch from 02c68e0 to c93efd3 Compare March 19, 2026 07:00
@copparihollmann

ghost commented Mar 19, 2026

Copy link
Copy Markdown
Contributor Author

I did a test on the Banana-Pi SpacemiTX60

For running this though I need to change the following:

runtime/src/iree/base/internal/cpu.c‎

+21-10Lines changed: 21 additions & 10 deletions
Original file line number	Diff line number	Diff line change
@@ -381,6 +381,7 @@ static void iree_cpu_initialize_from_platform_x86_64(uint64_t* out_fields) {
#include <sched.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/auxv.h>
#ifdef __has_include
#if __has_include(<asm/hwprobe.h>)
#include <asm/hwprobe.h>
@@ -418,17 +419,27 @@ long riscv_hwprobe(struct riscv_hwprobe* pairs, size_t pair_count,

static void iree_cpu_initialize_from_platform_riscv_64(uint64_t* out_fields) {
  long rc = riscv_hwprobe(&kv_pairs[0], 1, 0, NULL, 0);
  if (rc != 0) {
    fprintf(stderr, "riscv_hwprobe syscall failed");
    exit(1);
  if (rc == 0) {
    unsigned long long hwprobe = kv_pairs[0].value;
    IREE_COPY_BITS(out_fields[0], IREE_CPU_DATA0_RISCV_64_V, hwprobe,
                  IREE_RISCV_HWPROBE_IMA_V);
    IREE_COPY_BITS(out_fields[0], IREE_CPU_DATA0_RISCV_64_ZVFHMIN, hwprobe,
                  IREE_RISCV_HWPROBE_EXT_ZVFHMIN);
    IREE_COPY_BITS(out_fields[0], IREE_CPU_DATA0_RISCV_64_ZVFH, hwprobe,
                  IREE_RISCV_HWPROBE_EXT_ZVFH);
    return;
  }
  
  unsigned long hwcap = getauxval(AT_HWCAP);
  if (hwcap != 0) {
    unsigned long hwcap_v = (1 << ('V' - 'A'));
    IREE_COPY_BITS(out_fields[0], IREE_CPU_DATA0_RISCV_64_V, hwcap, hwcap_v);
    return;
  }
  unsigned long long hwprobe = kv_pairs[0].value;
  IREE_COPY_BITS(out_fields[0], IREE_CPU_DATA0_RISCV_64_V, hwprobe,
                 IREE_RISCV_HWPROBE_IMA_V);
  IREE_COPY_BITS(out_fields[0], IREE_CPU_DATA0_RISCV_64_ZVFHMIN, hwprobe,
                 IREE_RISCV_HWPROBE_EXT_ZVFHMIN);
  IREE_COPY_BITS(out_fields[0], IREE_CPU_DATA0_RISCV_64_ZVFH, hwprobe,
                 IREE_RISCV_HWPROBE_EXT_ZVFH);
  
  fprintf(stderr, "riscv_hwprobe syscall failed");
  fprintf(stderr, "Unified RISC-V CPU probe failed (no hwprobe, no HWCAP).\n");
}

#else

Benchmark Results

Both paths compiled with +m,+a,+f,+d,+c,+v,+zvl256b. The only difference is data-tiling + ukernel enablement.

Matmul Size With mmt4d Ukernel Without Ukernel Speedup
256x256 i8 4.43 ms 4.41 ms ~1.0x (parity)
512x512 i8 8.82 ms 35.3 ms 4.0x faster

Tile configuration

  • Tile shape: 7x32x1 (M0=7, N0=VLEN/8=32, K0=1)
  • Widening chain: i8(m1) → i16(m2) → i32(m4) using vwmul.vx + vwadd.wv
  • Register budget: 7×LMUL4(acc) + LMUL2(product) + LMUL1(rhs) = 31/32 vector registers
  • Matches the existing f32 RVV path (M0=7, N0=VLEN/8, LMUL=4)

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the updated patch!

Generally looks good to me, the main point is about the use of vwmul + vwadd vs sext + vwmacc. I think we could use some numbers there to judge :)

IREE_UK_MMT4D_TILE(riscv_64, s8, s8, s32, 2, 1, _v)
IREE_UK_MMT4D_TILE(riscv_64, s8, s8, s32, 4, 1, _v)
IREE_UK_MMT4D_TILE(riscv_64, s8, s8, s32, 7, 1, _v)
IREE_UK_MMT4D_TILE(riscv_64, s8, s8, s32, 8, 1, _v)

ghost Mar 23, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is this intentional?

ghost Mar 23, 2026

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.

Indeed, the logic in compiler/src/iree/compiler/Codegen/ExternalInterfaces/CPUEncodingExternalModels.cpp does not produce the case 8 so this tile function is likely unused.

ghost Mar 24, 2026

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.

Good catch, this was from a previous test of mine in that patch that I forgot to remove. Will do so tomorrow!

ghost Mar 24, 2026

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.

Also I will do an implementation with sext + vwmacc and get back to you on that :)

#include "iree/builtins/ukernel/arch/riscv_64/mmt4d_riscv_64_internal.h"

IREE_UK_ATTRIBUTE_ALWAYS_INLINE static inline void
iree_uk_mmt4d_tile_s8s8s32_1xXXx1_to_8xXXx1_riscv_64_v(

ghost Mar 23, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

just to be clear, you choose the inner tile size M to be 7 max, but implement the ukernel for 8 as well?

__riscv_vse32_v_i32m4(out_ptr + N0 * 4, acc4, vl);
__riscv_vse32_v_i32m4(out_ptr + N0 * 5, acc5, vl);
__riscv_vse32_v_i32m4(out_ptr + N0 * 6, acc6, vl);
} else if (M0 == 8) {

ghost Mar 23, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

as previously mentioned, I guess in this case you wouldn't have enough registers and would spill (8 * 4 for acc and you're out for the prods and rhs), so if I'm not missing something, there's no need to keep this here. If this is intended and I'm missing something, please add the layout to the external models file, and a comment explaining the kernel :)

ghost Mar 24, 2026

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.

Will change it accordingly, you are definitely right there and it was something I got leftover

Comment on lines +26 to +30
#define IREE_UK_RISCV_64_VWACC_I8(ACC, LHS, RHS, VL) \
do { \
vint16m2_t prod = __riscv_vwmul_vx_i16m2(RHS, LHS, VL); \
ACC = __riscv_vwadd_wv_i32m4(ACC, prod, VL); \
} while (0)

ghost Mar 23, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do we have to use a two-step multiply-add here? What if we sign-extend the operands to i16 and use vwmacc i16 x i16 -> i32 instead? How would that look like in means of performance? Is there a specific reason you do it this way? I think @adeel10x also pointed this out in Discord.

ghost Mar 24, 2026

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 be honest I focused on getting out the patch I had before so that I could get some feedback first an not overengineer it, but that is a very valid point that I forgot to test :)

Tomorrow I will get to it and get you some metrics back

ghost Mar 25, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yes, In my experience sign-extending the operands to i16 and using vwmacc i16 x i16 -> i32 instead of the 2-step multiply-add results in better perf. I see that you've already made the required changes :).

Comment on lines +199 to +201
IREE_UK_MMT4D_TILE_FUNC_IMPL_FOR_M0(
iree_uk_mmt4d_tile_s8s8s32_1xXXx1_to_8xXXx1_riscv_64_v,
iree_uk_mmt4d_tile_s8s8s32_8xXXx1_riscv_64_v, 8)

ghost Mar 23, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

same as above

const iree_uk_query_tile_sizes_2d_params_t* params) {
#if defined(IREE_UK_BUILD_RISCV_64_V)
if (iree_uk_cpu_riscv_64_v(params->cpu_data)) {
return (iree_uk_matmul_tile_sizes_t){.M = 7, .K = 1, .N = 32};

ghost Mar 23, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm not sure how important this actually is, but the N parameter passed here has the assumption that we have LMUL=4 and VLEN=256bits here, whereas the above f32 one has LMUL=4 but VLEN=128bits. Not sure if they have to be aligned or not...

ghost Mar 23, 2026

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.

query_tile_sizes is a historical thing, from an era when we considered supporting fully dynamic tile sizes with a runtime query based on the device CPU. hasn't actually been used. So, I don't care much what you do here; I don't remember how much the test harness forces you to implement, but do stick to the bare minimum required to pass tests.

ghost Mar 24, 2026

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.

Okay then I will just focus on keeping it to a bare minimum to get the tests passing

@egebeysel

ghost commented Mar 23, 2026

Copy link
Copy Markdown
Contributor

cc @adeel10x

@bjacob
bjacob self-requested a review March 23, 2026 16:29
@copparihollmann

ghost commented Mar 24, 2026

Copy link
Copy Markdown
Contributor Author

Will update tomorrow addressing your comments

@copparihollmann

ghost commented Mar 25, 2026

Copy link
Copy Markdown
Contributor Author

I went through the review points:

  • removed the stray M0=8 tile registration and implementation path
  • kept only M0 = 1, 2, 4, 7
  • switched the final widening path to vsext.vf2 + vwmacc.vx

On Banana Pi SpacemiT X60:

  • Arithmetic comparison on matmul_q_i8_1024.mlir:
    • vwmul.vx + vwadd.wv: 68.9 ms
    • vsext.vf2 + vwmacc.vx: 42.8 ms
  • End-to-end 512x512 i8:
    • with ukernel: 5.61 ms
    • without ukernel: 32.6 ms

So the final implementation is both better inner sequence and better e2e :)

Let me know if this is sufficient or I should change something

#define IREE_UK_RISCV_64_VWMACC_I8(ACC, LHS, RHS, VL) \
do { \
ACC = __riscv_vwmacc_vx_i32m4(ACC, (iree_uk_int16_t)(LHS), RHS, VL); \
} while (0)

ghost Mar 25, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is there a specific reason to use a macro here? Wouldn't it be a bit cleaner to use the vwmacc built-in directly in the ukernel?

ghost Mar 26, 2026

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.

Fair enough, let me fix that :)

ghost Mar 29, 2026

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.

Should be fixed now, sorry for the delay!

@egebeysel

ghost commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Can you fix the DCO error? @copparihollmann

Also, do you need this patch to run this? If so, someone else has to review that.

Other than that, it looks good to me, thanks for updating this and testing :) I'll approve once the DCO is fixed and according to the above patch situation 👍 Would also be nice if you could update the title and the description.

If you have time to do so, you can also get some measurements with more regular/irregular shapes, e.g. pow2s from 128 to 4096 instead of just 512, and non-pow2s, with possibly wide M/N/K dims. But that's not necessary for the PR, you can defer that to later.

@copparihollmann

ghost commented Apr 8, 2026

Copy link
Copy Markdown
Contributor Author

Hi all!

Sorry I was a bit by busy last week, I will get down with it toda/tomorrow :)

@copparihollmann

ghost commented Apr 8, 2026

Copy link
Copy Markdown
Contributor Author

Also, do you need this patch to run this? If so, someone else has to review that.

The patch is only if you want to run it on the banana-pi because of the old linux distro

If you have time to do so, you can also get some measurements with more regular/irregular shapes, e.g. pow2s from 128 to 4096 instead of just 512, and non-pow2s, with possibly wide M/N/K dims. But that's not necessary for the PR, you can defer that to later.

Working on this right now :)

@egebeysel

ghost commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

@copparihollmann Just a quick ping here. If you could fix the DCO issue and the CI failures we can land this PR as is prior to the more extensive measurements.

Agustin N. Coppari Hollmann added 2 commits April 17, 2026 15:50
Add mmt4d runtime microkernel for RISC-V 64 with the V extension,
targeting s8*s8->s32 matmul using widening multiply-accumulate:
vwmul.vx (i8*i8->i16) + vwadd.wv (i16+i32->i32).

Tile: M0={1,2,4,7} x N0=dynamic x K0=1. Primary tile for VLEN=256
is 7x32x1, matching the f32 RVV path's register pressure budget
(7*LMUL4 + LMUL2 + LMUL1 = 31/32 vector registers).

Tested on SpacemiT X60 (VLEN=256): 4x speedup on 512x512 i8 matmul
vs codegen-only path.

Fixes iree-org#23730

Signed-off-by: Agustin N. Coppari Hollmann <[email protected]>
Add VLEN-aware tile size selection for widening integer matmul in
enumerateMatmulTileRiscv64(). Uses N0=VLEN/8 (same formula as f32)
to fully utilize the m1->m2->m4 widening chain at LMUL=4.

Primary tile: {7, VLEN/8, 1} with truncations at M0={4,2,1}.

Signed-off-by: Agustin N. Coppari Hollmann <[email protected]>
Agustin N. Coppari Hollmann added 2 commits April 17, 2026 15:50
@copparihollmann
copparihollmann force-pushed the agustin/riscv-rvv-int8-kernels-23730 branch from f096cd6 to 7bc368d Compare April 17, 2026 22:55
@copparihollmann

ghost commented Apr 17, 2026

Copy link
Copy Markdown
Contributor Author

Done!

Sorry for the delay, our board died (forgot to give a heads-up), so I was waiting for the new one to arrive and do the tests.

DCO should be fixed now @egebeysel

@egebeysel

ghost commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Merging this as is, will fix in a follow-up PR if anything pops up because of something that changed since the quite oldish CI run.

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.

[RISCV] Add RVV int8 custom vector-contract kernels for widening i8*i8->i32 matmul

5 participants