Repository navigation
[mkldnn][7/N] Port batchnorm and layernorm from ideep to ATen - #205713
frost-intel wants to merge 5 commits into
Conversation
[ghstack-poisoned]
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - Ready for human review:
Findings (2): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/205713
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (1 Unrelated Failure)As of commit 6c9000f with merge base 4004f7e ( NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
Addressing bot comments:
|
|
@pytorchbot review |
There was a problem hiding this comment.
Automated review of 6c9000f: nothing blocking; ready for human review.
The PR moves ideep's batchnorm (inference, training, backward) and layernorm forward into aten/src/ATen/native/mkldnn/detail/, switches the Normalization.cpp call sites to them, and adds a frozen-graph layernorm test. Recommendation: Approve. Every earlier blocking concern is resolved or answered, and the two remaining points are non-blocking test improvements.
⚪ 2 non-blocking findings
Line 1037 in 6c9000f
Non-blocking: only the in-place layernorm path is tested. In Conv2d -> LayerNorm -> Conv2d, the layernorm is the only user of the first conv's output, so InplaceMKLDNNSubgraph renames the node to prim::MKLDNNLayerNorm_ (registered as MKLDNNLayerNormOp(stack, true)). Only the out_it = input_it branch at Normalization.cpp:123 runs. The out-of-place case, where mkldnn::layer_normalization_forward gets a newly allocated dst separate from src, never runs. FileCheck().check("prim::MKLDNNLayerNorm") is a substring match, so it can't tell which op ran. Suggested fix: check for prim::MKLDNNLayerNorm_ explicitly. To also cover the out-of-place path, keep the first conv's output alive past the layernorm, for example by adding it into the result.
Line 1025 in 6c9000f
Non-blocking: the Dynamo skip doesn't name a failure. The reason in @ skipIfTorchDynamo("TorchScript graph pass") names no crash, hang or flakiness, which the checklist's "Prefer xfail over skip" item asks for. The only other skipIfTorchDynamo in the file (:1449) links an issue, and xfailIfTorchDynamo is already imported. Pick one: drop the decorator if the test passes under Dynamo; use @ xfailIfTorchDynamo if it fails deterministically; otherwise, name the crash or hang in the reason.
This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review
| mod[1].weight.uniform_(0.5, 1.5) | ||
| mod[1].bias.uniform_(-0.5, 0.5) | ||
| scripted_mod = torch.jit._freeze.freeze(torch.jit._script.script(mod)) | ||
| torch._C._jit_pass_convert_frozen_ops_to_mkldnn(scripted_mod.graph) |
There was a problem hiding this comment.
Torchscript is being deleted. No need to add test for this as thi will be deleted soon.
You can remove this before merging.
|
Starting merge as part of PR stack under #205717 |
## 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
## 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
## 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
## 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
Stack from ghstack (oldest at bottom):
sum,binary, anddirect_copyops from ideep into ATen #205710Linked 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.
cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01 @gujinghui @PenghuiCheng @jianyuh @min-jean-cho @yanbing-j @Guobing-Chen @Xia-Weiwen @snadampal