Repository navigation
Conversation
PR Status: in progressPlease 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:
Findings (11): Reviewed commit: 🔗 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.
|
frost-intel
left a comment
There was a problem hiding this comment.
Can you document exactly what env options were specified to emulate AVX512 and AVX2?
| // 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); |
There was a problem hiding this comment.
Where does this heuristic come from? Was it tuned on just one machine? Or is there some reasoning you could provide in a comment?
There was a problem hiding this comment.
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.
|
@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.
|
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 |
|
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.
|
There was a problem hiding this comment.
⏳ 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 && 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 && |
There was a problem hiding this comment.
🔴 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 && 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 && 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.
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
⚪ 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.
| // 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 |
There was a problem hiding this comment.
⚪ 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.
| @dtypes(torch.bfloat16, torch.half) | ||
| @parametrize("transpose_a", [False, True]) | ||
| @parametrize("transpose_b", [False, True]) | ||
| @parametrize("alpha,beta", [(1, 0), (0.5, 2)]) |
There was a problem hiding this comment.
⚪ 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.
| 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) |
There was a problem hiding this comment.
⚪ 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.
| @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 |
There was a problem hiding this comment.
⚪ 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 > 1024*1024, so the thread-dependent branch never runs.
| // 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 || |
There was a problem hiding this comment.
⚪ 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.
| !use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { | ||
| return false; | ||
| } | ||
| at::DataPtr c_buf = c10::GetCPUAllocator()->allocate(m * n * sizeof(float)); |
There was a problem hiding this comment.
⚪ 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.
| // 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; |
There was a problem hiding this comment.
⚪ 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.
|
Just a quick follow-up here.
|
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)
TransformerEncoderLayerfwd, d=1024, FFN 4096, 4x128 tokensmm1024x1024 @ 1024x1024linearW 11008x4096, batch 512linearW 4096x4096, batch 128TransformerEncoderLayerfwd, d=1024, FFN 4096, 4x128 tokensmm1024x1024 @ 1024x1024linearW 11008x4096, batch 512linearW 4096x4096, batch 128linearW 4096x4096, batch 8The env options used to emulate older CPUs
ONEDNN_MAX_CPU_ISAMKL_ENABLE_INSTRUCTIONSATEN_CPU_CAPABILITYAVX512_COREAVX512avx512AVX2AVX2avx2