Skip to content

Add new fallback for reduced precision gemm - #203181

Open
Kanya-Mo wants to merge 11 commits into
pytorch:mainfrom
Kanya-Mo:mkl-xf16-gemm-fallback
Open

Kanya-Mo wants to merge 11 commits into
pytorch:mainfrom
Kanya-Mo:mkl-xf16-gemm-fallback

Conversation

@Kanya-Mo

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

Copy link
Copy Markdown
Contributor

This is one of the efforts alleviating the performance issue of reduced precision gemm on old CPU platforms reported in #146508. The PR adds a new fallback mkl_xf16_gemm. When oneDNN declines a bf16/fp16 gemm, it now calls MKL's cblas_gemm_{bf16bf16,f16f16}f32, writing into an fp32 temporary buffer that is then rounded back. Previously, these calls went to ATen's reference kernel.

Attached is performance data measure on Emerald Rapids Xeon Platinum 8570 (emulating old CPUs)

CPU (emulated) workload dtype 1 thread: main -> PR 25 threads: main -> PR
AVX-512 (no FP16) TransformerEncoderLayer fwd, d=1024, FFN 4096, 4x128 tokens fp16 716 -> 71.1 ms (10.1x) 108 -> 12 ms (9.0x)
AVX-512 (no FP16) mm 1024x1024 @ 1024x1024 fp16 1,588 -> 10.6 ms (150.2x) 1,572 -> 3.28 ms (478.8x)
AVX-512 (no FP16) linear W 11008x4096, batch 512 fp16 2,274 -> 283 ms (8.0x) 173 -> 33.6 ms (5.1x)
AVX-512 (no FP16) linear W 4096x4096, batch 128 fp16 210 -> 27.1 ms (7.7x) 16.1 -> 16.2 ms (0.99x)
AVX2 TransformerEncoderLayer fwd, d=1024, FFN 4096, 4x128 tokens bf16 704 -> 122 ms (5.8x) 99.7 -> 15.9 ms (6.3x)
AVX2 mm 1024x1024 @ 1024x1024 bf16 1,710 -> 18.5 ms (92.6x) 1,639 -> 4.69 ms (349.4x)
AVX2 linear W 11008x4096, batch 512 bf16 2,267 -> 469 ms (4.8x) 173 -> 47 ms (3.7x)
AVX2 linear W 4096x4096, batch 128 bf16 209 -> 43.4 ms (4.8x) 16.1 -> 16.1 ms (1.00x)
AVX2 linear W 4096x4096, batch 8 fp16 13.1 -> 13.1 ms (1.00x) 1.03 -> 1.04 ms (0.99x)

The env options used to emulate older CPUs

Emulated CPU class ONEDNN_MAX_CPU_ISA MKL_ENABLE_INSTRUCTIONS ATEN_CPU_CAPABILITY affected GEMM dtype
AVX-512 without FP16/BF16 AVX512_CORE AVX512 avx512 oneDNN declines fp16, bf16 is still taken by oneDNN
AVX2 AVX2 AVX2 avx2 oneDNN declines both bf16 and fp16

@pytorch-bot pytorch-bot Bot added the release notes: linalg_frontend release notes category label Nov 3, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

PR Status: in progress

Please address review feedback on your PR either with a code/PR description change. If a review comment is irrelevant, react with 👎 on that specific comment to reject it, and leave a short reply explaining why. The change must pass any running CI and existing failures must be classified as unrelated (see status below in this comment).

Passing automated review does not guarantee that this PR will be merged. It still requires maintainer review and may be closed if its design or direction does not align with the project.

To minimize iteration time, feel free to run the pr-review skill from the repo locally. To trigger a fresh automated review, make a new push or comment @pytorchbot review. To bypass automated review, please add the "no automated review" label.

🟡 AUTOMATED REVIEW - Changes requested:

The PR adds `mkl_xf16_gemm`: when oneDNN declines a bf16/fp16 gemm, the call
goes to MKL's `cblas_gemm_{bf16bf16,f16f16}f32` through an fp32 copy of C
instead of to ATen's reference kernel. Recommendation: Request Changes. One
point blocks: the new code is guarded only by `MKL_HAS_*`, so builds where MKL's
libraries are found but its headers are not hit an assertion crash on ordinary
bf16/fp16 mm. Everything else is non-blocking.

Findings (11):

[major] aten/src/ATen/native/CPUBlas.cpp:128
Blocking: lines 128, 465 and 531 are guarded only by `MKL_HAS_SBGEMM` /
`MKL_HAS_SHGEMM`, not `AT_MKL_ENABLED()`. `cmake/Modules/FindMKL.cmake:421-431`
calls `add_compile_definitions(MKL_HAS_SBGEMM/SHGEMM)` once
`check_function_exists` links against `MKL_LIBRARIES`. The header search comes
later (:446). If it fails, :492 sets `MKL_FOUND FALSE` but the definitions stay,
e.g. when the MKL runtime is installed without `mkl-include`/`mkl-devel`. In
that build `AT_MKL_ENABLED() == 0`, so
`mkl_gemm_bf16bf16f32`/`mkl_gemm_f16f16f32` are the stubs in
`mkl/LinearAlgebra.cpp:42-56` that call `TORCH_INTERNAL_ASSERT(false, ...)`.
Every non-tiny bf16/fp16 `mm`/`linear` that oneDNN declines, or that runs with
mkldnn disabled, then aborts. Before this PR it ran the ATen kernel. The
existing bf16/fp16fp32 overloads (:572-577, :608-613) have the same guard, but
this PR puts it on the ordinary mm path. Fix: use `#if AT_MKL_ENABLED() &&
defined(MKL_HAS_SBGEMM)` (and the SHGEMM equivalent) at all three sites, or move
the `add_compile_definitions` under `MKL_FOUND`.

[minor] aten/src/ATen/native/CPUBlas.cpp:155
Non-blocking: the new comment at :155-158 is inaccurate in three places. (1)
"transb == T with n == 1 is a contiguous vector" holds only when `ldb == 1`.
`addmm_impl_cpu_` can produce `(N, T, n=1)` with `ldb = stride[0]` for a column
slice, and `(N, N, n=1)` is also contiguous, so contiguity doesn't tell the two
cases apart. (2) The `A.t() @​ v` example only reaches this gemm for a 2-D `(k,
1)` `v`; a 1-D `v` goes through `mv`  gemv. (3) "as slow as MKL on one thread"
contradicts the author's own `(N, N, 4096, 1, 4096)` numbers: 159.6  172.1 ms.

[minor] aten/src/ATen/native/CPUBlas.cpp:129
Non-blocking: the header comment at :129-133 still omits the `!use_blas_gemm`
decline, which is left over from the earlier finding.

[minor] test/test_linalg.py:9141
Non-blocking: `test_lower_precision_accumulation_with_ref_path`
(`test/test_linalg.py:505-531`) no longer tests the kernel it was written for.
It disables mkldnn to check fp32 accumulation in ATen's reference kernel (#
95125, # 83863) on 300x300 bf16/fp16 matmul for all transpose combinations. On
MKL builds those shapes now go to MKL (mnk far above 4096, n = 300 is not
skinny, alpha = 1), and only its tiny bmm case still reaches ATen. It still
passes, but it no longer guards ATen's
`gemm_notrans_`/`gemm_transa_`/`gemm_transb_`/`gemm_transab_`. Either force ATen
for that test or note the coverage change.

[minor] test/test_linalg.py:9142
Non-blocking, carried over (test unchanged): there is no `alpha == 0` case with
inf or NaN inputs; `ldc == m` in every case; nothing shows MKL actually ran; the
`m*k > 1024*1024` branch is never hit; and the `beta == 0` case uses finite `c`,
so a NaN in C leaking through would not be caught (`_test_addmm_impl` uses a
NaN-filled input for this).

[minor] aten/src/ATen/native/CPUBlas.cpp:466
Non-blocking, carried over: bf16/fp16 results change for users on the
oneDNN-declined or mkldnn-disabled path. They are no longer bitwise equal to
earlier releases, they can now depend on thread count and MKL settings
(`MKL_ENABLE_INSTRUCTIONS`, `MKL_CBWR`), and there is no switch back to the ATen
reference kernel. The `release notes: linalg_frontend` entry should say so.

(5 more not shown, see the review run)

Reviewed commit: 5ac27ca

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

⚠️ 4 Awaiting Approval

As of commit 5ac27ca with merge base efbc870 (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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

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

Can you document exactly what env options were specified to emulate AVX512 and AVX2?

Comment thread aten/src/ATen/native/CPUBlas.cpp Outdated
// below a column count that grows with the thread count and the size of A.
// The threshold is measured on AVX2 and AVX-512 without AMX
const int64_t threads = at::in_parallel_region() ? 1 : at::get_num_threads();
const double min_cols_transa = std::max(24.0, 5.0 * threads * std::sqrt(static_cast<double>(m) * k) / 4096);

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.

Where does this heuristic come from? Was it tuned on just one machine? Or is there some reasoning you could provide in a comment?

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.

Simplified the model with more detailed comments on how it was fitted. Also, the threshold is set by keeping ATen in more cases to prevent regressions on old platforms.

Comment thread aten/src/ATen/native/CPUBlas.cpp Resolved
Comment thread aten/src/ATen/native/CPUBlas.cpp Resolved
@Kanya-Mo
Kanya-Mo requested a review from frost-intel November 20, 2026 00:42
@egeboy35

egeboy35 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

@Kanya-Mo I tested your PR on my laptop with an MKL build after @frost-intel raised the question of whether the heuristic had only been tuned on one machine.

The correctness checks passed, and the larger speedups hold up on my CPU as well. However, the column threshold behaves quite differently here, and I found one bf16 case that regressed.

I've included the numbers below.

Drafted by Claude (AI) for @egeboy35.

Measurements of this PR's head (612d8ef) on a second machine, mostly for @frost-intel's question about where the heuristic comes from. i7-11800H (Tiger Lake, 8 cores: AVX-512 F/BW/VL/DQ/VNNI, no AVX512_BF16, no AVX512_FP16, no AMX), WSL2, GCC 15.2, MKL 2024.2.0 static (the version in .ci/docker/requirements-ci.txt), so both MKL_HAS_SBGEMM and MKL_HAS_SHGEMM are defined. Two builds of the main this PR is based on (efbc870), the second with this PR's CPUBlas.cpp; only libtorch_cpu.so differs between runs. oneDNN declines fp16 matmul on this CPU, so fp16 reaches the fallback without ISA capping; bf16 was run under torch.backends.mkldnn.flags(enabled=False). Threads pinned one per physical core with taskset, median of 3 interleaved runs unless noted.

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: 104 passed with both libraries. I also compared torch.addmm against main on 704 cases: both dtypes, all four transpose layouts, 11 shapes on both sides of the size and column thresholds (including n=1, m=1 and k=1), alpha/beta of (1, 0), (0.5, 2), (0, 1) and (1, 1), inf and NaN in A, NaN in self with beta=0, and out= into a column slice of a wider tensor (ldc > m) with a sentinel in the other columns. NaN/inf positions matched main in every case, the sentinel was never overwritten, and the max relative error against an fp64 reference was the same as main's (4.4e-4 fp16, 3.4e-3 bf16).

The workloads from the PR description, fp16 (bf16 with oneDNN off gives the same picture within about 5%):

workload 1 thread 4 threads 7 threads
TransformerEncoderLayer forward, d=1024, ffn=4096, 4x128 tokens 702.1 -> 118.0 ms (5.95x) 330.1 -> 57.2 ms (5.77x) 299.2 -> 79.7 ms (3.76x)
mm 1024x1024 @ 1024x1024 1825 -> 17.4 ms (105x) 1807 -> 8.1 ms (222x) 1848 -> 9.4 ms (197x)
F.linear, W 11008x4096, batch 512 2100 -> 430 ms (4.88x) 970 -> 191 ms (5.07x) 749 -> 286 ms (2.62x)
F.linear, W 4096x4096, batch 128 193.2 -> 43.7 ms (4.43x) 89.0 -> 27.8 ms (3.20x) 73.1 -> 70.4 ms (1.04x)

With the PR, every row is slower at 7 threads than at 4; more on that below.

The skinny_transa threshold. I swept F.linear(x[batch, in], W[out, in]), which is gemm(T, N, m=out, n=batch, k=in), over batch 1 to 128 for three weight shapes, timing main's ATen kernel and MKL (this PR with skinny_transa forced off). The batch from which MKL is faster at every larger batch, against the PR's threshold:

W (out x in) threads PR threshold MKL faster from (fp16 / bf16) worst case for the PR's choice (fp16)
1024x1024 1 24 4 / 4 batch 20: ATen 1.99 ms, MKL 0.66 ms (3.0x)
4096x4096 1 30 8 / 8 batch 28: ATen 44.2 ms, MKL 18.1 ms (2.4x)
11008x4096 1 30 20 / 20 batch 28: ATen 117.7 ms, MKL 93.4 ms (1.3x)
1024x1024 4 24 8 / 8 batch 16: ATen 0.57 ms, MKL 0.28 ms (2.0x)
4096x4096 4 48 32 / 32 batch 40: ATen 25.1 ms, MKL 20.4 ms (1.2x)
11008x4096 4 48 40 / 32 batch 40: ATen 69.9 ms, MKL 55.2 ms (1.3x)
1024x1024 7 24 64 / 64 batch 32: MKL 1.97 ms, ATen 1.08 ms (1.8x)
4096x4096 7 66 128 / none up to 128 batch 96: MKL 92.8 ms, ATen 56.7 ms (1.6x)
11008x4096 7 66 none up to 128 batch 96: MKL 287.7 ms, ATen 143.7 ms (2.0x)

At one thread the threshold is conservative here: MKL already wins from batch 4 to 20, so below 24/30 the PR leaves up to 3x on the table. At 7 threads it goes the other way. The m*k <= 1M branch keeps 24 at every thread count, but ATen stays faster up to batch 48 for W 1024x1024, and for the larger weights ATen is faster well past 66.

The 7-thread rows come from how MKL's bf16/fp16 gemm scales on this CPU. Same F.linear, W 4096x4096, MKL forced, threads on distinct physical cores, one run per cell (median of 15 calls):

threads 1 2 3 4 5 6 7 8
bf16, batch 8 (ms) 15.0 10.6 23.0 17.9 45.4 17.9 71.0 26.7
bf16, batch 128 47.0 28.0 36.3 29.0 58.3 32.0 86.8 59.4
fp16, batch 8 12.9 11.4 20.2 15.7 54.9 18.8 82.7 33.3
fp16, batch 128 45.8 28.4 39.5 28.4 61.1 36.9 88.8 62.7
fp32 (MKL sgemm), batch 8 7.8 5.6 4.3 4.1 4.0 4.3 5.7 6.2
fp32 (MKL sgemm), batch 128 41.7 22.4 23.9 17.8 21.9 14.6 35.5 21.5

MKL_VERBOSE puts the time inside GEMM_BF16BF16F32 (63 to 106 ms per call with NThr:7 at batch 8), and fp32 sgemm on the same shape and cores doesn't show it, so it looks specific to MKL's bf16/fp16 kernels on a CPU without native bf16/fp16. Odd thread counts are the worst, and nothing improves past 2 threads. PyTorch calls mkl_set_dynamic(false), so MKL always uses all get_num_threads() threads for these calls. I have only run this under WSL2, not on bare-metal Linux. Since MKL's time here isn't monotone in the thread count, I don't think a formula in get_num_threads() can fit both ends on this machine. Do you see the odd-thread-count pattern on the Xeon 8570 too?

bf16 with n = 1. One layout got slower in the torch.mm case set I used for #203265:

torch.mm cpublas call (from MKL_VERBOSE) 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.29 -> 8.21 ms (0.04x) 0.35 -> 1.79 ms (0.19x)
same same fp16 1.70 -> 1.36 ms (1.25x) 2.06 -> 1.72 ms (1.20x)
x @ W, x 1x4096, W 4096x4096 gemm(N, N, m=4096, n=1, k=4096) bf16 143.4 -> 147.8 ms (0.97x) 143.2 -> 10.7 ms (13.4x)
same same fp16 144.0 -> 9.4 ms (15.3x) 143.4 -> 10.3 ms (13.9x)

MKL_VERBOSE at one thread: GEMM_BF16BF16F32(N,T,2048,1,2048) takes 10 to 11 ms where GEMM_F16F16F32 with the same arguments takes 1.5 ms, and (N,N,4096,1,4096) takes 131 to 201 ms in bf16 against 8.8 ms in fp16. With MKL_ENABLE_INSTRUCTIONS=AVX2 the bf16 times stay the same (9 to 11 ms and 134 to 139 ms). That could matter for AVX2-only CPUs: on x86, mkldnn_bf16_device_check() needs AVX-512 BW/VL/DQ or AVX-NE-CONVERT, so on those CPUs bf16 matmul lands in this fallback and, with this PR, in MKL. I've only emulated AVX2 through MKL's ISA cap, not measured on such a CPU. With n = 2 the same (N, T) call is already faster than main (9.4 -> 2.9 ms), so the loss is at n = 1 only.

Together with #203265. I also built this PR with #203265's BlasKernel.cpp on top. At one thread nothing changed measurably: across the 52 torch.mm cases in the details below, the ratio to this PR alone stayed between 0.88x and 1.12x, and in the F.linear sweep below the threshold (the cases this PR leaves on ATen) the times matched, for example W 4096x4096, batch 16: 26.01 vs 25.92 ms. The 7-thread runs moved by up to 40% in both directions, but so did cases that make the identical MKL call in both builds (512x512 @ 512x512 bf16: 0.57 vs 0.87 ms), so I read that as run-to-run noise at 7 threads. So on an MKL build, #203265's new code would only run for the shapes this PR leaves on ATen, and there it made no difference here; the gains I measured on #203265 apply where this PR's MKL path isn't compiled in.

I can rerun all of this on your next revision.

F.linear sweep: ATen ms / MKL ms, the PR's choice in bold (median of 3 runs)
dtype threads W PR threshold batch 1 batch 4 batch 8 batch 16 batch 24 batch 32 batch 48 batch 64 batch 96 batch 128
fp16 1 1024x1024 24 0.10 / 0.37 0.40 / 0.29 0.80 / 0.37 1.60 / 0.60 2.39 / 0.73 3.22 / 0.87 4.97 / 1.14 6.36 / 1.39 9.54 / 1.92 12.74 / 2.43
fp16 1 4096x4096 30 2.91 / 11.36 7.78 / 10.33 13.91 / 13.02 26.05 / 14.94 38.07 / 16.99 49.80 / 19.19 72.77 / 23.24 97.67 / 27.47 145.45 / 35.85 203.44 / 43.85
fp16 1 11008x4096 30 7.30 / 74.78 20.39 / 70.26 36.76 / 78.15 71.67 / 83.41 103.30 / 91.48 133.07 / 96.18 196.68 / 107.06 261.04 / 119.75 389.67 / 141.77 518.14 / 164.43
fp16 4 1024x1024 24 0.03 / 0.19 0.11 / 0.13 0.23 / 0.17 0.57 / 0.28 0.91 / 0.33 1.29 / 0.40 2.68 / 0.50 3.32 / 0.59 4.34 / 0.73 5.53 / 0.98
fp16 4 4096x4096 48 0.91 / 8.65 2.99 / 13.66 5.66 / 16.79 10.72 / 20.34 16.26 / 23.93 21.80 / 19.43 31.51 / 21.12 44.38 / 21.47 68.13 / 25.45 83.25 / 30.01
fp16 4 11008x4096 48 2.97 / 25.95 7.97 / 38.12 15.76 / 45.37 28.39 / 55.10 43.59 / 62.26 56.72 / 57.61 83.81 / 57.40 112.48 / 62.83 158.29 / 76.59 227.88 / 78.29
fp16 7 1024x1024 24 0.02 / 0.46 0.10 / 0.78 0.29 / 1.77 0.60 / 1.44 1.00 / 1.54 1.08 / 1.97 1.94 / 2.17 2.61 / 2.33 3.17 / 2.60 5.10 / 2.43
fp16 7 4096x4096 66 0.82 / 12.82 3.07 / 36.59 5.10 / 62.79 8.51 / 50.45 13.98 / 51.45 18.59 / 63.38 29.04 / 66.34 36.45 / 76.17 56.72 / 92.75 77.55 / 70.35
fp16 7 11008x4096 66 2.41 / 87.52 6.99 / 150.09 11.95 / 204.08 24.48 / 167.32 35.66 / 168.35 48.54 / 204.56 72.74 / 199.91 90.18 / 231.96 143.65 / 287.72 190.51 / 226.65
bf16 1 1024x1024 24 0.10 / 0.38 0.40 / 0.30 0.80 / 0.39 1.59 / 0.59 2.40 / 0.71 3.17 / 0.84 4.82 / 1.10 6.27 / 1.35 9.55 / 1.86 12.77 / 2.37
bf16 1 4096x4096 30 2.85 / 6.72 7.68 / 10.76 13.85 / 13.48 26.08 / 15.42 37.90 / 17.60 49.74 / 19.60 73.18 / 23.64 97.27 / 27.88 144.43 / 36.00 192.03 / 44.03
bf16 1 11008x4096 30 7.30 / 16.83 20.05 / 69.62 36.93 / 77.59 69.41 / 84.09 101.10 / 89.49 133.25 / 94.89 195.11 / 106.48 260.60 / 117.28 385.90 / 139.73 514.32 / 162.20
bf16 4 1024x1024 24 0.03 / 0.13 0.14 / 0.16 0.24 / 0.20 0.53 / 0.28 0.87 / 0.30 1.28 / 0.40 2.32 / 0.52 2.75 / 0.62 4.38 / 0.85 6.10 / 1.02
bf16 4 4096x4096 48 0.97 / 2.23 2.95 / 13.05 5.64 / 16.52 10.91 / 18.68 16.08 / 22.04 20.64 / 18.77 31.50 / 19.56 39.99 / 20.96 63.41 / 23.63 83.65 / 27.18
bf16 4 11008x4096 48 2.60 / 5.92 8.19 / 34.10 14.74 / 44.78 29.03 / 51.73 43.88 / 61.56 62.82 / 52.67 86.73 / 54.20 113.18 / 57.39 163.19 / 65.52 226.10 / 74.11
bf16 7 1024x1024 24 0.04 / 0.12 0.15 / 0.64 0.26 / 1.83 0.51 / 1.51 0.79 / 1.45 1.26 / 1.91 1.78 / 2.01 3.02 / 1.92 4.01 / 2.97 4.46 / 2.81
bf16 7 4096x4096 66 0.79 / 2.46 2.93 / 36.71 4.65 / 59.10 9.66 / 46.62 14.30 / 46.91 18.48 / 62.69 24.47 / 63.85 36.34 / 74.48 51.31 / 91.60 64.63 / 67.89
bf16 7 11008x4096 66 2.14 / 5.99 7.88 / 147.44 11.55 / 209.26 25.17 / 170.75 36.65 / 168.41 50.15 / 212.49 69.34 / 256.78 92.13 / 312.15 135.40 / 299.10 175.27 / 228.15
torch.mm case set from #203265, main vs this PR (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. The fp16 0.83x row is gemm(T, N, n=1), which this PR leaves on ATen, so it is noise between two runs of the same code.

dtype case (torch.mm) 1 thread, main -> PR (ms) speedup 7 threads, main -> PR (ms) speedup
fp16 linear_fwd [email protected]() 128x4096x4096 193.45 -> 43.67 4.43x 69.77 -> 71.34 0.98x
fp16 decode [email protected]() 1x4096x4096 2.90 -> 2.66 1.09x 0.73 -> 0.68 1.07x
fp16 decode x@W 1x4096x4096 144.02 -> 9.44 15.26x 143.40 -> 10.28 13.95x
fp16 grad_input dY@W 64x1024x1024 122.55 -> 1.18 104.13x 123.69 -> 1.79 69.13x
fp16 grad_weight dY.t() @ X 1024x1024x64 26.94 -> 1.77 15.25x 26.98 -> 0.55 48.84x
fp16 attn P@V 512x64x512 10.07 -> 0.30 33.19x 10.20 -> 0.09 111.25x
fp16 mm 512x512x512 NN 96.07 -> 2.28 42.21x 96.22 -> 0.68 142.41x
fp16 mm 512x512x512 TT 88.52 -> 2.31 38.38x 88.28 -> 0.70 125.25x
fp16 m=k=2048, n=1, A.t()=0, B.t()=0 2.45 -> 2.95 0.83x 3.03 -> 3.00 1.01x
fp16 m=k=2048, n=1, A.t()=1, B.t()=0 1.70 -> 1.36 1.25x 2.06 -> 1.72 1.20x
fp16 m=k=2048, n=1, A.t()=1, B.t()=1 8.33 -> 1.36 6.11x 8.27 -> 1.76 4.70x
fp16 m=k=2048, n=2, A.t()=0, B.t()=0 4.86 -> 2.05 2.37x 5.73 -> 0.57 10.10x
fp16 m=k=2048, n=2, A.t()=1, B.t()=0 6.59 -> 2.66 2.47x 7.14 -> 0.90 7.90x
fp16 m=k=2048, n=2, A.t()=1, B.t()=1 16.65 -> 2.52 6.60x 17.28 -> 0.85 20.22x
fp16 m=k=2048, n=4, A.t()=0, B.t()=0 9.65 -> 2.08 4.64x 9.84 -> 0.71 13.90x
fp16 m=k=2048, n=4, A.t()=1, B.t()=0 8.49 -> 2.56 3.32x 8.55 -> 0.90 9.51x
fp16 m=k=2048, n=4, A.t()=1, B.t()=1 33.22 -> 2.59 12.80x 32.13 -> 0.90 35.76x
fp16 m=k=2048, n=8, A.t()=0, B.t()=0 19.35 -> 2.06 9.39x 19.40 -> 0.51 38.06x
fp16 m=k=2048, n=8, A.t()=1, B.t()=0 14.95 -> 2.60 5.75x 15.03 -> 0.79 18.97x
fp16 m=k=2048, n=8, A.t()=1, B.t()=1 65.60 -> 2.59 25.30x 67.79 -> 0.96 70.55x
fp16 m=k=2048, n=16, A.t()=0, B.t()=0 39.13 -> 2.09 18.69x 39.40 -> 0.49 79.76x
fp16 m=k=2048, n=16, A.t()=1, B.t()=0 28.04 -> 2.56 10.96x 27.99 -> 0.93 30.14x
fp16 m=k=2048, n=16, A.t()=1, B.t()=1 131.95 -> 2.63 50.17x 129.94 -> 0.88 147.43x
fp16 m=k=2048, n=32, A.t()=0, B.t()=0 79.34 -> 3.19 24.87x 79.48 -> 1.07 74.26x
fp16 m=k=2048, n=32, A.t()=1, B.t()=0 54.06 -> 3.69 14.66x 54.07 -> 1.55 34.88x
fp16 m=k=2048, n=32, A.t()=1, B.t()=1 260.21 -> 3.81 68.30x 271.02 -> 1.25 216.22x
bf16 linear_fwd [email protected]() 128x4096x4096 191.92 -> 43.96 4.37x 70.30 -> 66.16 1.06x
bf16 decode [email protected]() 1x4096x4096 2.88 -> 2.74 1.05x 0.71 -> 0.64 1.11x
bf16 decode x@W 1x4096x4096 143.44 -> 147.78 0.97x 143.24 -> 10.73 13.35x
bf16 grad_input dY@W 64x1024x1024 117.96 -> 1.15 102.38x 119.74 -> 1.73 69.19x
bf16 grad_weight dY.t() @ X 1024x1024x64 6.24 -> 1.30 4.80x 6.25 -> 0.47 13.26x
bf16 attn P@V 512x64x512 8.94 -> 0.29 30.74x 9.05 -> 0.11 84.10x
bf16 mm 512x512x512 NN 88.85 -> 2.16 41.09x 89.34 -> 0.57 157.95x
bf16 mm 512x512x512 TT 87.91 -> 2.18 40.25x 88.09 -> 0.80 110.55x
bf16 m=k=2048, n=1, A.t()=0, B.t()=0 1.92 -> 1.50 1.28x 2.36 -> 0.32 7.35x
bf16 m=k=2048, n=1, A.t()=1, B.t()=0 0.29 -> 8.21 0.04x 0.35 -> 1.79 0.19x
bf16 m=k=2048, n=1, A.t()=1, B.t()=1 8.11 -> 8.28 0.98x 7.91 -> 1.57 5.05x
bf16 m=k=2048, n=2, A.t()=0, B.t()=0 3.82 -> 2.04 1.87x 4.56 -> 0.73 6.21x
bf16 m=k=2048, n=2, A.t()=1, B.t()=0 9.40 -> 2.92 3.22x 9.52 -> 0.95 10.02x
bf16 m=k=2048, n=2, A.t()=1, B.t()=1 15.86 -> 2.50 6.36x 15.90 -> 1.10 14.45x
bf16 m=k=2048, n=4, A.t()=0, B.t()=0 7.53 -> 1.99 3.78x 7.84 -> 0.52 15.07x
bf16 m=k=2048, n=4, A.t()=1, B.t()=0 6.64 -> 2.59 2.56x 6.84 -> 0.68 10.05x
bf16 m=k=2048, n=4, A.t()=1, B.t()=1 32.20 -> 2.58 12.48x 31.27 -> 0.92 33.82x
bf16 m=k=2048, n=8, A.t()=0, B.t()=0 15.03 -> 2.04 7.37x 15.12 -> 0.63 24.09x
bf16 m=k=2048, n=8, A.t()=1, B.t()=0 7.54 -> 2.57 2.94x 7.96 -> 0.90 8.84x
bf16 m=k=2048, n=8, A.t()=1, B.t()=1 63.12 -> 2.56 24.68x 61.68 -> 0.90 68.34x
bf16 m=k=2048, n=16, A.t()=0, B.t()=0 32.78 -> 2.02 16.22x 32.97 -> 0.73 44.93x
bf16 m=k=2048, n=16, A.t()=1, B.t()=0 9.41 -> 2.55 3.69x 9.56 -> 1.05 9.13x
bf16 m=k=2048, n=16, A.t()=1, B.t()=1 126.19 -> 2.48 50.93x 126.55 -> 1.03 122.61x
bf16 m=k=2048, n=32, A.t()=0, B.t()=0 71.13 -> 3.07 23.18x 71.58 -> 1.31 54.60x
bf16 m=k=2048, n=32, A.t()=1, B.t()=0 13.54 -> 3.67 3.69x 13.73 -> 1.32 10.42x
bf16 m=k=2048, n=32, A.t()=1, B.t()=1 259.26 -> 3.90 66.52x 262.38 -> 1.24 211.06x

@frost-intel

Copy link
Copy Markdown
Collaborator
bf16 m=k=2048, n=1, A.t()=1, B.t()=0 0.29 -> 8.21 0.04x 0.35 -> 1.79 0.19x

I confirmed a similar regression on GNR when we force AVX-512, so this is also a problem for Xeon.

@Kanya-Mo Although I suspect this regression here is entirely due to a bad implementation in MKL rather than anything in your code, let's just decline bf16 for n == 1 && transa == NoTranspose.

@egeboy35

Copy link
Copy Markdown
Contributor

Thanks for checking this on GNR.

@Kanya-Mo, one thing worth keeping in mind before changing the condition: it also matches a layout where MKL is actually faster.

Drafted by Claude (AI) for @egeboy35.

One note on the condition. n == 1 && transa == NoTranspose also catches the (N, N) layout, and there MKL helped in my runs; the slowdown I measured was only in (N, T). bf16, same builds as above, median ms, layouts as printed by MKL_VERBOSE:

torch.mm cpublas call main, 1 thread PR, 1 thread main, 7 threads PR, 7 threads
A.t() @ v, A 2048x2048, v 2048x1 gemm(N, T, 2048, 1, 2048) 0.29 8.21 (0.04x) 0.35 1.79 (0.19x)
x @ W, x 1x4096, W 4096x4096 gemm(N, N, 4096, 1, 4096) 143.4 147.8 (0.97x) 143.2 10.7 (13.4x)
A.t() @ v.t(), A 2048x2048, v 1x2048 gemm(N, N, 2048, 1, 2048) 8.11 8.28 (0.98x) 7.91 1.57 (5.05x)

Both (N, N) rows are flat at one thread and a lot faster at 7. So adding transb != NoTranspose to the check would remove the regression and keep them on MKL. That's from one laptop though. If GNR also gets slower on (N, N) with n = 1, the broader check is the safer choice.

@Kanya-Mo
Kanya-Mo marked this pull request as ready for review November 24, 2026 23:45
@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Nov 25, 2026
@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 25, 2026

@github-actions github-actions Bot 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.

⏳ Automated review in progress for 5ac27ca (run); its result will replace this review.

Previous automated review of 0161bad

Automated review of 0161bad: changes requested before human review.

This PR adds mkl_xf16_gemm, a fallback that sends bf16/fp16 gemm to MKL's cblas_gemm_{bf16bf16,f16f16}f32 through an fp32 copy of C when oneDNN declines the problem. Recommendation: Request Changes, because frost-intel's request to decline bf16 for n == 1 &amp;&amp; transa == NoTranspose is only partly implemented and the author hasn't replied. Everything else is non-blocking.

🔴 1 blocking finding is attached to the code below.

⚪ 8 non-blocking findings are attached to the code below, collapsed.

Please address the findings and push; a new commit normally gets a fresh automated review.

Disagree with a finding? Reply with your reasoning, then comment @ pytorchbot review to request a re-review. This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

transb == TransposeType::NoTranspose && n < min_cols_transa;
// MKL's bf16 gemm is slow for matrix-vector products with A not transposed. With B
// transposed the ATen kernel is much faster
const bool bf16_gemv_transb = std::is_same_v<scalar_t, at::BFloat16> && n == 1 &&

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.

🔴 Blocking: frost-intel's bf16 gemv request is only partly implemented, and the author hasn't replied. They asked to "decline bf16 for n == 1 &amp;&amp; transa == NoTranspose", but bf16_gemv_transb also requires transb != NoTranspose, so bf16 gemm(N, N, m, n=1, k) still goes to MKL. Ordinary code reaches this case: x(1,k) @ W(k,out) with W contiguous, or torch.matmul(v, M). In addmm_impl_cpu_ the (1,out) result sets transpose_c, which gives gemm(N, N, out, 1, k). The narrowing may be correct: frost-intel's measured case maps to (N, T), which HEAD declines, and ATen's serial gemm_notrans_ path for (N, N) may lose to MKL. Either decline every n == 1 &amp;&amp; transa == NoTranspose bf16 call, or post a (N, N, n=1) benchmark on the thread and get the maintainer to agree. Also, the comment at lines 155-156 should say that "B transposed" means the gemm-level flag. For n == 1 that is the user's ordinary contiguous vector, the opposite of the "B.t()=0" wording in the thread.

Report this finding

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.

Fixed the comment as requested. For (N,N), ATen's gemm_notrans_ is a serial loop that's as slow as MKL on one thread (and never more), so declining it would give MKL's multithreaded speedup.
Here's benchmark on Xeon Platinum 8570, AVX2-class CPU emulated with ONEDNN_MAX_CPU_ISA=AVX2 MKL_ENABLE_INSTRUCTIONS=AVX2 ATEN_CPU_CAPABILITY=avx2 so bf16 reaches this fallback, MKL 2024.2

bf16, n = 1 gemm call 1 thread: main -> PR 25 threads: main -> PR
x @ W, W 2048x2048 (N, N, 2048, 1, 2048) 22.6 -> 22.5 ms (1.01x) 13.1 -> 0.64 ms (20.4x)
x @ W, W 4096x4096 (N, N, 4096, 1, 4096) 159.6 -> 172.1 ms (0.93x) 81.9 -> 1.45 ms (56.6x)
A.t() @ v, A 2048x2048 (N, T, 2048, 1, 2048) 0.03x before the decline, 1.04x now 0.04x before, 1.04x now
A.t() @ v, A 4096x4096 (N, T, 4096, 1, 4096) 0.02x before, 1.03x now 0.43x before, 1.02x now

This matches the i7-11800H findings shared by @egeboy35 : (N, N) is neutral at one thread and much faster with more threads, and only (N, T) regressed.

!use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) {
return false;
}
at::DataPtr c_buf = c10::GetCPUAllocator()->allocate(m * n * sizeof(float));

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.

⚪ Non-blocking: the fp32 C staging is now written three times.

Lines 163-187 repeat the copy-in, f32 gemm, copy-out sequence of the OpenBLAS sbgemm_/shgemm_ blocks (around lines 435-461 and 501-527). A single templated helper would also give the OpenBLAS paths the profiler-visible allocator, the beta == 0 copy-in skip and the parallel copy. The new loops also use implicit BFloat16/Half <-> float conversion, where the neighbouring paths use c10::convert.

Report this finding

Comment thread aten/src/ATen/native/CPUBlas.cpp Outdated
// Runs a bf16/f16 gemm on MKL, which only writes f32 C, through an f32 copy of C.
// Returns false when the ATen kernel should handle the problem instead: tiny
// problems (same bound as mkldnn_gemm, where MKL's call overhead dominates),
// alpha == 0 (ATen kernel still propagates inf/NaN) and skinny transa ones, and

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.

⚪ Non-blocking: the header comment at lines 129-133 is garbled and incomplete.

It reads "...and skinny transa ones, and bf16...", and it leaves out the !use_blas_gemm decline.

Report this finding

Comment thread test/test_linalg.py
@dtypes(torch.bfloat16, torch.half)
@parametrize("transpose_a", [False, True])
@parametrize("transpose_b", [False, True])
@parametrize("alpha,beta", [(1, 0), (0.5, 2)])

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.

⚪ Non-blocking: the alpha == 0 decline is never exercised, because the test only uses alpha 1 and 0.5.

The decline exists to keep ATen's inf/NaN propagation, yet removing alpha == 0.0f from CPUBlas.cpp line 159 would still pass. Add a non-tiny case with alpha=0 and an inf or NaN in a.

Report this finding

Comment thread test/test_linalg.py
tol = 1e-2 if dtype == torch.bfloat16 else 2e-3
with torch.backends.mkldnn.flags(enabled=False):
for m, n, k in [(1, 65, 33), (7, 65, 33), (64, 33, 300), (129, 65, 33), (200, 1, 33), (129, 130, 1)]:
a, b, c = make(m, k, transpose_a), make(k, n, transpose_b), make(m, n, False)

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.

⚪ Non-blocking: ldc == m in every case.

The result is always freshly allocated and contiguous, so the stride-ldc vs stride-m indexing in the two copy loops (CPUBlas.cpp:166-187) is never tested. Write into a padded out= view, e.g. make_tensor((m, 2*n))\[:, :n\], and check that the untouched columns stay unchanged.

Report this finding

Comment thread test/test_linalg.py
@parametrize("transpose_b", [False, True])
@parametrize("alpha,beta", [(1, 0), (0.5, 2)])
def test_addmm_reduced_precision_without_mkldnn(self, device, dtype, transpose_a, transpose_b, alpha, beta):
# With oneDNN unavailable (ISA gate or disabled), bf16/fp16 gemm goes to MKL's

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.

⚪ Non-blocking: nothing shows that MKL ran.

On builds without MKL_HAS_SBGEMM/MKL_HAS_SHGEMM, the test silently checks only the ATen kernel. At minimum, reword the comment to say this is a results-only check. Also, no shape has m*k &gt; 1024*1024, so the thread-dependent branch never runs.

Report this finding

// transposed the ATen kernel is much faster
const bool bf16_gemv_transb = std::is_same_v<scalar_t, at::BFloat16> && n == 1 &&
transa == TransposeType::NoTranspose && transb != TransposeType::NoTranspose;
if (m * n * k <= 16 * 16 * 16 || alpha == 0.0f || skinny_transa || bf16_gemv_transb ||

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.

⚪ Non-blocking: numerics change for affected users.

This affects bf16/fp16 mm/addmm/linear/matmul on CPUs where oneDNN declines (AVX2-only CPUs for bf16; most CPUs without AVX512-FP16 for fp16), and any run with torch.backends.mkldnn disabled. Results will differ bitwise from previous releases. They can also depend on thread count: the ATen kernels computed each output element as one dot product on one thread, and MKL without CNR mode makes no such guarantee. Disabling mkldnn used to give the ATen reference kernel, and there is no switch to get it back. The release notes: linalg_frontend note should state this.

Report this finding

!use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) {
return false;
}
at::DataPtr c_buf = c10::GetCPUAllocator()->allocate(m * n * sizeof(float));

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.

⚪ Non-blocking: an extra fp32 buffer of m*n*4 bytes is allocated on every call, with no cap and no TODO, although frost-intel said a TODO for…

Non-blocking: an extra fp32 buffer of m*n*4 bytes is allocated on every call, with no cap and no TODO, although frost-intel said a TODO for chunking over n would be enough. The ATen notrans/transa/transab kernels it replaces allocated nothing; only gemm_transb_ and the OpenBLAS paths did. The cost is paid per batch element in the bf16/fp16 bmm fallback (the per-batch addmm_impl_cpu_ loop) and per frame inside at::parallel_for in slow_conv2d. Large outputs (e.g. an LM head) need several GB of extra temporary memory.

Report this finding

// thread count. The constants come from a sweep on one Xeon 8570 with AVX2 and
// AVX-512 without AMX emulated by capping the ISA.
const int64_t threads = at::in_parallel_region() ? 1 : at::get_num_threads();
const int64_t min_cols_transa = m * k <= 1024 * 1024 ? 24 : 24 + 6 * threads;

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.

⚪ Non-blocking: the heuristic's thread model doesn't hold in every build.

ParallelNative builds call mkl_set_num_threads(1) (ParallelNative.cpp:207), but at::get_num_threads() returns the intra-op pool size. So 24 + 6*threads assumes MKL threads that don't exist, and large skinny transa problems go to single-threaded MKL. The cutoff also jumps at m*k == 1024*1024 from 24 columns straight to 24 + 6*threads (216 at 32 threads). The constants come from a single Xeon 8570 with the ISA capped and are not checked on real AVX2 parts, including AMD. Consider named constants, and say in the comment which threading backend the model assumes.

Report this finding

@egeboy35

egeboy35 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Just a quick follow-up here.

Drafted by Claude (AI), edited by @egeboy35.

The (N, N, n=1) bf16 benchmark requested by the automated review is already in my Nov 21 comment above. On my i7-11800H, gemm(N, N, 4096, 1, 4096) and gemm(N, N, 2048, 1, 2048) showed no significant change at one thread, but were 13.4x and 5.05x faster, respectively, with this PR at seven threads. Only the (N, T) case showed a regression.

Based on these results, I think the narrower check makes sense. That said, I've only tested this on one laptop, so it would be good to confirm with GNR numbers.

This branch was previously deployed

1 inactive (outdated) deployment
bedrock — 0161bad1 Deployed Nov 24, 2026 by Kanya-Mo via analyze #41109
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

in progress PR is being worked on by the author, until the automated review accepts it open source release notes: linalg_frontend release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants