Skip to content

Vectorize and parallelize the bf16/fp16 gemm fallback for all layouts - #203265

Draft
Kanya-Mo wants to merge 3 commits into
pytorch:mainfrom
Kanya-Mo:aten-xf16-gemm-kernels
Draft

Kanya-Mo wants to merge 3 commits into
pytorch:mainfrom
Kanya-Mo:aten-xf16-gemm-kernels

Conversation

@Kanya-Mo

@Kanya-Mo Kanya-Mo commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

The PR aims at improving performance of reduced precision gemm on old CPU platforms reported in #146508. When oneDNN does not handle a bf16/fp16 matmul on CPU, cpublas::gemm falls back to the kernels in BlasKernel.cpp. Only one of the four transpose layouts there had a vectorized, parallel kernel gemm_transa_. This PR modify the routing and does a few improvements.

  1. Routes the other three layouts to this kernel by repacking operands that it cannot read directly and leaves small problem to the naive loop.
  2. Write a generaic overload templated for the three gemm_transa_ functions
  3. In the kernel body, split the longer side of c across threads with grain size (if n >= m, split columns). Previously, splitting rows of c (column major) when m is small would cause threads writing interleaved bytes of the same cache lines.

The performance data is measured on GNR Xeon 6960P emulating old CPUs.

CPU (emulated) workload dtype main -> PR
AVX2 Linear bwd, grad_input = dY @ W (256x4096 @ 4096x4096) bf16 36,344 ms -> 35.2 ms (1034x)
AVX2 Linear bwd, grad_input = dY @ W (256x4096 @ 4096x4096) fp16 35,799 ms -> 35.3 ms (1015x)
AVX2 Linear bwd, grad_weight = dY.t() @ X (4096x256 @ 256x4096) bf16 694 ms -> 42.0 ms (17x)
AVX2 Linear bwd, grad_weight = dY.t() @ X (4096x256 @ 256x4096) fp16 2,582 ms -> 44.1 ms (59x)
AVX2 Attention P @ V, one head (512x512 @ 512x64) bf16 9.61 ms -> 0.18 ms (55x)
AVX2 Decode x @ W (1x4096 @ 4096x4096) bf16 140.8 ms -> 3.8 ms (37x)
AVX-512 (no AVX512-FP16) Linear bwd, grad_input = dY @ W (256x4096 @ 4096x4096) fp16 35,896 ms -> 35.6 ms (1009x)
AVX-512 (no AVX512-FP16) Linear bwd, grad_weight = dY.t() @ X (4096x256 @ 256x4096) fp16 2,632 ms -> 44.3 ms (59x)
AVX-512 (no AVX512-FP16) Attention P @ V, one head (512x512 @ 512x64) fp16 11.05 ms -> 0.18 ms (63x)
AVX-512 (no AVX512-FP16) Decode x @ W (1x4096 @ 4096x4096) fp16 139.2 ms -> 4.0 ms (35x)

cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01

@pytorch-bot

pytorch-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/203265

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 9952853 with merge base 6bf26fa (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added module: cpu CPU specific problem (e.g., perf, algorithm) release notes: linalg_frontend release notes category labels Nov 3, 2026

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

I think this will overlap with work in #203181, so you might need to remeasure benchmarks when that lands first.

Also, this doesn't enable parallelism for large k and small m, n. The existing code doesn't either, but it's something you could consider.

Comment thread test/test_linalg.py
@@ -8891,6 +9621,27 @@ def test():
check_correctness(torch.dot, torch.bfloat16, a, b)
check_correctness(torch.dot, torch.half, a, b)

@onlyCPU
@dtypes(torch.bfloat16, torch.half)
def test_addmm_reduced_precision_without_mkldnn(self, device, dtype):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This name matches #203181 and will conflict.

// it cannot read directly and use it for every layout. Leave tiny problems to naive loop.
if (m * n * k > 16 * 16 * 16) {
std::unique_ptr<scalar_t[]> a_packed, b_packed;
if (transa == TransposeType::NoTranspose) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This copies all of A on every call. For large n the copy is cheap, but for n==1 or other small n the work would be limited by memory bandwidth, so the copy would be expensive. Could you skip the repack for small n and use a vectorized kernel that sweeps A column by column?

You could test this with n=1, 4, 16, 64 for non-transposed A.

Comment thread aten/src/ATen/native/cpu/BlasKernel.cpp Resolved
@egeboy35

Copy link
Copy Markdown
Contributor

@Kanya-Mo I tested this PR on the same laptop as well, but this time with MKL disabled so fp16 actually uses the new BlasKernel.cpp paths.

Most layouts show substantial speedups. However, I was able to reproduce the small-n slowdown @frost-intel was concerned about, along with another regression on the same layout.

Here are the numbers:

Drafted by Claude (AI) for @egeboy35.

Numbers from real hardware in the AVX-512-without-FP16 class: i7-11800H (Tiger Lake: AVX-512 F/BW/VL/DQ/VNNI, no AVX512_FP16, no AVX512_BF16, no AMX), WSL2, GCC 15.2. oneDNN declines fp16 matmul on this CPU, so fp16 torch.mm reaches the BlasKernel.cpp fallback without any ISA capping; bf16 was run under torch.backends.mkldnn.flags(enabled=False). Two builds of main 30c5b5d with oneDNN on and no MKL, the second with BlasKernel.cpp from this PR's head (9952853); only libtorch_cpu.so differs between runs. 1 thread pinned to one core and 7 threads on 7 physical cores, median of 3 interleaved runs.

Correctness: test/test_linalg.py -k "without_mkldnn or ((addmm or addmv or matmul or bmm) and (float16 or bfloat16) and cpu)" with this PR's test file: 90 passed with both libraries. The max relative error against an fp32 reference was identical with both libraries in every benchmark case but one (fp16 512x512 @ 512x512: 2.820e-4 on main, 2.823e-4 with the PR).

Most layouts get much faster, for example in fp16:

case (torch.mm) main -> PR, 1 thread main -> PR, 7 threads
grad_input dY@W, 64x1024 @ 1024x1024 264.7 -> 12.4 ms (21.3x) 244.1 -> 4.2 ms (57.6x)
512x512 @ 512x512, both operands transposed views 193.7 -> 26.1 ms (7.4x) 174.5 -> 8.1 ms (21.5x)
attention P@V, 512x512 @ 512x64 18.6 -> 3.2 ms (5.8x) 20.7 -> 1.1 ms (19.0x)
decode x@W, 1x4096 @ 4096x4096 197.6 -> 37.9 ms (5.2x) 190.3 -> 13.8 ms (13.8x)

There are two slowdowns, both on the (transa=N, transb=T) layout. Main serves it with gemm_transb_, one pass over A that accumulates into an fp32 copy of C; this PR repacks A with pack_k_contiguous first, which transposes all of A on every call:

case (torch.mm) cpublas call dtype main -> PR, 1 thread main -> PR, 7 threads
A.t() @ v, A 2048x2048, v 2048x1 gemm(N, T, m=2048, n=1, k=2048) bf16 0.50 -> 5.09 ms (0.10x) 0.76 -> 1.67 ms (0.45x)
same same fp16 3.91 -> 5.34 ms (0.73x) 4.24 -> 1.73 ms (2.44x)
grad_weight dY.t() @ X, dY 64x1024, X 64x1024 gemm(N, T, m=1024, n=1024, k=64) bf16 12.95 -> 33.57 ms (0.39x) 14.88 -> 9.22 ms (1.61x)
same same fp16 54.47 -> 30.76 ms (1.77x) 61.02 -> 9.25 ms (6.60x)

The first row is the small-n case @frost-intel raised in review: at n=1 the call with the repack takes about ten times as long as main's whole bf16 gemm. The k=64 row is the other end, short dot products, where main's single-threaded bf16 loop still wins at one thread. On main the fp16 instantiation of that loop is 4x to 8x slower than the bf16 one (3.91 vs 0.50 ms, 54.5 vs 13.0 ms), so keeping gemm_transb_ for these shapes, parallelized and with an explicitly vectorized fp16 conversion, might keep the bf16 numbers and speed up fp16 as well.

This build has no MKL. I measured #203181 separately on an MKL 2024.2.0 build (the version CI uses), and there #203181 sends almost all of these layouts to MKL before they reach BlasKernel.cpp: with this PR applied on top of #203181, none of the cases above changed measurably at one thread (the numbers are in my comment on #203181). So what this PR changes is mainly visible in builds without #203181's MKL path. I can rerun the same set on this machine for your next revision, and add shapes from the #146508 reports if you point me to the ones you care about.

All cases (median of 3 runs)

A.t()=1 means the first operand is a transposed view of a contiguous tensor, B.t()=1 the same for the second.

dtype case (torch.mm) 1 thread, main -> PR (ms) speedup 7 threads, main -> PR (ms) speedup
fp16 linear_fwd [email protected]() 128x4096x4096 477.86 -> 360.22 1.33x 112.73 -> 94.93 1.19x
fp16 decode [email protected]() 1x4096x4096 4.12 -> 3.78 1.09x 1.17 -> 1.11 1.05x
fp16 decode x@W 1x4096x4096 197.58 -> 37.91 5.21x 190.28 -> 13.80 13.79x
fp16 grad_input dY@W 64x1024x1024 264.66 -> 12.42 21.30x 244.14 -> 4.24 57.63x
fp16 grad_weight dY.t() @ X 1024x1024x64 54.47 -> 30.76 1.77x 61.02 -> 9.25 6.60x
fp16 attn P@V 512x64x512 18.62 -> 3.24 5.75x 20.72 -> 1.09 19.02x
fp16 mm 512x512x512 NN 190.04 -> 24.92 7.63x 205.22 -> 7.94 25.84x
fp16 mm 512x512x512 TT 193.74 -> 26.07 7.43x 174.47 -> 8.12 21.49x
fp16 m=k=2048, n=1, A.t()=0, B.t()=0 5.10 -> 0.75 6.80x 5.52 -> 0.26 20.91x
fp16 m=k=2048, n=1, A.t()=1, B.t()=0 3.91 -> 5.34 0.73x 4.24 -> 1.73 2.44x
fp16 m=k=2048, n=1, A.t()=1, B.t()=1 18.04 -> 5.13 3.52x 20.58 -> 1.64 12.53x
fp16 m=k=2048, n=2, A.t()=0, B.t()=0 11.41 -> 1.45 7.86x 10.80 -> 0.51 21.32x
fp16 m=k=2048, n=2, A.t()=1, B.t()=0 12.38 -> 6.12 2.02x 12.36 -> 1.94 6.37x
fp16 m=k=2048, n=2, A.t()=1, B.t()=1 39.44 -> 5.86 6.73x 32.88 -> 1.94 16.95x
fp16 m=k=2048, n=4, A.t()=0, B.t()=0 20.76 -> 3.09 6.72x 19.81 -> 0.76 25.93x
fp16 m=k=2048, n=4, A.t()=1, B.t()=0 18.10 -> 7.55 2.40x 15.21 -> 2.43 6.25x
fp16 m=k=2048, n=4, A.t()=1, B.t()=1 68.27 -> 7.43 9.18x 66.29 -> 2.38 27.87x
fp16 m=k=2048, n=8, A.t()=0, B.t()=0 45.96 -> 6.23 7.37x 43.74 -> 2.00 21.84x
fp16 m=k=2048, n=8, A.t()=1, B.t()=0 28.72 -> 11.17 2.57x 28.07 -> 3.45 8.14x
fp16 m=k=2048, n=8, A.t()=1, B.t()=1 153.23 -> 10.40 14.74x 129.99 -> 3.73 34.81x
fp16 m=k=2048, n=16, A.t()=0, B.t()=0 90.27 -> 11.25 8.02x 81.46 -> 3.67 22.20x
fp16 m=k=2048, n=16, A.t()=1, B.t()=0 53.40 -> 17.94 2.98x 54.85 -> 4.52 12.14x
fp16 m=k=2048, n=16, A.t()=1, B.t()=1 311.61 -> 17.67 17.63x 280.48 -> 5.37 52.19x
fp16 m=k=2048, n=32, A.t()=0, B.t()=0 182.09 -> 23.67 7.69x 167.41 -> 7.49 22.34x
fp16 m=k=2048, n=32, A.t()=1, B.t()=0 103.41 -> 29.48 3.51x 104.67 -> 8.56 12.23x
fp16 m=k=2048, n=32, A.t()=1, B.t()=1 597.74 -> 31.45 19.01x 569.81 -> 8.81 64.65x
bf16 linear_fwd [email protected]() 128x4096x4096 366.53 -> 385.03 0.95x 92.35 -> 92.05 1.00x
bf16 decode [email protected]() 1x4096x4096 3.57 -> 3.78 0.94x 1.10 -> 1.10 1.00x
bf16 decode x@W 1x4096x4096 188.55 -> 39.70 4.75x 201.05 -> 13.83 14.54x
bf16 grad_input dY@W 64x1024x1024 221.24 -> 13.53 16.36x 252.78 -> 3.99 63.31x
bf16 grad_weight dY.t() @ X 1024x1024x64 12.95 -> 33.57 0.39x 14.88 -> 9.22 1.61x
bf16 attn P@V 512x64x512 17.61 -> 3.07 5.73x 18.38 -> 1.09 16.90x
bf16 mm 512x512x512 NN 187.82 -> 25.96 7.24x 166.68 -> 8.29 20.10x
bf16 mm 512x512x512 TT 155.34 -> 27.52 5.64x 161.81 -> 8.16 19.84x
bf16 m=k=2048, n=1, A.t()=0, B.t()=0 3.31 -> 0.69 4.79x 4.17 -> 0.24 17.12x
bf16 m=k=2048, n=1, A.t()=1, B.t()=0 0.50 -> 5.09 0.10x 0.75 -> 1.67 0.45x
bf16 m=k=2048, n=1, A.t()=1, B.t()=1 16.69 -> 5.64 2.96x 17.53 -> 1.19 14.70x
bf16 m=k=2048, n=2, A.t()=0, B.t()=0 6.54 -> 1.57 4.16x 9.02 -> 0.50 18.03x
bf16 m=k=2048, n=2, A.t()=1, B.t()=0 17.41 -> 7.06 2.46x 17.51 -> 1.95 8.98x
bf16 m=k=2048, n=2, A.t()=1, B.t()=1 30.85 -> 7.14 4.32x 34.36 -> 1.94 17.67x
bf16 m=k=2048, n=4, A.t()=0, B.t()=0 14.56 -> 3.29 4.43x 14.46 -> 1.03 14.10x
bf16 m=k=2048, n=4, A.t()=1, B.t()=0 12.74 -> 7.76 1.64x 13.69 -> 2.74 4.99x
bf16 m=k=2048, n=4, A.t()=1, B.t()=1 63.20 -> 8.25 7.66x 86.47 -> 2.27 38.06x
bf16 m=k=2048, n=8, A.t()=0, B.t()=0 29.47 -> 6.11 4.82x 30.36 -> 1.93 15.73x
bf16 m=k=2048, n=8, A.t()=1, B.t()=0 17.22 -> 11.05 1.56x 16.99 -> 3.21 5.30x
bf16 m=k=2048, n=8, A.t()=1, B.t()=1 144.10 -> 12.10 11.91x 136.98 -> 3.33 41.15x
bf16 m=k=2048, n=16, A.t()=0, B.t()=0 79.12 -> 12.44 6.36x 64.23 -> 3.41 18.84x
bf16 m=k=2048, n=16, A.t()=1, B.t()=0 23.33 -> 17.09 1.37x 16.73 -> 5.28 3.17x
bf16 m=k=2048, n=16, A.t()=1, B.t()=1 323.92 -> 17.19 18.84x 299.45 -> 5.06 59.16x
bf16 m=k=2048, n=32, A.t()=0, B.t()=0 151.31 -> 23.59 6.41x 150.15 -> 5.75 26.11x
bf16 m=k=2048, n=32, A.t()=1, B.t()=0 27.20 -> 30.54 0.89x 26.87 -> 7.81 3.44x
bf16 m=k=2048, n=32, A.t()=1, B.t()=1 617.07 -> 28.42 21.71x 539.50 -> 8.82 61.19x
Benchmark script

Run once per library and thread count: taskset -c 2 python gemm_bench.py out.jsonl <tag> 1 and taskset -c 0,2,4,6,8,10,12 python gemm_bench.py out.jsonl <tag> 7.

import json
import sys
import time

import torch

out, tag, threads = sys.argv[1], sys.argv[2], int(sys.argv[3])
torch.set_num_threads(threads)
torch.manual_seed(0)


def operands(m, n, k, ta, tb, dtype):
    a = torch.randn(k, m).t() if ta else torch.randn(m, k)
    b = torch.randn(n, k).t() if tb else torch.randn(k, n)
    return a.to(dtype), b.to(dtype)


# (name, m, n, k, a transposed view, b transposed view)
CASES = [
    ("linear_fwd [email protected]() 128x4096x4096", 128, 4096, 4096, False, True),
    ("decode [email protected]() 1x4096x4096", 1, 4096, 4096, False, True),
    ("decode x@W 1x4096x4096", 1, 4096, 4096, False, False),
    ("grad_input dY@W 64x1024x1024", 64, 1024, 1024, False, False),
    ("grad_weight dY.t()@X 1024x1024x64", 1024, 1024, 64, True, False),
    ("attn P@V 512x64x512", 512, 64, 512, False, False),
    ("mm 512x512x512 NN", 512, 512, 512, False, False),
    ("mm 512x512x512 TT", 512, 512, 512, True, True),
]
for n in (1, 2, 4, 8, 16, 32):
    for ta, tb in ((False, False), (True, False), (True, True)):
        CASES.append((f"small_n m=k=2048 n={n} ta={int(ta)} tb={int(tb)}", 2048, n, 2048, ta, tb))


def bench(fn, budget=1.5, max_iters=50):
    fn()
    t0 = time.perf_counter()
    fn()
    once = time.perf_counter() - t0
    iters = max(3, min(max_iters, int(budget / max(once, 1e-6))))
    times = []
    for _ in range(iters):
        t0 = time.perf_counter()
        fn()
        times.append(time.perf_counter() - t0)
    times.sort()
    return times[len(times) // 2], iters


with open(out, "a") as f:
    for dtype in (torch.float16, torch.bfloat16):
        for name, m, n, k, ta, tb in CASES:
            a, b = operands(m, n, k, ta, tb, dtype)
            with torch.backends.mkldnn.flags(enabled=dtype != torch.bfloat16):
                med, iters = bench(lambda: torch.mm(a, b))
                ref = (a.float() @ b.float())
                err = ((torch.mm(a, b).float() - ref).abs().max() / ref.abs().max().clamp_min(1e-6)).item()
            rec = dict(tag=tag, threads=threads, dtype=str(dtype)[6:], case=name, ms=med * 1e3, iters=iters, rel_err=err)
            f.write(json.dumps(rec) + "\n")
            f.flush()
print("done", tag, threads)

This branch has not been deployed

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

Labels

module: cpu CPU specific problem (e.g., perf, algorithm) open source release notes: linalg_frontend release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants