Understanding and Optimizing GEMM: From Naive Matrix Multiplication to Memory-Aware Algorithms on RISC-V

GEMM semantics, blocking, packing, BLIS-like kernels, scratchpad memory, DMA, numerical correctness and Roofline analysis, grounded in the GAP8 research.

Scope and research evidence

GEMM exposes a useful engineering tension: the mathematical operation is compact, but a fast implementation depends on where every operand resides, how often it moves, and how the processor issues arithmetic. This article develops that relationship from a scalar implementation to explicitly managed memory. The analytical models are derived below; they are not measurements of GAP8.

The associated research is A BLIS-like matrix multiplication for machine learning in the RISC-V ISA-based GAP8 processor, hereafter R1. The work was carried out in collaboration with Jie Lei, under the supervision of Enrique Quintana and Adrián Castelló. The research project provides the shorter engineering case study.

Three evidence levels remain separate:

  • Published implementation: the 2022 paper evaluates integer GEMM on the Fabric Controller (FC). Its SDK simulated the vector dot-product operation; a source helper does not establish a single executed hardware instruction R1, §§3–4.
  • Portable educational implementation: the FP32 C examples illustrate semantics and transformations. They are new teaching code, not a reconstruction of the research kernel or a production BLAS replacement.
  • Architectural extensions: DMA overlap, double buffering and multicore decomposition below are proposals for analysis. The paper identifies overlap and cluster execution as future work R1, §5.

The public qblis_gpduino repository explicitly links the same DOI. It is relevant implementation evidence, but a current snapshot is not automatically the exact artifact of a historical experiment R2. No new GAP8 benchmark or energy measurement is claimed here.

View the Research Project · Download the portable C examples and tests

Matrix multiplication as a dependency graph

Start with ordinary real-valued multiplication:

C=AB,A∈RM×K,B∈RK×N,C∈RM×N.C=AB,\qquad A\in\mathbb{R}^{M\times K},\quad B\in\mathbb{R}^{K\times N},\quad C\in\mathbb{R}^{M\times N}.

M is the number of output rows, N the number of output columns, and K the shared inner dimension. With zero-based indices, 0 ≤ i < M, 0 ≤ j < N and 0 ≤ k < K:

Cij=∑k=0K−1AikBkj.C_{ij}=\sum_{k=0}^{K-1}A_{ik}B_{kj}.

Every output depends on one row of A and one column of B. Multiplying a 2-by-3 matrix by a 3-by-2 matrix gives a 2-by-2 result. The entry C[1,0] uses A[1,0:3] and B[0:3,0]; it does not depend on other output entries. Its three products must nevertheless be combined before it is final.

A dot product finishes one output using the full inner dimension. A matrix-vector product computes one output column, using all of A against one column of B. A matrix-matrix product processes multiple columns together, allowing an A value to serve multiple outputs. An outer-product view instead fixes k:

C=∑k=0K−1A:,kBk,:.C=\sum_{k=0}^{K-1}A_{:,k}B_{k,:}.

Each outer product adds a rank-one contribution. An A element can serve N updates, and a B element M updates. These are available reuse opportunities, not promises that a loop nest realizes them in registers or cache.

Compatible dimensions

Dimensions of A, B and C A has M rows and K columns; B has K rows and N columns. The shared inner dimension K must match. Their product C has M rows and N columns. Rectangles are schematic, not to scale. ABC ×= M × KK × NM × N K: reduction dimension

Dot product: one output element

Dependencies of C i j Row i of A and column j of B each contain K elements. Their pairwise products are summed over k to produce the scalar C i j. A[i, :]B[:, j] C[i,j] = Σₖ A[i,k] B[k,j]

Outer product: one contribution

Rank-one update for one fixed k For one fixed k, column k of A, with shape M by one, multiplies row k of B, with shape one by N. This produces an M by N contribution to C. The full product sums these contributions over all K values of k. ×= M×11×NM×N C += A[:,k] × B[k,:]
Two decompositions of the same product: each dot product produces one element; each outer product contributes a matrix of rank at most one. Summing K outer products produces AB. Shapes show dependencies, not dimensions to scale.

Convolution can be expressed using GEMM after arranging receptive fields into a matrix. Materializing that arrangement introduces memory traffic and storage; improving GEMM does not prove an equal end-to-end convolution speedup. Fully connected layers and recurrent computations also use matrix operations. The original matrix-dimension illustration is preserved alongside these new explanatory diagrams.

The GEMM contract: more than three dimensions

General matrix multiplication updates an existing output:

C←α op⁡(A)op⁡(B)+βC.C\leftarrow\alpha\,\operatorname{op}(A)\operatorname{op}(B)+\beta C.

Alpha scales the product; beta scales the previous output. Logical operand dimensions remain M-by-K and K-by-N after applying op. For real operands, op selects the matrix or its transpose. Complex GEMM additionally distinguishes conjugate transpose R5.

Apply beta once, not once per K tile. With beta zero, the result must not depend on initial C values. If K or alpha is zero, the operation reduces to scaling C. If M or N is zero, there are no output elements to touch. These cases are useful for detecting broken blocked implementations.

Layout is independent of mathematical dimensions. In row-major storage, an address in units of elements is base + i*ld + j; leading dimension ld separates successive rows. For untransposed A, B and C, it must accommodate K, N and N elements respectively. Padding can make it larger. A submatrix retains its parent’s leading dimension rather than becoming compact because its logical width shrinks.

In column-major storage the address is base + i + j*ld: the leading dimension separates columns. The Fortran BLAS convention is column-major. A transpose flag changes logical indexing and dimension constraints; it need not physically transpose the allocation. Treating lda as universally M or K is a common interoperability error. Independent row/column strides describe more general tensor views, but the portable examples deliberately support only untransposed row-major operands.

The examples require nonoverlapping A, B and C, valid allocation extents, and representable size/address calculations. They do not support in-place overlap, arbitrary tensor views or general exceptional floating-point inputs. A library interface must validate its contract before dispatch, rather than letting layout mistakes appear as numerical errors.

Arithmetic work, storage and communication

For positive K, an independently reduced dot product needs K multiplications and K−1 additions. The exact unscaled-product count under this convention is:

FAB=MN(2K−1),F≈2MNK.F_{AB}=MN(2K-1),\qquad F\approx2MNK.

The usual approximation counts acc += a*b as two arithmetic operations. A fused multiply-add contributes two floating-point operations under that convention, although it is one instruction with a single final rounding. Applying alpha, beta and the final sum can add roughly three operations per output; special coefficients eliminate some work. State whether a rate uses conventional 2MNK useful work or includes that epilogue.

For FP32, the convention gives FLOP/s. For INT8 multiplication with integer accumulation, report integer operations/s. MAC/s counts a multiply-accumulate as one, whereas the two-operation convention counts it as two. A four-lane packed dot product contributes eight integer operations under that latter convention, not eight FLOPs. Align these definitions before comparing implementations.

The classical loop body executes MNK times: cubic work for square problems, proportional to MNK generally. Resident operand/output storage is proportional to MK + KN + MN, while a scalar implementation needs constant auxiliary workspace. Blocking and packing add organization and possibly workspace; they do not reduce the classical arithmetic count.

Communication is separate. Registers can reuse loaded operands; cache lines can serve multiple accesses; DMA can move contiguous panels. Source-level load expressions do not equal transferred bytes at every boundary. Assuming each input crosses once and C is read/written once gives a footprint-based estimate:

Qonce=sAMK+sBKN+2sCMN.Q_{\mathrm{once}}=s_A MK+s_B KN+2s_C MN.

The s values are stored bytes per element. With beta zero, an initial C read may be omitted in an explicitly controlled scheme. This estimate may be unattainable with limited fast memory. Write allocation, repeated panels, packing and intermediate spills increase traffic. Communication-avoiding design asks which values can remain resident across more useful arithmetic, rather than merely reducing instruction count.

Numerical representation is part of correctness

Representation changes bandwidth demand, supported instructions, accumulator pressure and the acceptable result. FP32, FP16 and BF16 are not interchangeable storage labels. FP16 has a narrower exponent range than FP32; BF16 retains an FP32-like exponent range with fewer significand bits. Input conversion loses information. Whether lower-precision inputs accumulate in FP32 is an explicit kernel contract, not a consequence of their storage size.

Floating-point addition is not associative. Loop transformations, vector reductions and fused operations can change rounding despite implementing the same real-valued formula. A higher-precision reference and absolute-plus-relative tolerance are useful, but cancellation makes purely relative comparison unreliable near zero. A stronger diagnostic also considers the magnitude of contributing products. Record contraction and reassociation flags: -ffast-math changes the numerical assumptions permitted to the compiler R8.

For full-range signed INT8 inputs, −128 through 127, the largest positive product magnitude is 16384. An INT32 accumulator initially zero has this conservative sufficient bound:

K 16384≤231−1⟹K≤131071.K\,16384\leq2^{31}-1\quad\Longrightarrow\quad K\leq131071.

This guarantees safety for arbitrary raw INT8 inputs without bias or previous accumulation. It is not a universal quantized-network limit: initial accumulator values, zero-point subtraction, bias and rescaling change the range budget. In C, signed overflow is undefined behavior. The accompanying integer example accumulates in INT64 and checks INT32 range before conversion; it does not demonstrate a GAP8 instruction.

Fixed-point arithmetic associates an integer with an implicit scale. Multiplication changes that scale, and conversion back requires a specified shift, rounding rule and range policy. Saturation clips an unrepresentable result and changes the operation. It is neither ordinary wraparound nor an exact correction for overflow.

A simple affine quantization model is:

x≈sx(qx−zx),sx>0.x\approx s_x(q_x-z_x),\qquad s_x>0.

Here q is the stored integer, z the zero point and s the scale. Centered-integer products approximate real products after rescaling. The LiteRT specification supplies a concrete framework contract R7; it must not be silently imposed on this historical research. Quantization introduces approximation and possibly clipping. Bias, zero-point correction, requantization and activation clipping are additional work absent from bare integer GEMM.

Kernel correctness and application accuracy are distinct requirements: computing the declared integer operation exactly does not establish that the quantized application meets its accuracy target. Conversely, small application-level error does not excuse undefined overflow inside the kernel.

Algorithms 1–2: naive GEMM and loop reordering

Portable C example. The downloadable package supplies declarations, validation/scaling helpers and build commands. All three FP32 kernels accept M, N, K and padded leading dimensions; inputs are row-major, untransposed and nonoverlapping. They implement alpha/beta semantics for finite inputs whose intermediate products and accumulations remain representable. The article includes the exact source compiled by the tests.

/* Portable C: FP32 row-major, i-j-k order; helpers are in gemm.c. */
int gemm_naive(size_t m, size_t n, size_t k, float alpha,
               const float *a, size_t lda, const float *b, size_t ldb,
               float beta, float *c, size_t ldc) {
    int status = gemm_validate(m, n, k, alpha, a, lda, b, ldb, c, ldc);
    if (status != GEMM_OK || m == 0 || n == 0) return status;
    if (alpha == 0.0f || k == 0) {
        gemm_scale(m, n, beta, c, ldc);
        return GEMM_OK;
    }
    for (size_t i = 0; i < m; ++i) {
        for (size_t j = 0; j < n; ++j) {
            float sum = 0.0f;
            for (size_t p = 0; p < k; ++p)
                sum += a[i * lda + p] * b[p * ldb + j];
            float old_c = beta == 0.0f ? 0.0f : beta * c[i * ldc + j];
            c[i * ldc + j] = alpha * sum + old_c;
        }
    }
    return GEMM_OK;
}

The i-j-k order completes one output at a time. A’s row is contiguous, but successive B values are ldb elements apart. A can be revisited for every output column. Whether those accesses hit cache depends on capacity, associativity and other active data. One scalar accumulator avoids repeatedly storing that dot product’s partial sum.

Changing to i-k-j exposes contiguous B and C rows:

/* Portable C: FP32 row-major, i-k-j order; helpers are in gemm.c. */
int gemm_reordered(size_t m, size_t n, size_t k, float alpha,
                   const float *a, size_t lda, const float *b, size_t ldb,
                   float beta, float *c, size_t ldc) {
    int status = gemm_validate(m, n, k, alpha, a, lda, b, ldb, c, ldc);
    if (status != GEMM_OK || m == 0 || n == 0) return status;
    gemm_scale(m, n, beta, c, ldc);  /* Scale C exactly once. */
    if (alpha == 0.0f || k == 0) return GEMM_OK;
    for (size_t i = 0; i < m; ++i) {
        for (size_t p = 0; p < k; ++p) {
            float scaled_a = alpha * a[i * lda + p];
            for (size_t j = 0; j < n; ++j)
                c[i * ldc + j] += scaled_a * b[p * ldb + j];
        }
    }
    return GEMM_OK;
}

For a fixed (i,k), one scaled A value serves N outputs. Contiguous B/C accesses can make vectorization easier, but C is updated repeatedly across k. If the output row cannot remain cached, that traffic can outweigh better B access. Applying alpha inside the reduction also changes rounding relative to scaling the completed dot product; the tests use a declared tolerance, not bitwise equality.

The k-i-j order reuses a B row across output rows but revisits a larger part of C for each k. It can help if that output working set stays resident and hurt when it does not. Column-major storage changes which traversal is contiguous. There is no universally best permutation independent of layout and hierarchy.

A compiler may unroll, vectorize, hoist loads or contract multiply-adds, subject to aliasing and numerical rules. Source analysis predicts opportunities, not exact executed load counts. Inspect optimization diagnostics and assembly before attributing a result to a particular instruction sequence. Both variants retain proportional-to-MNK arithmetic and constant auxiliary workspace.

Algorithm 3: blocking for a bounded working set

Blocking limits the part of A, B and C reused at a time. An output tile contains at most BM rows and BN columns; each reduction panel contains at most BK inner elements. For row block I, column block J and inner block P:

CI,J←βCI,J+α∑PAI,PBP,J.C_{I,J}\leftarrow\beta C_{I,J}+\alpha\sum_P A_{I,P}B_{P,J}.

Clip the final blocks to the remaining dimensions. Beta belongs outside the sum over K panels. A capacity estimate for simultaneous tiles is:

W=sABMBK+sBBKBN+sCBMBN.W=s_A B_M B_K+s_B B_K B_N+s_C B_M B_N.

Portable C example. This kernel scales C once, then performs edge-aware blocking. BM, BN and BK must be positive. It uses FP32 storage/accumulation, no packing and no explicit DMA.

/* Portable C: FP32 row-major; bm/bn/bk must be nonzero. */
int gemm_blocked(size_t m, size_t n, size_t k, float alpha,
                 const float *a, size_t lda, const float *b, size_t ldb,
                 float beta, float *c, size_t ldc,
                 size_t bm, size_t bn, size_t bk) {
    if (bm == 0 || bn == 0 || bk == 0) return GEMM_INVALID;
    int status = gemm_validate(m, n, k, alpha, a, lda, b, ldb, c, ldc);
    if (status != GEMM_OK || m == 0 || n == 0) return status;
    gemm_scale(m, n, beta, c, ldc);
    if (alpha == 0.0f || k == 0) return GEMM_OK;
    for (size_t ii = 0; ii < m;) {
        size_t i_end = gemm_edge(ii, bm, m);
        for (size_t jj = 0; jj < n;) {
            size_t j_end = gemm_edge(jj, bn, n);
            for (size_t pp = 0; pp < k;) {
                size_t p_end = gemm_edge(pp, bk, k);
                for (size_t i = ii; i < i_end; ++i)
                    for (size_t p = pp; p < p_end; ++p) {
                        float scaled_a = alpha * a[i * lda + p];
                        for (size_t j = jj; j < j_end; ++j)
                            c[i * ldc + j] += scaled_a * b[p * ldb + j];
                    }
                pp = p_end;
            }
            jj = j_end;
        }
        ii = i_end;
    }
    return GEMM_OK;
}

Spatial locality means traversing adjacent elements. Temporal locality means reusing a value before eviction. Blocking tries to make both compatible with limited fast memory. BM and BN control how many outputs share each input panel; BK controls reduction-panel length and transfer granularity. A larger BK consumes capacity that could otherwise hold a wider output tile, without necessarily increasing reuse between outputs.

A capacity inequality is necessary but insufficient on cached CPUs: set conflicts, cache-line behavior, TLB reach and other live data reduce useful capacity. On a scratchpad it becomes an explicit allocation constraint, with stacks and runtime data reserved separately. Alignment can improve vector loads or DMA, but padding adds bytes that must be counted.

For a 7-by-11 output with K=5, BM=4, BN=6 and BK=3, every axis has a partial tile. Reading a nominal full tile beyond its allocation is invalid even if extra products are discarded. Implement clipped bounds or padded copies with valid storage. Tests include these cases, oversized block parameters and padded leading dimensions.

Blocking adds control overhead and tuning choices. Tiny matrices may fit already; skinny matrices offer limited reuse in one direction. The example explains a transformation rather than asserting optimal CPU performance. Arithmetic remains proportional to MNK and auxiliary workspace remains constant because this version does not allocate separate tile buffers.

Row-major B traversal

Loop order changes the memory stride On the left, i-j-k traverses one B column in its inner loop, with a stride of ldb elements. On the right, i-k-j traverses one B row, with a stride of one element. This assumes row-major storage and no transpose. i-j-ki-k-jstride = ldbstride = 1

Compatible tiles

One tiled update of C An A tile of BM by BK and a B tile of BK by BN update a C tile of BM by BN. Input tiles are reused across operations updating this output tile; BK is the tile reduction dimension. ABC×→BM×BKBK×BNBM×BNRepeat over the K tiles

Logical BLIS-like hierarchy

From macro tile to register tile The macro-kernel updates an mc by nc C tile. It consumes packed A and B panels with depth kc. The micro-kernel accumulates an mr by nr output tile in registers. This logical hierarchy does not automatically assign each block to a particular physical memory. Macro-kernelC: m_c × n_cPacked A and B panelsm_c×k_c ; k_c×n_cMicro-kernel · C registersm_r × n_r
Loop order changes accesses without changing the mathematical operation. Blocking bounds the working set; packing changes data layout, and the micro-kernel holds a small output tile in registers. Tile sizes and physical placement depend on the architecture.

Algorithm 4: packing operands for the consumer

Packing copies a strided panel into a layout selected for its microkernel. One possible A format stores an MR-element column slice for each k; one possible B format stores an NR-element row slice per k. The consumer then reads compact sequences rather than repeatedly handling arbitrary source strides. These are example formats; packer and consumer must agree exactly.

Regular loads, known alignment and simpler address arithmetic can improve the inner loop. Packing may incorporate transposition or padding. Padded elements need the correct neutral representation: for an affine quantized value, real zero may require the zero-point integer rather than a zero bit pattern.

Copying E elements of size s has a simple explicit-copy estimate of 2sE bytes, one read plus one write across the source/destination interfaces. This is not necessarily DRAM traffic: those interfaces may be at different hierarchy levels. The compute kernel subsequently reads the packed panel too. Count both implementations at the same boundary before claiming a traffic reduction.

Amortization determines whether packing helps. A B panel consumed by many A panels can repay its copy repeatedly. For a single tiny matrix, allocation and copying may dominate. Prepacking constant weights moves cost outside repeated inference calls but consumes persistent memory and requires invalidation when weights or the packing format change.

State alignment requirements for successive panel strides as well as the first address. Padding K to a lane-width multiple can increase executed arithmetic unless the tail is suppressed. Report useful operations separately from padded operations. Packing adds workspace proportional to the selected panels and an extra pass over their contents; it is an optimization with a break-even point, not a mandatory step for every GEMM.

Algorithm 5: a BLIS-like macro-kernel and microkernel

BLIS separates reusable organization from architecture-specific kernels R3. Its documented GEMM microkernel consumes packed operands and updates a small output tile R4. The following educational arrangement is not a transcription of either BLIS or the GAP8 implementation.

Architecture-independent pseudocode. Operands are conceptually FP32 and row-major before packing, dimensions M/N/K, with clipped edge sizes. Packing workspace is proportional to MC*KC + KC*NC; the register tile is MR*NR. Buffers do not overlap.

if M == 0 or N == 0: return
if alpha == 0 or K == 0:
    scale_C_by_beta(); return
for jc in blocks(N, NC):
    for pc in blocks(K, KC):
        Bp = pack_B(B[pc, jc], actual_KC, actual_NC)
        for ic in blocks(M, MC):
            Ap = pack_A(A[ic, pc], actual_MC, actual_KC)
            for jr in blocks(actual_NC, NR):
                for ir in blocks(actual_MC, MR):
                    beta_panel = beta if pc == 0 else 1
                    microkernel(actual_MR, actual_NR, actual_KC,
                                alpha, Ap[ir], Bp[jr], beta_panel,
                                C[ic + ir, jc + jr], ldc)

At microkernel level, initialize MR-by-NR accumulators, stream the packed inputs over KC and add outer-product contributions into registers. After the reduction, combine with C using alpha/beta and store. Independent accumulators expose instruction-level parallelism and avoid writing every partial sum to memory.

MR and NR depend on register capacity and instruction layout. More accumulators can hide latency, but excess pressure spills values, defeating reuse. Input registers, pointers and loop state consume resources too. The best register tile is not simply the largest accumulator array that seems to fit.

The macro-kernel chooses which packed panel is reused at each level. Most organization can remain portable while a specialized microkernel handles register layout and scheduling. The GAP8 research adapts BLIS-like principles to integer arithmetic and explicit memory movement R1; it does not imply an ordinary CPU BLIS binary runs unchanged on GAP8.

At revision 53f8bc6187470a435c501fbfb6ef58267c431b75, gemm_blis_B3C2A0 packs B in external memory, stages a B micro-panel through L2 into FC TCDM, keeps a C block in L2 and consumes an A micro-tile in packed registers R2. This placement differs from the educational C-register-resident pseudocode above; the paper’s comparison paragraphs also vary the variant names, so placement is the safer description. The checked-in S_CHART configuration stores C through signed char types, so wider-accumulator teaching examples must not be attributed to that source.

Packing, macro scheduling and instruction tuning solve different problems. Accelerating the inner kernel can expose a packing bottleneck. Enlarging panels can reduce packing frequency while exhausting local memory. Measure the components and the complete operation before deciding where another transformation belongs.

Memory hierarchy and GAP8 architecture

Registers hold immediately active operands and accumulators. A cache-based CPU automatically fills and evicts data-cache lines; software influences that behavior through access patterns. A scratchpad exposes storage that software allocates and populates. Both have latency, bandwidth and capacity limits, but different correctness obligations: hardware handles a missing cache line, whereas consuming a scratchpad tile before transfer completion reads stale or unavailable data.

A cache-friendly loop nest is therefore incomplete for a scratchpad target: placement, transfers, synchronization and lifetime rules are also needed. Conversely, copying every tile manually on a cached system can add traffic without improving reuse. Identify the constrained interface rather than treating either management policy as universally superior.

The official GAP8 manual distinguishes the Fabric Controller from the eight-core compute cluster, including their local-memory contexts. The cluster has banked shared L1 storage, L2 is a larger on-chip level, and DMA supports explicit movement R6. Shared-bank contention can serialize accesses even when data fits. GAP8 has instruction caches; describing its software-managed data memory does not mean the chip has no caches of any kind.

Published 2022 target: FC

Fabric Controller and data memories The GAP8 Fabric Controller is a core separate from the compute cluster. It can access its private L1 TCDM and shared L2 memory. The 2022 work implements and evaluates GEMM on the FC. Connections indicate access, not automatic cache transfers. Fabric Controller1 RISC-V coreload/store accessPrivate L1FC TCDMShared L2data memoryThe FC is not the cluster

Cluster: architectural context

GAP8 cluster and DMA The cluster's eight RISC-V cores access a shared banked L1 TCDM. The cluster DMA moves data between that L1 and shared L2. This L1 differs from the FC's private L1. The diagram does not attribute this path to the published FC experiment. Compute cluster8 RISC-V coresShared, banked L1 TCDMDMA: L1 ↔ L2Shared L2
Simplified GAP8 data paths based on the hardware reference manual. Sizes, peripherals and instruction caches are omitted; the diagram does not imply that GAP8 has no instruction caches. The data memories shown are explicitly managed. FC and cluster have distinct L1 memories; the 2022 evaluation targeted the FC.

The 2022 implementation targets the FC, not eight concurrently executing cluster cores R1, §3. Cluster capacity and aggregate throughput cannot be assigned to that experiment. The diagram is structural, not an allocation map of the published kernel. Similarly, the chip’s low-power positioning does not establish that every transformation saves energy.

External memory creates another boundary where the board configuration includes it. Its bandwidth cannot substitute for L2-to-local bandwidth. Reproducibility requires board/memory specification, FC/cluster placement, and locations of code, operands and packed buffers. A processor name alone leaves essential conditions unspecified.

Budgeting tiles and auxiliary storage

For one locally resident output tile and one input-buffer set, let s_acc be accumulator size. Let W_pack count only packing storage additional to the input buffers:

W1=sABMBK+sBBKBN+saccBMBN+Wpack+Waux.W_1=s_A B_M B_K+s_B B_K B_N+s_{\mathrm{acc}}B_M B_N+W_{\mathrm{pack}}+W_{\mathrm{aux}}.

Reserve stacks, descriptors, alignment gaps and runtime data in W_aux. If input buffers are already packed, count them once rather than charging another identical packing allocation. If stored C and its accumulator have different representations, count any separately resident input/output buffer as well.

Double-buffering both inputs gives:

W2=2sABMBK+2sBBKBN+saccBMBN+Wpack+Waux.W_2=2s_A B_M B_K+2s_B B_K B_N+s_{\mathrm{acc}}B_M B_N+W_{\mathrm{pack}}+W_{\mathrm{aux}}.

Fit the relevant budget into available, not nominal, local memory. These models assume one accumulator tile and no double-buffered output. A smaller tile forced by W2 can lose enough reuse to offset overlap. Buffer scheduling and tile selection must therefore be designed together.

Algorithm 6: SIMD and packed dot products

SIMD processes multiple lanes per operation. A packed dot product multiplies corresponding lanes and reduces them into an accumulator. Benefit depends on feeding lanes, hiding dependency latency and preserving signedness and range semantics. Packing INT8 values into a word is a layout action; selecting the intended instruction is a separate toolchain question.

Multiple independent accumulators can interleave dependency chains. Unrolling reduces branch overhead but increases register and code pressure. Unaligned inputs, short K tails and conversion instructions can erode the gain. Tail handling must avoid out-of-allocation reads, even if an allocation ends at an inaccessible page.

GAP8’s packed arithmetic is documented by the vendor R6, but the paper describes SDK simulation of dot operations in its evaluated setup R1. The official SDK also contains target builtin and scalar-emulation routes for gap8_dotp4 R10. Neither a helper name nor a vector C type proves which route a historical binary executed. Keep compiler/ISA flags and hot-loop disassembly to support a later native-instruction claim.

The FP32 examples depend on the host compiler, request no GAP8 intrinsics and establish no integer SIMD speedup. Their role is to validate semantics and transformations before introducing architecture-specific selection. The wider-accumulator INT8 teaching code is a correctness example; it must not be mistaken for the historical repository’s accumulator layout.

Algorithm 7: DMA-aware GEMM

Conceptual optimization. Consider one resident output tile, INT8 A/B tiles and an INT32 accumulator with a proven safe range. DMA transfers from slower memory into local buffers; compute consumes only completed transfers. This is architecture-independent pseudocode, not verified GAP8 SDK code:

initialize output accumulator using the declared beta semantics
for p in inner_dimension_tiles:
    shape = clipped_shape(p, M, N, K, BM, BN, BK)
    a_event = dma_load_A(A, local_A, shape)
    b_event = dma_load_B(B, local_B, shape)
    wait(a_event); wait(b_event)
    make_completed_writes_visible_to_compute()
    accumulate_tile(local_A, local_B, accumulator, shape)
apply declared scaling / conversion; store output tile
wait for output store before reusing its source storage

Initialization and final conversion must match the actual integer contract. Arbitrary real alpha/beta are not automatically supported by an INT8 kernel. A floating-point extension instead loads/scales C with floating-point accumulators. The tile arithmetic remains proportional to BMBNBK; transfer and synchronization costs are additional.

DMA may impose alignment, granularity and stride constraints. A strided tile needs a two-dimensional descriptor or multiple row transfers. A useful first transfer model is:

Ttransfer≈ndescτ+QBeffective.T_{\mathrm{transfer}}\approx n_{\mathrm{desc}}\tau+\frac{Q}{B_{\mathrm{effective}}}.

n_desc counts descriptors, tau effective setup/launch cost, and Q transferred bytes. These are parameters to measure. Large tiles amortize setup but consume capacity. Two input transfers can share one engine or bus, so their times are not necessarily independent.

This single-buffer schedule serializes load and compute. It is a useful baseline with clear ownership. Packing remains a separate phase: if the compute core performs it, merely calling it part of transfer does not make it overlap arithmetic. Output completion likewise matters before reuse or timing termination.

Algorithm 8: double buffering with explicit ownership

Architectural extension, not a verified result of the 2022 study. Allocate two input-buffer sets. DMA populates one while computation consumes the other, provided independent resources permit overlap. This hypothetical schedule handles zero, one, odd and partial tile counts. It assumes reliable completion/visibility events, INT8 inputs, safe INT32 accumulation and one resident output tile.

initialize_output_accumulator_using_declared_beta_semantics()
if tile_count == 0:
    finalize_and_store_output()
    wait_for_output_store()
    return

for b in {0, 1}: state[b] = FREE
event[0] = launch_both_inputs(tile=0, buffer=0, clipped_shape(0))
state[0] = LOADING

for t in 0 .. tile_count-1:
    cur = t mod 2
    nxt = 1 - cur
    wait_all(event[cur])
    make_completed_writes_visible_to_compute()
    state[cur] = READY

    if t + 1 < tile_count:
        assert state[nxt] == FREE
        event[nxt] = launch_both_inputs(t + 1, nxt, clipped_shape(t + 1))
        state[nxt] = LOADING

    state[cur] = COMPUTING
    accumulate_tile(buffer[cur], accumulator, clipped_shape(t))
    wait_for_any_async_compute_reads_to_finish()
    state[cur] = FREE

finalize_and_store_output()
wait_for_output_store()

The first load precedes computation. Reuse occurs only after the previous consumer finishes. Every iteration waits for both inputs and launches a next transfer only if one exists; the final iteration cannot access an out-of-range tile. Odd counts require no special unsafe prefetch rule: parity only selects a buffer.

If a worker or accelerator consumes asynchronously, its completion determines when a buffer becomes free, not the issuing core’s return. The explicit compute wait covers that case. Implement visibility, fences and event lifetimes according to the real runtime; the abstract API is not an SDK recipe. C remains owned by compute until its final store completes. These rules prevent DMA from overwriting inputs while they are still in use.

One input-buffer set

Serialized transfers and computation DMA loads tile zero into buffer set A, then computation consumes it. Only after computation finishes can tile one be loaded into the same set A. DMA and computation do not overlap in this one-buffer schedule. DMACPUD0:AC0:AD1:AC1:Aschematic timeDMA and CPU alternate ownership

Two buffer sets: A and B

Double-buffer startup, overlap and drain At startup DMA loads tile zero into A. In steady state computation processes zero in A while DMA loads one into B, then processes one in B while DMA loads two into A. During drain only tile two in A remains to compute. DMA never writes the buffer actively owned by computation. The example terminates with three tiles, an odd count. DMACPUD0:AD1:BD2:AC0:AC1:BC2:AstartupsteadydrainWait → consume → reuse
Conceptual schedule, not a measurement or a claim about the 2022 implementation. Dn loads input data for tile n; Cn consumes it. A and B name buffer sets, not the GEMM matrices. Computation waits for transfer completion before reading; DMA waits for release before overwriting. Widths are schematic and output writeback is omitted. Overlap requires actual DMA/compute independence.

For L uniform tiles, transfer time D and compute time G, a single-buffer input schedule takes L(D+G). Independent resources and negligible synchronization give:

Tdouble≈D+(L−1)max⁡(D,G)+G.T_{\mathrm{double}}\approx D+(L-1)\max(D,G)+G.

Startup D and final compute G have no neighboring phase to hide them. The steady-state interval approaches:

Ttile≈max⁡(Tcompute,Ttransfer).T_{\mathrm{tile}}\approx\max(T_{\mathrm{compute}},T_{\mathrm{transfer}}).

This optimistic model excludes output movement, nonuniform edges, packing and synchronization. DMA and arithmetic can contend for banks, increasing D and G during overlap. One tile offers no inter-tile overlap, small transfers may be launch-bound, and the extra buffers can force worse blocking. Double buffering helps only if hidden latency exceeds these additional costs.

Parallel GEMM: partition outputs before reductions

Conceptual multicore extension. Assign disjoint C tiles to workers. Each performs its full K reduction, applies beta once and owns its stores. This avoids concurrent output writes and cross-core reductions. A shared B panel can serve several workers if its lifetime is protected until every consumer finishes.

Splitting K gives several partial outputs for the same C tile. It requires private accumulators or synchronized updates and a final reduction. That adds storage, communication and a changed floating-point reduction order. Atomic scalar updates can erase parallel gains. K partitioning can help very small M/N problems, but is not a free transformation.

Static distribution suits similarly sized tiles. Edges and variable transfer times create imbalance; a dynamic queue improves balancing at the cost of scheduling. Shared-bank conflicts or a saturated DMA path can make more workers slower. Scaling efficiency must compare the same workload and algorithm on one and p workers, rather than a scalar reference against a different optimized algorithm.

GAP8’s eight-core cluster is an architectural capability. Demonstrating a cluster implementation requires evidence of worker launch, partitioning, synchronization and measured scaling; it cannot be inferred from the FC experiment.

Performance Modeling and Analysis

Metrics and fair comparisons

Execution time measures a declared scope: kernel only, packing plus kernel, or the whole inference operation. Throughput divides useful arithmetic by time. Use FLOP/s for FP32 and integer operations/s for INT8 with explicit MAC conventions. Kernel throughput and end-to-end latency answer different questions.

For identical workloads and correctness requirements:

S=TbaselineToptimized,Ep=T1pTp.S=\frac{T_{\mathrm{baseline}}}{T_{\mathrm{optimized}}},\qquad E_p=\frac{T_1}{pT_p}.

E_p denotes parallel efficiency. T1 and Tp need comparable scopes; changed precision, omitted packing or different beta values can invalidate the interpretation. Effective bandwidth is transferred bytes divided by time for a specified boundary, not automatically the vendor’s bus maximum.

Record whether operands are already packed, whether C is initialized and whether transfers are queued or synchronous. A baseline compiled under different floating-point rules is not a controlled comparison. Reusing a packed panel across many invocations is a valid workload only if that reuse belongs to the application being described.

Deriving tile operational intensity

Operational intensity divides useful operations by bytes across a chosen interface. For floating point it is also called arithmetic intensity:

I=FQ.I=\frac{F}{Q}.

Consider a hypothetical L2-to-local-buffer boundary. One BM-by-BN output tile remains local across the entire K reduction. Input sizes are sA and sB; local accumulators use sacc, but transferred C uses sC. Let K panels have lengths bk_p summing to K. Assume each required input panel crosses once for this output tile, beta requires one C read, and there is one final C write:

Qtile=∑p(sABMbk,p+sBbk,pBN)+2sCBMBN.Q_{\mathrm{tile}}=\sum_p\left(s_A B_M b_{k,p}+s_B b_{k,p}B_N\right)+2s_C B_M B_N.

Ignoring padding and M/N edges gives:

Itile≈2BMBNKsABMK+sBKBN+2sCBMBN.I_{\mathrm{tile}}\approx\frac{2B_M B_N K}{s_A B_M K+s_B K B_N+2s_C B_M B_N}.

For one BK panel including a partial-C read/write, substitute BK for K. If a schedule spills C after every panel, charge that cost for every panel; if it keeps C, do not invent intermediate transfers. Output residency can matter more than a small arithmetic improvement.

An illustrative FP32 calculation, BM=BN=BK=32 and sA=sB=sC=4, gives 65536 conventional operations and 16384 bytes, or 4 FLOP/byte. Keeping that output tile resident over K=256 gives approximately 7.11 FLOP/byte in this model. These are derived examples, not GAP8 measurements.

For INT8 inputs with INT32 transferred partial/output values, substitute sA=sB=1 and sC=4 and use integer operations. A local accumulator can occupy four bytes even when the final quantized output uses one; use the correct size at each boundary. Omitting that width exaggerates available tile capacity.

Beta zero may remove an explicit initial transfer, while a write-allocating cache may still fetch a line on a store miss. Padding, repeated panels, packing and refills change Q. Distinguish a footprint estimate from measured traffic, and state whether bytes come from DMA descriptors, hardware counters or a model. Identify counter events rather than reporting an unexplained bandwidth number.

Roofline: ceilings and the ridge point

Roofline relates arithmetic capacity to data supply R9. Let Ppeak be a compute ceiling in useful operations/s, Bmemory sustainable bandwidth in bytes/s and I intensity in operations/byte:

P≤min⁡(Ppeak,BmemoryI).P\leq\min\left(P_{\mathrm{peak}},B_{\mathrm{memory}} I\right).

Bmemory*I has units of operations/s. On logarithmic axes it forms a sloped bandwidth ceiling; the compute ceiling is horizontal. Their intersection is the ridge point:

I∗=PpeakBmemory.I^*=\frac{P_{\mathrm{peak}}}{B_{\mathrm{memory}}}.

Below that intensity, even an ideal kernel cannot feed peak arithmetic through the modeled interface. Above it, increasing reuse alone cannot raise this roof. The distinction identifies a limiting modeled resource; it does not prove a slow measured point has reached either ceiling.

Illustrative normalized Roofline

Roofline bound without hardware measurements Both axes are logarithmic and normalized. The horizontal axis is intensity I divided by ridge intensity I star; the vertical axis is performance P divided by peak P peak. The rising dashed bandwidth limit meets the horizontal compute ceiling at coordinates one, one. Ridge intensity is I star equals P peak divided by B. There are no measured points or GAP8 values. P / P_peak I / I* 1½¼ ¼½124 P/P_peak = 1I / I* I* = P_peak / B
Derived illustrative model: P/Ppeak ≤ min(1, I/I*). It contains no experimental results or GAP8 numbers. Both axes are logarithmic. The dashed line is the bandwidth limit and the horizontal line the compute ceiling; their intersection is (1, 1) by normalization. B and Ppeak require consistent operation units and an explicit memory boundary.

The diagram is normalized and illustrative, with no measured GAP8 bandwidth or throughput. A kernel may lie below both roofs because of instruction dependencies, address generation, poor lane utilization, synchronization, bank conflicts or short-problem overhead. Moving right through packing is not automatically beneficial when packing time or traffic has been excluded from the plotted point.

A theoretical peak comes from an instruction-rate/clock model. A measured compute ceiling comes from a documented calibration kernel. Sustainable bandwidth must match access pattern and direction: a long sequential copy may not predict short two-dimensional DMA transfers. Combining a theoretical bus maximum with measured kernel rates creates an optimistic bound, not a measured attainable roof.

Hierarchical Roofline analysis gives each interface its own traffic count and bandwidth: registers/local memory, local/L2 and external memory where present. A kernel can have high intensity at one boundary and still be limited at another:

P≤min⁡(Pcompute,B1I1,B2I2,…).P\leq\min\left(P_{\mathrm{compute}},B_1 I_1,B_2 I_2,\ldots\right).

Each pair must use the same boundary and operation convention. Additional ceilings can describe instruction mix, issue width and imperfect lane occupancy. Treat them as hypotheses until grounded in verified architectural behavior or measurements.

Adapting Roofline to GAP8

Select FC or cluster first. Specify the integer kernel, SDK and generated instructions. If a dot helper expands in software, native packed-dot issue rate is not the executed kernel’s compute ceiling. Calibrate what actually runs.

For a DMA proposal, measure local/L2 transfers with the same shapes, alignment, descriptor count and concurrent activity. Count completed descriptors plus other traffic at that boundary. Compare isolated and overlapping transfers to reveal contention. This educational package supplies no verified device calibration, so new numerical GAP8 roofs and speedup plots remain pending.

Communication costs and break-even reasoning

A simple serial model is:

Tserial≈Tpack+Ttransfer+Tcompute+Tsync.T_{\mathrm{serial}}\approx T_{\mathrm{pack}}+T_{\mathrm{transfer}}+T_{\mathrm{compute}}+T_{\mathrm{sync}}.

With independent transfer/compute resources, a pipeline replaces repeated sums by their maximum, plus startup/drain and synchronization. That substitution fails when one core executes both phases or shared resources serialize them. Include packing explicitly unless its overlap is demonstrated.

Suppose one-time packing costs Tp and saves deltaT per panel reuse. With R uses, the elementary break-even condition is:

R ΔT>Tp.R\,\Delta T>T_p.

DeltaT must include changed computation and movement. A wider panel can reduce repeated transfers while increasing packing and capacity pressure. Communication-avoiding transformations retain or fuse useful intermediates; they can also increase live storage and scheduling complexity. Optimize the measured cost of the complete required operation, not an isolated count that omits the new work.

Energy and power require measurements

Power is energy per unit time. Over a measured interval:

E=∫t0t1P(t) dt,eop=EF.E=\int_{t_0}^{t_1}P(t)\,dt,\qquad e_{\mathrm{op}}=\frac{E}{F}.

With identical interval/counting scope, throughput divided by average power equals operations per joule. Shorter execution can reduce energy while increasing instantaneous power; lower frequency can reduce power while extending runtime. Neither trend alone establishes efficiency.

Application energy should include required data movement and idle waits. State whether instrumentation covers a chip rail, board or system, and whether idle energy is subtracted. No numerical energy savings, power traces or energy-per-operation measurements are supplied here.

Reproducible benchmark methodology

The downloadable package includes a host benchmark example with a monotonic POSIX timer, warmup, repeated measurements, correctness checks and statistical summaries. It is not a GAP8 timer implementation. All compared kernels use identical M/N/K, FP32 row-major storage and alpha=1, beta=0. Allocation and input initialization are outside the timed region; whole kernel work, including C initialization/scaling, is inside it.

/* POSIX host harness excerpt: setup/reference/checks occur outside timing. */
static double measure_kernel(int algorithm, size_t m, size_t n, size_t k,
                              const float *a, const float *b, float *c) {
    double start = seconds();
    int status = invoke(algorithm, m, n, k, a, b, c);
    double elapsed = seconds() - start;
    if (status != GEMM_OK) exit(EXIT_FAILURE);
    return elapsed;
}

This compiled excerpt is shared with both translations. The complete harness supplies initialization, argument validation, reference comparisons and reporting. Run bash run_checks.sh before timing. Its Linux/WSL output describes the host only and must never be relabeled as GAP8 results.

Item Required record
Hardware Board/processor, memory, FC or cluster, active cores, clock and power policy
Toolchain Compiler/SDK versions, exact flags, source revision, instruction evidence
Workload M/N/K, alpha/beta, precision, input ranges, layout, strides and tile sizes
Scope Allocation, packing, transfers, synchronization and conversion included/excluded
Timing Timer resolution/overhead, warmup, repetitions and completion synchronization
Results Raw samples, median/minimum/spread, correctness tolerance and reference

Warmup must match the question. A warm-cache microkernel test studies reuse; a cold-start inference test includes first-use work. Record state management instead of presenting either regime as universally representative. Rotate or randomize algorithm order when thermal or background effects could bias a fixed sequence. Frequency scaling and throttling can change elapsed-time rates despite identical source.

Time completed work: enclosing only a DMA launch measures submission, not transfer. A monotonic clock avoids wall-clock adjustments, but short kernels can still approach timer overhead/resolution. Batch enough equivalent work to exceed that cost and state whether repeated calls reuse packed operands or cached data. Keep raw samples rather than subtracting a noisy overhead estimate from every timing.

Repeated beta=1 calls grow C and can eventually overflow. Reset outside timing with that scope declared, or include reset cost consistently. Preserve observable output validation to prevent dead-code elimination; making all arrays volatile changes the memory behavior being studied. Check generated code when whole-program optimization or aggressive constant propagation could undermine a microbenchmark.

Correctness coverage should include small/nonsquare matrices, edge tiles, padded strides, zeros, alpha/beta variants and deterministic random inputs. Compare FP32 against an independent wider-accumulator reference, with tolerances appropriate to K and input range. The included tolerance is for bounded teaching cases, not a universal numerical guarantee. Check exact integer results when representable and test overflow boundaries before conversion.

Publish configuration and raw samples with any claimed rate. A minimum can approximate favorable machine conditions, while a median and spread characterize typical behavior in that run. Neither is universally the right summary. Separate kernel improvements from end-to-end application gains. New GAP8 execution, cycle/instruction validation and energy experiments remain pending access to the corresponding platform.

References and retained source material

  1. Cristian Ramírez et al. A BLIS-like matrix multiplication for machine learning in the RISC-V ISA-based GAP8 processor. The Journal of Supercomputing, 2022. DOI: 10.1007/s11227-022-04581-6. Implementation/FC scope: §§3–4; future work: §5.
  2. crissmath/qblis_gpduino, inspected revision 53f8bc6187470a435c501fbfb6ef58267c431b75. README relates the source to R1; source availability is not proof of historical artifact identity.
  3. Field G. Van Zee and Robert A. van de Geijn. BLIS: A Framework for Rapidly Instantiating BLAS Functionality. ACM Transactions on Mathematical Software, 2015.
  4. BLIS maintainers. Kernel documentation and multithreading documentation.
  5. Reference BLAS. DGEMM specification and source.
  6. GreenWaves Technologies. GAP8 Hardware Reference Manual, v1.5.5. FC/cluster, memory, DMA and instruction-set documentation.
  7. Google. LiteRT 8-bit quantization specification. A framework example, not an assertion about the research’s complete pipeline.
  8. LLVM project. Clang Compiler User’s Manual: floating-point behavior.
  9. Samuel Williams, Andrew Waterman and David Patterson. Roofline: An Insightful Visual Performance Model for Floating-Point Programs and Multicore Architectures. Technical report UCB/EECS-2008-134, 2008.
  10. GreenWaves Technologies. GAP SDK Gap8.h, target builtin and host-emulation paths. This revision does not establish the 2022 SDK version.

The research poster (PDF) and original attribution are preserved. The earlier article’s reference to Alman and Williams (2020) remains as asymptotic context beyond classical multiplication, not an algorithm implemented here. All new diagrams are explanatory originals. View the Research Project for the publications and engineering evidence.