Skip to content

[mkldnn][17/N] Port ideep's primitive cache and attr_t into ATen - #205977

Closed
frost-intel wants to merge 4 commits into
gh/frost-intel/15/basefrom
gh/frost-intel/15/head
Closed

frost-intel wants to merge 4 commits into
gh/frost-intel/15/basefrom
gh/frost-intel/15/head

Conversation

@frost-intel

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

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Linked issue or supporting maintainer

Part of #154444
Supported by @albanD

BC-breaking?

No

Summary (human written only)

This PR ports oneDNN primitive cache and attr_t from ideep to ATen, as well as renames for uses within ATen.

Tests verified the same number of cache-misses for a fixed workload with A/B testing.

Agent details (if applicable)

Developed with assistance from Claude Opus 5.5.

Three parts, each line-for-line with no behavior change:

  1. Primitive cache. detail/PrimitiveCache.h ports ideep::utils::lru_cache, computation_cache and the to_bytes/create_key key builders. Behavior is unchanged: one thread-local store per descriptor type, capacity 1024 (1 on aarch64), overridable with LRU_CACHE_CAPACITY, and byte-identical keys. The conv, deconv, inner-product and matmul ports, plus clear_computation_cache, now use it. The ideep store is no longer used by ATen.
  2. Attr alias. Mechanical rename of ideep::attr_t to at::native::mkldnn::Attr (233 uses).
  3. Attr class. detail/Attr.h ports ideep::attr_t: the constructors ATen uses, deep-copy assignment, scale/zero-point storage, has_op_kind, non_negative_output (ideep spells it non_negitive_output), to_bytes, and the 15 factory helpers ATen uses. Unused helpers and constructors are not ported. ideep's note in to_bytes saying scales and zero points are not encoded is out of date (they are), so it is rewritten to list what is actually left out. A conversion to ideep::attr_t that carries the scale and zero-point maps remains until ideep::tensor is ported (21/N), because its reorders still take ideep::attr_t.

Testing:

  • oneDNN verbose logs before vs. after are identical for test_mkldnn, quantized conv/deconv/linear, and the fp matmul tests. The cache-miss probes for quantized linear/deconv and the fp32 matmul probe also give bitwise-equal outputs.
  • Per-op primitive-descriptor cache-miss counts are identical before vs. after, at the default capacity and with LRU_CACHE_CAPACITY=1.
  • A standalone probe checks that Attr and ideep::attr_t produce byte-identical cache keys for every factory and constructor ATen uses, and that copying and conversion keep scales and zero points.

Previously submitted as #204801.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 21, 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 ports ideep's primitive cache (lru_cache, computation_cache,
to_bytes/create_key) and ideep::attr_t into ATen as detail/PrimitiveCache.h and
detail/Attr.h, and moves every ATen use to at::native::mkldnn::Attr. The review
recommends Approve and found no blocking problems. Every point it raises is
labeled non-blocking, mostly hazards inherited from ideep.

Findings (9):

[minor] aten/src/ATen/native/mkldnn/detail/Attr.h:284
Non-blocking: `Attr::operator=` overwrites `scales_` and `zero_points_` only
when `rhs` has them. Assigning a plain attr onto one that already holds scales
leaves the old maps in place. Those stale maps then feed `to_bytes` (the
primitive-cache key) and `operator ideep::attr_t()` (the reorder scales), so the
cache key and reorders would disagree with the real oneDNN handle. No current
caller hits this: the reassignments in Conv.cpp:129/132, Matmul.cpp:37/301 and
InnerProduct.cpp:105 all run on a fresh object. Reordering any one of them would
make it a silent bug. Fix: reset the maps (`scales_.reset()` /
`zero_points_.reset()`) when `rhs` has none.

[minor] aten/src/ATen/native/mkldnn/detail/PrimitiveCache.h:171
Non-blocking: `LRU_CACHE_CAPACITY` is checked for being positive only under
`#ifndef NDEBUG`. In release builds, a value of 0 or a non-numeric value calls
`resize(0)`. `insert` then pushes the node, the trim loop pops it, and `insert`
returns `vlist_.begin()`, which equals `end()`. `fetch_or_create` dereferences
that iterator: undefined behaviour, most likely a crash. A negative value wraps
to a huge `size_t`, so the cache becomes unbounded. Fix: read the variable with
`c10::utils::get_env` (c10/util/env.h) instead of `std::getenv`, parse it once,
and `TORCH_CHECK(capacity > 0, ...)` in all builds.

[minor] aten/src/ATen/native/mkldnn/detail/Attr.h:379
Non-blocking: this note is stale. It says scales and zero points are "not
encoded so far" and that the cache is "supposed to use in convolution only".
Lines 354-370 do encode scales and zero points, and the cache now also serves
deconv, inner product and matmul.

[minor] aten/src/ATen/native/mkldnn/detail/Attr.h:266
Non-blocking: `non_negitive_output` is a typo. It is new ATen API with one
caller (detail/Conv.cpp:72), so renaming it now is cheap.

[minor] aten/src/ATen/native/mkldnn/detail/Attr.h:128
Non-blocking: `fuse_relu` is marked `// Deprecated`, yet every ATen relu call
site uses it (Utils.cpp, qlinear.cpp, qlinear_dynamic.cpp, qconv.cpp,
OpContext.h, OnednnUtils.h). Either move the callers to `fuse_relu_v2` or drop
the label. The same applies to `fuse_gelu` (line 140), which Utils.cpp:131 uses.

[minor] aten/src/ATen/native/mkldnn/detail/Attr.h:38
Non-blocking: lines 38 and 58-62 add implicit converting constructors.
`Attr(const dnnl::primitive_attr&)` shares the oneDNN handle instead of cloning
it, and it accepts an `ideep::attr_t` by slicing, which silently drops that
attr's scale and zero-point maps. `Attr(dnnl_fpmath_mode_t, ...)` lets a bare
`dnnl_fpmath_mode_*` enum convert silently wherever a `const Attr&` is expected.
Neither has a caller in aten/ or torch/csrc, and neither does `Attr(int arg, int
mask, const std::vector<float>&)` at line 41. That contradicts the description's
"Unused helpers are not ported." Fix: remove the unused constructors, or at
least mark them `explicit`.

[minor] aten/src/ATen/native/mkldnn/detail/PrimitiveCache.h:34
Non-blocking: this adds a second `lru_cache`.
aten/src/ATen/native/mkldnn/xpu/detail/LRUCache.h already provides a header-only
`at::native::onednn::lru_cache` with the same template signature and API
(find/insert/resize/clear/end). Consider moving that one somewhere shared and
using it for both CPU and XPU rather than keeping two copies.

(2 more not shown, see the review run)

Reviewed commit: 31e807f (NOT the current head 84794a9)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit 84794a9 with merge base 47eb5c6 (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: quantization release notes category labels Nov 21, 2026
@github-actions
github-actions Bot requested a review from albanD November 21, 2026 01:49
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Nov 21, 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 21, 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 of 31e807f: nothing blocking; ready for human review.

The PR ports ideep's primitive cache (lru_cache, computation_cache, to_bytes/create_key) and ideep::attr_t into ATen as detail/PrimitiveCache.h and detail/Attr.h, and moves every ATen use to at::native::mkldnn::Attr. The review recommends Approve and found no blocking problems. Every point it raises is labeled non-blocking, mostly hazards inherited from ideep.

⚪ 9 non-blocking findings

Attr& operator=(const Attr& rhs) {

Non-blocking: Attr::operator= overwrites scales_ and zero_points_ only when rhs has them. Assigning a plain attr onto one that already holds scales leaves the old maps in place. Those stale maps then feed to_bytes (the primitive-cache key) and operator ideep::attr_t() (the reorder scales), so the cache key and reorders would disagree with the real oneDNN handle. No current caller hits this: the reassignments in Conv.cpp:129/132, Matmul.cpp:37/301 and InnerProduct.cpp:105 all run on a fresh object. Reordering any one of them would make it a silent bug. Fix: reset the maps (scales_.reset() / zero_points_.reset()) when rhs has none.


}(std::getenv("LRU_CACHE_CAPACITY"));

Non-blocking: LRU_CACHE_CAPACITY is checked for being positive only under #ifndef NDEBUG. In release builds, a value of 0 or a non-numeric value calls resize(0). insert then pushes the node, the trim loop pops it, and insert returns vlist_.begin(), which equals end(). fetch_or_create dereferences that iterator: undefined behaviour, most likely a crash. A negative value wraps to a huge size_t, so the cache becomes unbounded. Fix: read the variable with c10::utils::get_env (c10/util/env.h) instead of std::getenv, parse it once, and TORCH_CHECK(capacity &gt; 0, ...) in all builds.


// not encoded so far. PD cache is supposed to use in convolution only

Non-blocking: this note is stale. It says scales and zero points are "not encoded so far" and that the cache is "supposed to use in convolution only". Lines 354-370 do encode scales and zero points, and the cache now also serves deconv, inner product and matmul.


bool non_negitive_output() const {

Non-blocking: non_negitive_output is a typo. It is new ATen API with one caller (detail/Conv.cpp:72), so renaming it now is cheap.


Non-blocking: fuse_relu is marked // Deprecated, yet every ATen relu call site uses it (Utils.cpp, qlinear.cpp, qlinear_dynamic.cpp, qconv.cpp, OpContext.h, OnednnUtils.h). Either move the callers to fuse_relu_v2 or drop the label. The same applies to fuse_gelu (line 140), which Utils.cpp:131 uses.


Attr(const dnnl::primitive_attr& other) : dnnl::primitive_attr(other) {}

Non-blocking: lines 38 and 58-62 add implicit converting constructors. Attr(const dnnl::primitive_attr&amp;) shares the oneDNN handle instead of cloning it, and it accepts an ideep::attr_t by slicing, which silently drops that attr's scale and zero-point maps. Attr(dnnl_fpmath_mode_t, ...) lets a bare dnnl_fpmath_mode_* enum convert silently wherever a const Attr&amp; is expected. Neither has a caller in aten/ or torch/csrc, and neither does Attr(int arg, int mask, const std::vector&lt;float&gt;&amp;) at line 41. That contradicts the description's "Unused helpers are not ported." Fix: remove the unused constructors, or at least mark them explicit.


Non-blocking: this adds a second lru_cache. aten/src/ATen/native/mkldnn/xpu/detail/LRUCache.h already provides a header-only at::native::onednn::lru_cache with the same template signature and API (find/insert/resize/clear/end). Consider moving that one somewhere shared and using it for both CPU and XPU rather than keeping two copies.


Non-blocking: this adds a class Attr in at::native::mkldnn that is unrelated to the existing at::native::onednn::Attr (xpu/detail/Attr.h:133). Two unrelated classes with the same name in sibling oneDNN backends will confuse readers.


inline void to_bytes(bytestring& bytes, const T arg) {

Non-blocking: the class overload to_bytes(bytestring&amp;, const T arg) takes its argument by value. Attr's copy constructor (Attr.h:34-36) goes through operator=, which runs dnnl_primitive_attr_clone and copies both maps. So every create_key(..., attr, ...) deep-clones the attr on every x86 forward, including cache hits (Conv.cpp:451, InnerProduct.cpp:60, Matmul.cpp:157/383/552, Deconv.cpp:53). Attr also has no move constructor or move assignment, so each std::move(op_attr) into the params structs clones too. This matches ideep, so it is not a regression. Changing the overload to const T&amp; alone does not compile: the unconstrained variadic to_bytes(bytestring&amp;, T&amp;&amp;, Ts&amp;&amp;...) with an empty pack would then win for rvalue class arguments such as weights.get_desc(), so it also needs a sizeof...(Ts) &gt; 0 constraint. Adding defaulted-style move operations to Attr would remove the copies on the params path.

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

@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 21, 2026
[ghstack-poisoned]
@frost-intel

Copy link
Copy Markdown
Collaborator Author

Addressing bot comments:

  • Fixed the stale to_bytes note and the non_negitive_output typo, and removed the unused constructors.
  • operator=, LRU_CACHE_CAPACITY handling and the to_bytes copies are kept as in ideep and noted as follow-ups, along with the Deprecated labels and sharing the LRU cache with XPU.
  • Attr is in at::native::mkldnn, separate from XPU's at::native::onednn::Attr.

[ghstack-poisoned]
@frost-intel frost-intel added the topic: not user facing topic category label Nov 23, 2026

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

Kk

@frost-intel

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 25, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

[ghstack-poisoned]
@frost-intel

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 3 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

@frost-intel

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

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

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/trunk Trigger trunk jobs on your pull request 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. release notes: quantization release notes category topic: not user facing topic 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.

4 participants