Epilogue Fusion Configuration (EFC)#

Epilogue Fusion Configuration (EFC) fuses post-GEMM work into the epilogue of a persistent, warp-specialized dense GEMM written in CuTe DSL. The epilogue is a plain Python function: it reads the accumulator and any number of extra tensors and scalars, computes with the usual arithmetic operators and a set of built-in activations, and writes, broadcasts into or reduces into any number of output tensors. EFC analyses that function once to learn how each argument is used, generates its device code inside the kernel, and can evaluate the same function with PyTorch to produce a reference result.

EFC is reachable in two ways:

  • Through the CUTLASS Operator API. Pass an ordinary Python function to EpilogueArguments; operator discovery then picks a GEMM operator that fuses it. The function has no EFC-specific parameter, and the Operator API lowers it onto EFC. See the tutorial Custom epilogue fusions for GEMMs and the arguments reference.

  • Directly from CuTe DSL. Write an EFC epilogue function, whose first parameter is efc_config, and instantiate the EFC dense GEMM operation yourself. This exposes the whole EFC surface, mode remapping, explicit data transports and accumulator splitting, together with the kernel’s design parameters. This guide covers that path.

Installation#

The EFC framework and its dense GEMM operations form the cutlass.kernels.efc package of the nvidia-cutlass-operators wheel, which contributes to the cutlass namespace next to nvidia-cutlass-dsl:

pip install nvidia-cutlass-dsl nvidia-cutlass-operators

One subpackage per architecture provides the operations:

Subpackage

Dense operation

Block-scaled (MXFP8) operation

cutlass.kernels.efc.dense_gemm.sm100 (Blackwell)

DenseGemmEFC

DenseGemmEFCBlockScaled

cutlass.kernels.efc.dense_gemm.sm107 (Rubin)

DenseGemmEFCSm107

DenseGemmEFCBlockScaledSm107

The block-scaled operations take fp8 A and B with E8M0 scale factors as extra mainloop inputs, passed right after A and B; the epilogue sees the dequantized accumulator, so everything below applies to them unchanged.

Writing an Epilogue Function#

An EFC epilogue is a Python function whose first parameter is named efc_config. Every other parameter is a supplemental argument: a tensor the epilogue reads or writes, or a scalar. The parameter names identify the arguments throughout compilation and execution, and the arguments are later passed to compile and to the compiled kernel in the same order.

def epilogue(efc_config, C, D, alpha, beta, X, x_factor, Y):
    # Store the accumulator A x B as is to Y.
    Y.store(efc_config.accum())
    # D = relu(acc * alpha + C * beta) + X * x_factor
    result = (
        efc_config.relu(efc_config.accum() * alpha + C.load() * beta)
        + X.load() * x_factor
    )
    D.store(result)

Inside the function:

  • efc_config.accum() is the accumulator tile, the result of A x B.

  • tensor.load() reads a supplemental tensor and tensor.store(value) writes one. Whether a tensor is an input, an output or both follows from these calls; nothing is declared up front.

  • Scalars, Python numbers or cutlass.Numeric values, are used as they are.

  • The operators +, -, * and / act element-wise, and efc_config provides the built-in activations identity, relu, leaky_relu(x, slope), tanh, sigmoid, silu, hardswish and gelu.

The function is invoked several times with different implementations of efc_config: at compile time to discover how each parameter is used, while the device code of the kernel is generated, and optionally on CPU tensors to compute a PyTorch reference. It therefore has to be pure: no side effects and no branching on element values. An epilogue that writes nothing, through neither store nor reduce, is rejected.

Wiring the Epilogue into a GEMM#

The operation takes the MMA settings of the kernel and the epilogue function, and compiles against the actual tensors:

import cutlass
from cutlass.kernels.efc.dense_gemm.sm100 import DenseGemmEFC

cluster_shape_mn = (2, 1)
gemm = DenseGemmEFC(
    acc_dtype=cutlass.Float32,
    epi_dtype=cutlass.Float32,
    use_2cta_instrs=True,
    mma_tiler_mn=(128, 128),
    cluster_shape_mn=cluster_shape_mn,
    epilogue_function_configuration=epilogue,
)

# Raises ValueError when the tensors do not fit this configuration.
gemm.check_implementable(a_tensor, b_tensor, d_tensor)

max_active_clusters = cutlass.utils.HardwareInfo().get_max_active_clusters(
    cluster_shape_mn[0] * cluster_shape_mn[1]
)

# The supplemental arguments follow the order of the epilogue parameters.
compiled_gemm = gemm.compile(
    a_tensor, b_tensor, max_active_clusters, stream,
    c_tensor, d_tensor, alpha, beta, x_tensor, x_factor, y_tensor,
    options="--opt-level=3",
)
compiled_gemm(
    a_tensor, b_tensor, stream,
    c_tensor, d_tensor, alpha, beta, x_tensor, x_factor, y_tensor,
)

compile runs the parameter analysis of the epilogue and then cute.compile, to which it forwards the options string; the result is called with the same arguments minus max_active_clusters. epi_dtype is the type the epilogue computes in; each written tensor converts to its own type on store.

A is (M, K, L), B is (N, K, L) and the supplemental tensors are (M, N, L) unless remapped as described below, with L the batch mode; they share the output’s major mode and their contiguous mode is 16-byte aligned. They are ordinary cute.Tensor objects, for instance built from PyTorch tensors with cute.runtime.from_dlpack (see Integration with Frameworks) or, as the examples do, with cutlass.torch.cute_tensor_like(t, dtype, is_dynamic_layout=True, assumed_align=16). A 0-d tensor keeps a static layout (is_dynamic_layout=False). stream is a cuda.CUstream.

The same epilogue evaluates on CPU with PyTorch, which gives a reference to compare the kernel’s outputs against:

gemm.evaluate_on_cpu(
    a_torch, b_torch, epi_dtype,
    c_torch, d_torch, alpha, beta, x_torch, x_factor, y_torch,
)

Broadcasting and Transposing with remap_modes#

A supplemental tensor need not be (M, N, L). tensor.remap_modes[...] gives, for each mode of the output, the mode of the source tensor that supplies it: an integer selects a source mode and : broadcasts along that output mode.

def epilogue(efc_config, C, D, alpha, beta, X, x_factor, Y):
    # Y is (N, M, L), transposed relative to the output: read-modify-write.
    Y.remap_modes[1, 0, 2].store(
        efc_config.accum() + Y.remap_modes[1, 0, 2].load()
    )
    # C is (N, L): broadcast along M.  X is (M, L): broadcast along N.
    # x_factor is a 0-d tensor: broadcast to the whole output.
    result = (
        efc_config.relu(
            efc_config.accum() * alpha
            + C.remap_modes[:, 0, 1].load() * beta
        )
        + X.remap_modes[0, :, 1].load()
        * x_factor.remap_modes[:, :, :].load()
    )
    D.store(result)

The subscript has one entry per output mode and at most as many integers as the source has modes, so a size-1 source mode can be left out. The same remap_modes[...] view may be both loaded and stored, and repeating the subscript returns the same view. An all-: subscript on a 0-d tensor passes the value to the kernel as a scalar.

Reductions#

reduce(value, op=...) on a remapped view folds value along the : modes of the subscript and combines the result into the destination with atomic operations. An all-: subscript yields a single element; keeping one mode yields a vector with one entry per kept index.

def epilogue(efc_config, D, sum_sq, col_sum):
    acc = efc_config.accum()
    D.store(acc)
    # sum_sq += sum(acc * acc) over the whole output.
    sum_sq.remap_modes[:, :, :].reduce(acc * acc, op=efc_config.ADD)
    # col_sum[n] += sum over m and l of acc[m, n, l].
    col_sum.remap_modes[:, 0, :].reduce(acc, op=efc_config.ADD)

efc_config.ADD, MAX and MIN are the supported operators, aliases of the cute.ReductionOp members. The destination has a 32-bit type, and the kernel combines on top of its existing content rather than clearing it: the caller fills it with the operator’s identity for a fresh reduction, or leaves a running total in place to accumulate across launches.

Gated Activations on a Single GEMM#

A gated linear unit (SwiGLU, GeGLU, ReGLU) multiplies an up projection by the activation of a gate projection. With the two projections interleaved along N in B, column 2j being the gate and column 2j + 1 the up projection of output column j, one GEMM computes both and the epilogue pairs them:

def swiglu_epilogue(efc_config, D):
    D.store(efc_config.swiglu())

def scaled_swiglu_epilogue(efc_config, D, alpha):
    gate, up = efc_config.accum_split(2)
    D.store(up * efc_config.silu(gate) * alpha)

efc_config.accum_split(n) returns n parts, part i holding the accumulator columns whose index is i modulo n; a tensor written from a part is n times narrower along N than the GEMM. swiglu(), geglu(), reglu() and gated(name), for any built-in activation, are the two-way shorthands for up * activation(gate). A part combines with another part or with a scalar, not with a loaded full-width tensor.

Per-Tensor Data Transport#

By default each supplemental tensor moves between global memory and the kernel through TMA, staged in shared memory. TMA imposes alignment, vector width and layout constraints that some tensors cannot meet, so load and store accept via= to pick another path per tensor:

Transport member

Direction

Path

TMA (default)

read and write

TMA bulk-tensor copy through shared memory

SYNC_GMEM_LOAD

read

per-thread copy from global memory straight into registers

SYNC_GMEM_STORE

write

per-thread copy from registers straight to global memory

ASYNC_GMEM_LOAD

read

per-thread cp.async copy through shared memory

from cutlass.kernels.efc import Transport

def epilogue(efc_config, bias, D):
    v = efc_config.accum() + bias.load(via=Transport.SYNC_GMEM_LOAD)
    D.store(v, via=Transport.SYNC_GMEM_STORE)

The members are also reachable as efc_config.SYNC_GMEM_LOAD and so on. An optional num_bits_per_copy= sets the width of each copy; by default the widest width the fragment’s alignment allows is used, up to 256 bits. A tensor uses the same via on every access.

Constraints#

  • A and B share a type among Float16, BFloat16, TFloat32, Int8, Uint8, Float8E4M3FN and Float8E5M2. Float32 accumulates any of the floating-point types, Float16 accumulates Float16 and the fp8 types, and Int32 accumulates the integer types.

  • The MMA tiler M is 64 or 128 with one-CTA instructions and 128 or 256 with two-CTA instructions (use_2cta_instrs); the tiler N is a multiple of 32 up to 256; the cluster shape has power-of-two sides, at most 16 CTAs, and an even M side with two-CTA instructions. The block-scaled operations use the block-scaled instruction’s M and a tiler N of 64, 128, 192 or 256.

  • check_implementable reports a configuration the tensors cannot use before any compilation.

Debugging#

Setting CUTE_DSL_EFC_LOG_LEVEL to INFO or DEBUG logs the parameter analysis, the tensor layouts and the shared-memory budget of every step:

CUTE_DSL_EFC_LOG_LEVEL=DEBUG python custom_epilogue_dense_gemm.py --mnkl 256,256,512,1

Examples and Further Reading#

The efc/ directory of the Blackwell CuTe DSL examples holds complete programs, each with a CPU reference check:

The framework’s design notes, DESIGN.md, describe the three-phase execution model, the warp-specialized pipeline the epilogue plugs into, and the device mechanisms behind remap_modes, reduce and accum_split.