Skip to content

[mkldnn][3/N] Port ideep eltwise operators into ATen - #205709

Closed
frost-intel wants to merge 2 commits into
gh/frost-intel/1/basefrom
gh/frost-intel/1/head
Closed

frost-intel wants to merge 2 commits into
gh/frost-intel/1/basefrom
gh/frost-intel/1/head

Conversation

@frost-intel

@frost-intel frost-intel commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Linked issue or supporting maintainer

Part of #154444

BC-breaking?

No

Summary (human written only)

This PR directly ports the element-wise operators from ideep into ATen. This includes:
relu, sigmoid, tanh, gelu, scalar mul, dense GELU, and JIT from scalar mul.

Code is a line-for-line port from ideep, with identical functionality. 'mkldnn' tests pass with identical behavior.

Agent details (if applicable)

Developed with assistance from Claude Opus 5.5.

one_of and is_avx2_vnni_2, the helpers the ported operators share, are added to the existing
aten/src/ATen/native/mkldnn/Utils.h.

Previously submitted as #201055.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR copies ideep's eltwise_forward/eltwise_backward compute into ATen as
at::native::mkldnn::eltwise_forward/eltwise_backward and switches the relu,
sigmoid, tanh, gelu, scalar-mul and JIT frozen scalar-mul call sites over to
them. The review found no correctness, security or BC problems. Recommendation:
Approve, with only non-blocking style and consistency points.

Findings (3):

[minor] aten/src/ATen/native/mkldnn/detail/Utils.h:10
Second `Utils.h` (non-blocking): this adds a `Utils.h` one directory below the
existing `aten/src/ATen/native/mkldnn/Utils.h`, which already holds the
device/ISA capability checks (`mkldnn_bf16_device_check`, `is_arm_neoverse`,
...). Two headers with the same name in nested directories invite include
mix-ups. Consider moving `is_avx2_vnni_2` into the existing `Utils.h`. `one_of`
is only used in `Eltwise.cpp`, so it could be file-local there; as it stands, a
very generic template name lands in `at::native::mkldnn`, a namespace that
`torch/csrc/jit/tensorexpr/external_functions.cpp:1358` pulls in wholesale with
`using namespace`.

[minor] aten/src/ATen/native/mkldnn/detail/Eltwise.cpp:1
No TORCH_ASSERT guard (non-blocking): this file has no TORCH_ASSERT define,
unlike its sibling call sites (`Relu.cpp`, `Gelu.cpp`, `UnaryOps.cpp`,
`BinaryOps.cpp` and most other `native/mkldnn/*.cpp`), which start with `#define
TORCH_ASSERT_ONLY_METHOD_OPERATORS`. That guard compiles here, because the file
includes neither `Functions.h` nor `NativeFunctions.h`, and it stops the file
from later picking up a dependency on `native_functions.yaml`.
`TORCH_ASSERT_NO_OPERATORS` would not compile, since `MKLDNNCommon.h` includes
`ATen/core/Tensor.h`.

[minor] aten/src/ATen/native/mkldnn/detail/Eltwise.h:11
No `TORCH_API` (non-blocking): `eltwise_forward` and `eltwise_backward` are
declared without `TORCH_API`, yet
`torch/csrc/jit/passes/frozen_ops_to_mkldnn.cpp:502` calls `eltwise_forward`
from outside ATen. Nothing breaks today: both end up in `torch_cpu`, and there
is precedent in `mkldnn_layer_norm_last_index_weight_bias_f32`
(`mkldnn/Utils.h:20`). But the other ATen helpers this JIT file calls,
`itensor_from_mkldnn` and `new_with_itensor_mkldnn` (`MKLDNNCommon.h:43,46`),
are `TORCH_API`. Adding it would match them and protect against split-library
builds.

Reviewed commit: 2b0a34f (NOT the current head bab4100)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit bab4100 with merge base 4004f7e (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: jit release notes category labels Nov 19, 2026
@albanD albanD added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 19, 2026
@albanD
albanD self-requested a review November 19, 2026 19:00

@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 of 2b0a34f: nothing blocking; ready for human review.

The PR copies ideep's eltwise_forward/eltwise_backward compute into ATen as at::native::mkldnn::eltwise_forward/eltwise_backward and switches the relu, sigmoid, tanh, gelu, scalar-mul and JIT frozen scalar-mul call sites over to them. The review found no correctness, security or BC problems. Recommendation: Approve, with only non-blocking style and consistency points.

⚪ 3 non-blocking findings

template <typename T, typename... Items>

Second Utils.h (non-blocking): this adds a Utils.h one directory below the existing aten/src/ATen/native/mkldnn/Utils.h, which already holds the device/ISA capability checks (mkldnn_bf16_device_check, is_arm_neoverse, ...). Two headers with the same name in nested directories invite include mix-ups. Consider moving is_avx2_vnni_2 into the existing Utils.h. one_of is only used in Eltwise.cpp, so it could be file-local there; as it stands, a very generic template name lands in at::native::mkldnn, a namespace that torch/csrc/jit/tensorexpr/external_functions.cpp:1358 pulls in wholesale with using namespace.


#include <ATen/native/mkldnn/detail/Eltwise.h>

No TORCH_ASSERT guard (non-blocking): this file has no TORCH_ASSERT define, unlike its sibling call sites (Relu.cpp, Gelu.cpp, UnaryOps.cpp, BinaryOps.cpp and most other native/mkldnn/*.cpp), which start with #define TORCH_ASSERT_ONLY_METHOD_OPERATORS. That guard compiles here, because the file includes neither Functions.h nor NativeFunctions.h, and it stops the file from later picking up a dependency on native_functions.yaml. TORCH_ASSERT_NO_OPERATORS would not compile, since MKLDNNCommon.h includes ATen/core/Tensor.h.


No TORCH_API (non-blocking): eltwise_forward and eltwise_backward are declared without TORCH_API, yet torch/csrc/jit/passes/frozen_ops_to_mkldnn.cpp:502 calls eltwise_forward from outside ATen. Nothing breaks today: both end up in torch_cpu, and there is precedent in mkldnn_layer_norm_last_index_weight_bias_f32 (mkldnn/Utils.h:20). But the other ATen helpers this JIT file calls, itensor_from_mkldnn and new_with_itensor_mkldnn (MKLDNNCommon.h:43,46), are TORCH_API. Adding it would match them and protect against split-library builds.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@frost-intel frost-intel added topic: not user facing topic category and removed release notes: jit release notes category labels Nov 19, 2026
@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 19, 2026
[ghstack-poisoned]
@frost-intel

Copy link
Copy Markdown
Collaborator Author

I moved the util functions into mkldnn/Utils.h

@frost-intel

Copy link
Copy Markdown
Collaborator Author

Regarding the TORCH_API and TORCH_ASSERT, those remain the same for this stack in order to preserve identical behavior to ideep, and I've noted it for a follow-up PR.

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

Looks good

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #205717

pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
…into ATen (#205710)

## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Ports `sum` and `binary` operators from ideep to `at::native::mkldnn::sum/binary`. Port is line-for-line. I also copy the `direct_copy` function in a new file. When we port `ideep::tensor` into ATen, the direct copy function will be moved into that file, so this is temporary.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.

> **What changed** (11 files, +167/−8):
>
> - **`detail/Sum.{h,cpp}` and `detail/Binary.{h,cpp}`:** `at::native::mkldnn::sum` and `binary`, ported line for line from ideep's `sum.hpp` and `binary.hpp`, one file each as in ideep. They keep the user-managed scratchpad, the output layout choice (from the inputs for `sum`, "any" for `binary`), input reorders for `binary`, and the in-place buffer replacement on `dst`.
> - **`detail/DirectCopy.{h,cpp}`:** `direct_copy`, ported from ideep's `direct_copy.hpp`. It keeps the buffer replacement, the reorder and the scale propagation.
> - **Call sites:** all 8 switched.
>
>   | File | Ops | Calls |
>   |---|---|---|
>   | `BinaryOps.cpp` | `add_out` (×2), `add`, `mul_out` | 4 |
>   | `Copy.cpp` | `copy_` | 1 |
>   | `TensorShape.cpp` | `clone` | 1 |
>   | `Normalization.cpp` | batchnorm running-stats update | 2 |
>
>   No `ideep::sum`, `ideep::binary` or `ideep::direct_copy` calls remain outside XPU, and `BinaryOps.cpp` and `Copy.cpp` no longer call any ideep operator.
> - **`build_variables.bzl`:** 3 entries. CMake and Buck pick up headers from the `detail/` setup added in PR 3.
>
> **Checks:**
>
> - **Same oneDNN calls before and after.** I ran all of `test_mkldnn.py` plus `test_freezing.py -k mkldnn` with `ONEDNN_VERBOSE=1` and compared the logged primitive creations and executions, with timings stripped. I ran the baseline twice first, and it repeats exactly, so any difference would be real.
>   - All 6,572 distinct primitive log lines are identical.
>   - Those tests exercise the ported code: `sum` runs 40 times (13 distinct), `binary` 4 times, and `reorder` runs 130,755 times, which includes the copies.
> - **Tests:**
>   - `test_mkldnn.py`: 92 passed, 1 skipped.
>   - Freezing tests: 4 passed, 5 skipped.
>   - `test_mkldnn_fusion.py`: OK.
>   - `test_nn.py -k "batchnorm and cpu"`: 9 passed.
> - **Lint:** clean.
>
> (`test/jit/test_freezing.py` and `test/test_mkldnn_fusion.py` were later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201059.

Pull Request resolved: #205710
Approved by: https://github.com/albanD
ghstack dependencies: #205709
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Softmax is ported line-for-line from ideep. Since the backward pass is never called in ATen, that is not ported.  As part of this process, any ideep code that is not called in ATen is not being ported. A softmax backend for mkldnn tensors doesn't currently exist, but adding it is outside the scope of this PR. Generally loss has been computed on regular tensors, making mkldnn softmax backward unnecessary.

Prelu forward and backward are ported line-for-line. An unused arg is dropped from `prelu_backward` (`prop_kind`).

Any calls to the ideep operators are removed from ATen.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.
> **What changed** (7 files, +209/−4):
>
> - **`detail/Softmax.{h,cpp}`:** `softmax_forward`, ported line for line, including the in-place buffer replacement on `dst`. Only the forward pass is ported, because ATen never calls ideep's `softmax_backward`.
> - **`detail/Prelu.{h,cpp}`:** `prelu_forward` and `prelu_backward`, ported line for line.
>   - Kept: the weight reshape to match the input's rank, the input reorders, buffer replacement on the outputs, the avx2_vnni_2 bf16/f16 check (using `is_avx2_vnni_2` from `mkldnn/Utils.h`), and reshaping the weight gradient back at the end.
>   - Dropped two things ideep never used: an unused variable, and the `prop_kind` argument of `prelu_backward`. The call site no longer passes `dnnl::prop_kind::backward`.
> - **Call sites:** `SoftMax.cpp` (1) and `Prelu.cpp` (2). Neither file calls ideep operators anymore.
> - **`build_variables.bzl`:** 2 entries.
>
> **Checks:**
>
> - **Same oneDNN calls before and after.** I ran all of `test_mkldnn.py` plus `test_freezing.py -k mkldnn` with `ONEDNN_VERBOSE=1` and compared the logged primitive creations and executions, with timings stripped. All 6,572 distinct primitive log lines are identical.
>   - `prelu` runs 64 times in those tests, 13 of the distinct lines being backward.
>   - `softmax` runs only 3 times.
> - **Tests:**
>   - `test_mkldnn.py`: 92 passed, 1 skipped.
>   - Freezing tests: 4 passed, 5 skipped.
>   - `test_nn.py -k "prelu or softmax"`: 36 passed.
> - **Lint:** clean.
>
> (`test/jit/test_freezing.py` was later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201062.

Pull Request resolved: #205711
Approved by: https://github.com/albanD
ghstack dependencies: #205709, #205710
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Port of `pooling_forward/backward` from ideep. Ported line-for-line. A few details that might be seen in review:
* The dilation variants (pooling_v2) in ideep are never called in ATen, so they are left out of the port here.
* A workaround for an existing layout issue (`src._get_unblocked_desc_if_4c_blocked`) is left as-is. Fixing/verification is outside the scope of this porting PR.

Pooling calls are now to aten operators, not ideep.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.

> **What changed** (4 files, +189/−2):
>
> - **`detail/Pooling.{h,cpp}`:** `pooling_forward` and `pooling_backward`, ported line for line from ideep's `pool.hpp`.
>   - Kept: the workaround that reads `src`'s layout through `_get_unblocked_desc_if_4c_blocked()` (for oneDNN issue uxlfoundation/oneDNN#588), output layout `any`, the input reorder, buffer replacement on the outputs, scale propagation, and the avx2_vnni_2 bf16/f16 check on backward.
>   - **Max-pool indices:** in training mode, forward stores the indices on `dst` (`init_workspace`), and backward reads them back from `dst` and reorders them if needed. This is unchanged from ideep, so tensors created before and after this change behave the same.
>   - Only the variants ATen calls are ported. ideep's `pooling_v2_forward/backward` (the dilation variants) have no ATen callers.
> - **Call sites:** `Pooling.cpp` (2). It no longer calls ideep operators.
> - **`build_variables.bzl`:** 1 entry.
>
> **Checks:**
>
> - **Same oneDNN calls before and after.** Same comparison as above. All 6,572 distinct primitive log lines are identical.
>   - Pooling runs 227 times, with 216 distinct lines. Of those, 48 are max-pool forward in training mode and 48 are max-pool backward.
>   - The max-pool backward lines include the workspace argument (`ws:s32::blocked:...`), so the stored indices reach the backward pass.
> - **Tests:**
>   - `test_mkldnn.py`: 92 passed, 1 skipped.
>   - Freezing tests: 4 passed, 5 skipped.
>   - `test_nn.py -k "pool and cpu"`: 1 passed, 6 skipped.
> - **Lint:** clean.
>
> (`test/jit/test_freezing.py` was later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201080.

Pull Request resolved: #205712
Approved by: https://github.com/albanD
ghstack dependencies: #205709, #205710, #205711
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Line-for-line ports of layernorm and batchnorm from ideep to ATen.

Layernorm drops an empty stub that wasn't ported from ideep.

Batchnorm includes the inference, training, and backward versions. Some args that had no effect were removed.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.

> **What changed** (7 files, +318/−5):
>
> - **`detail/BatchNorm.{h,cpp}`:** the three batchnorm functions ATen calls, ported line for line from ideep's `batchnorm.hpp`:
>   - `batch_normalization_forward_inference`: the version that takes the running mean and variance.
>   - `batch_normalization_forward_training`: the version without running stats. ATen updates the running stats itself.
>   - `batch_normalization_backward`.
>   - Kept: the workaround that reads `src`'s layout through `_get_unblocked_desc_if_4c_blocked()` (for oneDNN issue uxlfoundation/oneDNN#588), the input/mean/variance reorders, buffer replacement on the outputs, the user-managed scratchpad, and the avx2_vnni_2 bf16/f16 check on backward.
>   - The flags are fixed to `use_scale | use_shift` (plus `use_global_stats` for inference). ATen always used ideep's default flags, so ideep's fused-relu path and its workspace never ran. I also removed the parameters ideep took but ATen never set or ideep never used: `flags`, `dst` on backward, and `momentum` on training. In ideep's training function `momentum` had no effect.
>   - Not ported because ATen never calls them: the inference version without stats, and the training version that updates running stats with `ideep::sum`.
> - **`detail/LayerNorm.{h,cpp}`:** `layer_normalization_forward`, ported line for line. ideep's `layer_normalization_backward` is an empty stub and isn't ported.
> - **Call sites:** `Normalization.cpp` (4). The two `ideep::sum` calls for the running stats are ported separately in the sum/binary PR.
> - **`build_variables.bzl`:** 2 entries.
>
> **Checks:**
>
> - **Same oneDNN calls before and after.** I ran all of `test_mkldnn.py` plus `test_freezing.py -k mkldnn` with `ONEDNN_VERBOSE=1` and compared the logged primitive creations and executions, with timings stripped. All 6,572 distinct primitive log lines are identical.
>   - Batchnorm runs 87 times: 17 distinct lines for inference, 1 for training forward and 1 for backward.
>   - The oneDNN logs are identical, including the `layer_normalization` call.
>   - The outputs are bitwise identical.
>   - The output matches eager mode to within 2.4e-7.
> - **Tests:**
>   - `test_mkldnn.py`: 92 passed, 1 skipped.
>   - Freezing tests: 4 passed, 5 skipped.
>   - `test_mkldnn_fusion.py`: OK.
>   - `test_nn.py -k "batchnorm or layer_norm or layernorm"`: 24 passed.
> - **Lint:** clean.
>
> **Update:** `test_mkldnn_layer_norm` was originally added to `test/jit/test_freezing.py`. Upstream
> #203621 deleted that file along with the public `torch.jit.script` / `torch.jit.freeze`, so the test now
> lives in `test/test_mkldnn.py`. It drives the frozen-graph pass through `torch.jit._script.script`,
> `torch.jit._freeze.freeze` and `torch._C._jit_pass_convert_frozen_ops_to_mkldnn`, checks for
> `prim::MKLDNNLayerNorm`, and compares against eager with a random LayerNorm weight and bias. It passes before and after this PR and executes the
> oneDNN `layer_normalization` primitive.
>
> (`test/jit/test_freezing.py` and `test/test_mkldnn_fusion.py` were later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201083.

Pull Request resolved: #205713
Approved by: https://github.com/albanD
ghstack dependencies: #205709, #205710, #205711, #205712
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Line-for-line ports of LSTM from ideep. Not all of ideep functionality is included, only what is used in ATen currently. Note that we continue to use `ideep::tensor` until all ops are ported over, then we will transition to the ported class.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.

> **What changed** (5 files, +464/−7):
>
> - **`detail/Lstm.{h,cpp}`:** the five LSTM functions ATen calls, ported line for line from ideep's `lstm.hpp`:
>   - `lstm_forward_inference`
>   - `lstm_forward_inference_expected_weights_desc`: the packed weight layout used when weights are prepacked
>   - `lstm_forward_training_prepare` and `lstm_forward_training`
>   - `lstm_backward`
> - **Kept as in ideep:**
>   - "any" layouts for the weights, the weight reorders, buffer replacement on the outputs, the workspace argument, and the user-managed scratchpad. The packed-layout lookup keeps ideep's default scratchpad mode.
>   - Backward computes gradients in f32, zero-initializes the weight and bias gradients before running (oneDNN adds into them), and copies the results back into the caller's tensors.
>   - The avx2_vnni_2 bf16/f16 check on backward.
>   - ideep's 8-bit-input branch (s8 weights plus the RNN quantization attributes), kept line for line. ATen cannot reach it today: every LSTM entry point builds its input with `itensor_view_from_const_dense`, which accepts only float, bfloat16 and half. ATen never passes quantization parameters, so it would keep ideep's defaults (all −1).
> - **Simplified:**
>   - Removed parameters ATen never sets or ideep never reads: the attribute and quantization parameters, and `reverse`/`prop_kind` on training `compute`, where ideep ignored them.
>   - ideep's `lstm_forward_training::expected_weights_desc` has no ATen callers and is not ported.
> - **Call sites:** `RNN.cpp` (5) and `MKLDNNConversions.cpp` (1, the LSTM weight prepack). No `ideep::lstm_*` calls remain.
> - **`build_variables.bzl`:** 1 entry.
>
> **Checks:**
>
> - **Same oneDNN calls before and after.** I ran all of `test_mkldnn.py` plus `test_freezing.py -k mkldnn` with `ONEDNN_VERBOSE=1` and compared the logged primitive creations and executions, with timings stripped. All 6,572 distinct primitive log lines are identical.
>   - LSTM runs 36,864 times there, in f32 and bf16: 156 distinct lines for inference, 104 for training forward and 104 for backward.
> - **Weight prepack (`mkldnn._reorder_mkldnn_rnn_layer_weight`).** Inductor's freezing pass uses this op, and it's the only caller of `expected_weights_desc`. I called it for 24 configurations (f32/bf16, two sizes, both directions, three input-size settings) on builds from before and after this change:
>   - The oneDNN logs are identical.
>   - The serialized layout of all 48 packed weights is byte-identical.
>   - Their values are bitwise identical.
> - **Tests:**
>   - `test_mkldnn.py`: 92 passed, 1 skipped.
>   - `test_nn.py -k "lstm and cpu"`: 8 passed.
>   - `test/inductor/test_cpu_repro.py -k lstm`: 514 passed. This exercises the prepacked-weight path end to end.
> - **Lint:** clean.
>
> (`test/jit/test_freezing.py` was later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201126.

Pull Request resolved: #205714
Approved by: https://github.com/albanD
ghstack dependencies: #205709, #205710, #205711, #205712, #205713
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Ports inner-product operators from ideep to ATen. A few unused parameters are removed.

One non-impactful code change: previously, calls within `mkldnn_linear` calls a function marked "DEPRECATED" in ideep. These deprecated functions were superseded by a templatized version, but the `mkldnn_linear` calls hadn't been updated to match those in `mkldnn_linear_pointwise` which do use the templateized version. I did not port the deprecated calls over, so the calls in `mlkdnn_linear` now fallback to the templatized version.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.

> **What changed** (5 files, +838/−10):
> - **`detail/InnerProduct.{h,cpp}`:** the inner-product code ATen calls, ported line for line from ideep's `inner_product.hpp`:
>   - `inner_product_forward` (with and without bias) and `inner_product_forward_binary` (with and without bias), keeping ideep's `reorder_src`/`reorder_weight` template parameters. Only the combinations ATen uses are compiled: `<true, true>` and `<false, false>` for forward, `<false, false>` for binary.
>   - `inner_product_forward_expected_weights_desc`, `inner_product_backward_data`, and `inner_product_backward_weights` (with and without bias).
>   - ideep's private functions and its `inner_product_forward_params` struct are ported under their ideep names, local to the `.cpp`. ideep's backward-weights `compute_impl` becomes `backward_weights_compute_impl`, because it would otherwise collide with the forward `compute_impl`.
> - **Primitive cache:** on x86, primitive descriptors are still fetched from ideep's cache (`ideep::utils::computation_cache<dnnl::inner_product_forward::primitive_desc>` with `ideep::utils::create_key`). This is the same cache ideep's own operators use, with the same key fields, capacity, and `LRU_CACHE_CAPACITY` handling. Porting the cache itself is a later PR. The aarch64 path, which bypasses the cache, is kept under `#ifdef __aarch64__` as in ideep.
> - **Kept as in ideep:** input/weight/bias reorders, the dst-buffer reuse and copy-back logic, the sum post-op copy in `do_compute_`, the Caffe2 int8 source-scale handling, the src/weights reshape workaround, the avx2_vnni_2 bf16/f16 check on both backward functions, and ideep's debug-only argument checks. Those are written out as `#ifndef NDEBUG dnnl::error::wrap_c_api(...)`, so they still only run in debug builds and throw the same error.
> - **Not ported, because ATen never calls them:** the `prepare`/`compute`/`compute_binary` overloads that take a precomputed `params` object, plus `do_prepare` and `do_compute`, which only those overloads use.
> - **Removed, because ATen never set them or they did nothing:**
>   - The unused scale and `lowp_kind` parameters of ideep's deprecated `compute` overloads. These were the overloads ATen's plain linear actually resolved to; they called the same `compute_impl` as the templated overloads.
>   - The `attr` parameters on both backward functions (ATen always used the default).
>   - `diff_weight_type` on backward weights (always the default, so the gradient type is `diff_dst`'s), along with the type-conversion branch that only ran for other values.
>   - An unused `op_attr` local in `do_compute_binary`.
> - **Call sites:** `Linear.cpp` (9) and `MKLDNNConversions.cpp` (1, the linear weight prepack). The only remaining `ideep::inner_product_forward` text is a comment in `qlinear_dynamic.cpp`.
> - **`build_variables.bzl`:** 1 entry.
>
> **Checks:**
>
> - **Same oneDNN calls before and after**, with `ONEDNN_VERBOSE=1` and timings stripped:
>   - `test_mkldnn.py` plus `test_freezing.py -k mkldnn`: all 6,572 distinct primitive log lines are identical. These include 32 inner-product executions, some of them backward.
>   - `test_mkldnn_fusion.py` plus `test/inductor/test_mkldnn_pattern_matcher.py -k "linear and not qlinear and not quant and not woq and not da8w8"`: all 892 distinct primitive log lines are identical. These cover 254 distinct inner-product lines (the fused linear and binary-fusion paths with prepacked weights) and 61 distinct reorder lines, including the weight-prepack reorders.
> - **Tests:**
>   - `test_mkldnn.py`: 92 passed, 1 skipped.
>   - Freezing tests: 4 passed, 5 skipped.
>   - `test_mkldnn_fusion.py`: 9 passed.
>   - `test_mkldnn_pattern_matcher.py` (linear subset): 12 passed.
> - **Lint:** clean.
>
> (`test/jit/test_freezing.py` and `test/test_mkldnn_fusion.py` were later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201194.

Pull Request resolved: #205715
Approved by: https://github.com/albanD
ghstack dependencies: #205709, #205710, #205711, #205712, #205713, #205714
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Ports floating-point conv **forward** operators from ideep.  Only ops called within ATen are ported over. Backward and quantized ops are left for a follow-up PR

Ports are line-for-line and do not change any behavior.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.

> Ports the floating-point convolution **forward** operators that ATen uses from ideep (`ideep::convolution_forward`) into `aten/src/ATen/native/mkldnn/detail/Conv.{h,cpp}` (namespace `at::native::mkldnn`). The port is line-for-line and changes no behavior: it still takes `ideep::tensor` / `ideep::attr_t` and uses ideep's engine, stream and primitive cache.
>
> To stay under the PR size limit, convolution is split across three PRs:
> - **This PR:** fp32 forward.
> - **#201229, backward:** `convolution_backward_data` / `convolution_backward_weights`, in `detail/Conv.{h,cpp}`.
> - **#202611, `compute_v2`:** ideep's deprecated `compute_v2` and the int8 `prepare_parameters` / `compute_dispatch` it routes through. Used only by `ConvPrepack.cpp`. Stacked on this PR.
>
> ### Ported
> Public (`detail/Conv.h`), each with ideep's comment:
> - `convolution_forward_compute_v3`: with and without bias.
> - `convolution_forward_compute_binary<reorder_src, reorder_weight>`: with and without bias. Explicitly instantiated for `<true, true>`, the only combination ATen uses.
> - `convolution_forward_expected_weights_desc`: the overload that takes `is_channels_last` at runtime.
>
> File-local (`detail/Conv.cpp`), same names as in ideep:
> - `convolution_forward_params`
> - `conv_deconv_utils::prepare_parameters` (fp32 overload)
> - `get_primitive_desc`: the uncached aarch64 variant and the cached x86 variant
> - `expected_weights_desc<is_channels_last>`
> - `do_compute`, `do_compute_binary`
> - `compute_dispatch` (fp32)
> - `do_prepare` (fp32)
> - `compute_binary_dispatch`
>
> ### Call sites switched
> - `mkldnn/Conv.cpp`: `compute_v3` ×2, `compute_binary` ×2.
> - `mkldnn/ConvPrepack.cpp`: `expected_weights_desc`.
> - `mkldnn/MKLDNNConversions.cpp`: `expected_weights_desc` ×2 (conv2d/conv3d weight reorder).
> - `quantized/cpu/qconv_prepack.cpp`: `expected_weights_desc` ×2. This is a quantized file, but the call is the same fp `expected_weights_desc` overload.
>
> Still on ideep:
> - backward data and weights (backward PR)
> - `ConvPrepack.cpp` `compute_v2` (`compute_v2` PR)
> - quantized `prepare` / `compute` in `qconv.cpp`
> - transposed convolution
> - `t_store().clear()` in `IDeepRegistration.cpp`
>
> ### Dropped (no ATen callers / unused)
> - `convolution_forward::use_gemm`
> - unused overloads, and the `engine` / `lowp_kind` parameters on the public functions
> - the int8 `do_prepare` and the param-based `prepare` / `compute(params, ...)` overloads (moving with quantized conv)
>
> ### Other changes
> - `IDEEP_ENFORCE` becomes a debug-only `dnnl::error::wrap_c_api(...)` under `#ifndef NDEBUG`. `IDEEP_CHECK` becomes an unconditional `wrap_c_api`. Both behave as in ideep.
> - Called directly from ideep for now: `ideep::utils::get_compatible_dilates`, `ideep::utils::group_dims`, `ideep::utils::create_key`, `ideep::utils::computation_cache`.
> - The primitive cache is ideep's thread-local `computation_cache<dnnl::convolution_forward::primitive_desc>`, the same store ideep uses. `clear_computation_cache()` therefore needs no change.
> - Two loop indices in `expected_weights_desc` changed from `int` to `size_t` (sign-compare; ideep hides this as a system header).
> - Fixed typos in a comment copied from ideep: "workaroud", "detials", "weihgts".
>
> ### Testing
> oneDNN verbose logs (`ONEDNN_VERBOSE=1`, timings stripped, sorted counts) are identical before and after:
> - `test_mkldnn.py` plus `test_freezing.py -k mkldnn`: 6,572 distinct lines.
> - `quantization/core/test_quantized_op.py -k "qconv and pt2e and not fp8"`: 257 distinct lines.
> - `test_mkldnn_fusion.py`, `nn/test_convolution.py -k mkldnn`, and `inductor/test_mkldnn_pattern_matcher.py -k "conv and not qconv and not quant and not woq"`: 1,284 distinct lines, 772 of them convolution.
>
> Four Inductor tests fail identically with and without this change: `test_conv{2,3}d_binary_broadcast_shapes_cpu` and `test_conv_transpose{2,3}d_unary_cpu`, all with bf16 tolerance errors. `test_conv2d_unary_cpu` is flaky at its fp32 tolerance.
>
> Convolution is split across PRs for size: forward (#201224), backward (#201229), `compute_v2` (#202611), quantized (#202622) and transposed (#203645). Backward lives in `detail/Conv.{h,cpp}` alongside forward.
>
> (`test/jit/test_freezing.py` and `test/test_mkldnn_fusion.py` were later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201224.

Pull Request resolved: #205716
Approved by: https://github.com/albanD
ghstack dependencies: #205709, #205710, #205711, #205712, #205713, #205714, #205715
pytorchmergebot pushed a commit that referenced this pull request Nov 20, 2026
## Linked issue or supporting maintainer
Part of #154444

## BC-breaking?
No

## Summary (human written only)
Port of the convolution backward ops from ideep to ATen. Unused params and functions were dropped, but otherwise this is a line-for-line port with identical functionality, verified by tests and onednn_verbose log checking.

## Agent details (if applicable)
Developed with assistance from Claude Opus 5.5.

>
> Ports the floating-point convolution **backward** operators that ATen uses from ideep (`ideep::convolution_backward_data`, `ideep::convolution_backward_weights`) into `aten/src/ATen/native/mkldnn/detail/Conv.{h,cpp}` (namespace `at::native::mkldnn`), based on #201224 (conv forward). The port is line-for-line and changes no behavior: it still takes `ideep::tensor` / `ideep::attr_t` and uses ideep's engine and stream.
>
> This is one of the convolution PRs (split for size). It adds the backward functions to the same `detail/Conv.{h,cpp}` as the forward port.
>
> ### Ported
> Public (`detail/Conv.h`):
> - `convolution_backward_data_compute_v2` (`ideep::attr_t op_attr` by value, as in ideep)
> - `convolution_backward_weights_compute_v2`: with and without bias
>
> File-local (`detail/Conv.cpp`):
> - `backward_weights_compute_impl<with_diff_bias>`: ideep's `convolution_backward_weights::compute_impl`, renamed to avoid clashing with the forward helpers.
>
> Both functions keep ideep's aarch64 and x86 primitive-descriptor variants.
>
> The forward primitive descriptor used as a hint comes from the ported `get_primitive_desc`, exactly as ideep's backward does. On x86 that lookup goes through ideep's forward primitive cache, as before.
>
> ### Call sites switched
> - `mkldnn/Conv.cpp`: `mkldnn_convolution_backward_input` (backward data) and `mkldnn_convolution_backward_weights` (with and without bias).
>
> ### Dropped (no ATen callers / unused)
> - The `algorithm` parameter of both functions; it was always `convolution_direct`, which is now fixed locally.
> - The `engine` parameters.
> - Backward weights: `diff_weight_type` and the branch that only ran with a non-default value.
>
> ### Other changes
> - `IDEEP_CHECK` (bf16/f16 on avx2_vnni_2) becomes an unconditional `dnnl::error::wrap_c_api`, as in ideep. ideep's backward functions have no `IDEEP_ENFORCE`, so there is no debug-only check here.
> - Called directly from ideep for now: `ideep::utils::get_compatible_dilates`.
>
> ### Testing
> oneDNN verbose logs (`ONEDNN_VERBOSE=1`, timings stripped, sorted counts) are identical before and after:
> - `test_mkldnn.py` plus `test_freezing.py -k mkldnn`: 6,572 distinct lines, 1,494 of them convolution backward.
> - `quantization/core/test_quantized_op.py -k "qconv and pt2e and not fp8"`: 257 distinct lines.
> - `nn/test_convolution.py -k mkldnn` and the Inductor mkldnn pattern tests: covered by the whole-series A/B comparison against `main` in #204808, with identical per-test outcomes and identical oneDNN primitive logs. (`test_mkldnn_fusion.py` no longer exists upstream.)
>
> (`test/jit/test_freezing.py` was later deleted upstream by #203621. The final A/B comparison of the whole series against `main`, described in #204808, re-checks these paths without it.)
>
> Previously submitted as #201229.

Pull Request resolved: #205717
Approved by: https://github.com/albanD
ghstack dependencies: #205709, #205710, #205711, #205712, #205713, #205714, #205715, #205716
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Merged module: cpu CPU specific problem (e.g., perf, algorithm) open source ready for review Automated review passed, ready for a final review by a maintainer. topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants