Skip to content

[MLIR] Align cacheValues and reverse-mode adjoint guards for load and store rules - #3247

Open
agourakis82 wants to merge 13 commits into
EnzymeAD:mainfrom
agourakis82:fix/mlir-reverse-cache-guards
Open

agourakis82 wants to merge 13 commits into
EnzymeAD:mainfrom
agourakis82:fix/mlir-reverse-cache-guards

Conversation

@agourakis82

@agourakis82 agourakis82 commented Sep 22, 2026 •

Copy link
Copy Markdown

November 26 refresh and MLIR validation

Integrated upstream main at 8fc3136ca458fff85e35b261bbdbddd8d6924513 (merge eb4bc456) and rebuilt the exact candidate against the LLVM/MLIR revision pinned by the current Enzyme MLIR workflow, 8823cdce1b565e01cb47f89c30f51a0e0ec32d6a (LLVM 24). The SDK source was clean before and after the build. The private SDK overlay used for the October validation was not needed.

The first test run on the refreshed merge revealed a regression in the existing unsupported_active_store.mlir test: an inactive LLVM pointer-vector value stored into duplicated memory could reach the vector null-value builder, which asserted. The follow-up commit bca98b9a materializes this null shadow as llvm.mlir.zero and adds a FileCheck assertion for the zero and its store. The active-pointer-vector diagnostic and inactive controls remain in the test. This preserves the intended distinction between active values requiring a differentiation model and constant values requiring a zero shadow.

Current validation

On x86-64 Linux, Ubuntu Clang 18.1.3, CMake 3.28.3, Release, assertions enabled in the LLVM/MLIR SDK:

  • Built mlir-opt, FileCheck, mlir-translate, enzymemlir-opt, enzymemlir-translate, and enzymemlir-type-tree-test.
  • Focused reverse-mode tests: 2 passed, including load_store_cache_guards.mlir and unsupported_active_store.mlir (89 excluded by the filter).
  • cmake --build /work/enzyme-build --parallel 6 --target check-enzymemlir: 244 passed, 1 expected failure, 1 unsupported, 0 unexpected failures, 246 discovered.
  • git diff --check passed, and the deployed candidate and two follow-up files were verified by SHA-256. The original unmodified-SDK failure and final passing logs were retained locally.

The local build enables MLIR and disables Clang integration, the bitcode loader, and Flang integration. A task-local linker search path supplied the system zlib runtime because the container lacked the development symlink. This is a native MLIR validation against the unmodified pinned SDK, not a substitute for the full upstream CI matrix. Hosted Actions and maintainer review remain pending.

OpenAI Codex assisted with the integration, build diagnosis, follow-up fix, tests, and description update. The previous October validation below is retained as historical context.


Fixes #3240.

Align the forward cache guards with the reverse load/store rules for LLVM, memref, and affine operations. Loads of mutable types no longer leave unused caches behind.

Register vector differentiation for supported numeric element types. Reject unsupported active vector elements before shadow creation, report a diagnostic, and propagate differentiation failure instead of asserting or silently omitting a derivative. Constant values remain exempt from this active-type check.

The regression tests cover cache guards, raw f32 shadow accumulation, unsupported Float8 and pointer vectors, and inactive controls.

Validation

The refreshed branch includes upstream ad5e418d157eb03094829230c80ddc06fb9198a3. Commit 6fbaeed9 was rebuilt and validated on the x86_64 cluster on October 10. The subsequent formatting-only update preserves its C++ token sequence:

  • Full MLIR suite: 213 passed, 1 expected failure (214 discovered).
  • Focused regression tests passed.
  • Float8 and pointer-vector reproducers exit with a diagnostic rather than aborting.
  • Removing shadow accumulation makes the negative-control check fail.
  • Independent source reviews completed with Kimi K3 and GPT-5.5.

Validation used LLVM/MLIR 62e30e3326d9b4e3948d242ccfee7aa4fc030ef3 with a private SDK overlay moving the OneShotAnalysisState constructor after its nested cache definitions. These results are not an unmodified-SDK CI pass. Upstream CI and maintainer review remain pending.

@wsmoses
wsmoses requested review from Pangoraw and pengmai September 23, 2026 14:15
Copilot AI lite review requested due to automatic review settings September 24, 2026 19:20
@agourakis82

Copy link
Copy Markdown
Author

Implemented both points as suggested by @pengmai:

  1. Implemented AutoDiffTypeInterface for VectorType in BuiltinAutoDiffTypeInterfaceImpl.cpp, delegating element-wise null value/add/conj to the underlying element type.
  2. In store rules across MemRef, Affine, and LLVM dialects, if an active value does not implement AutoDiffTypeInterface, emit a descriptive op->emitError() rather than silently skipping or crashing.
  3. Updated the test case to verify active vector stores compute reverse-mode derivatives.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Critical vector-model correctness and compilation issues remain, along with an LLVM cache-guard mismatch.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 6 High severity

Open (6)
What changed in this PR

This PR aligns MLIR reverse-mode cache handling for load/store operations and adds vector autodiff support with regression tests.

Changes:

  • Synchronizes mutable-load cache guards across LLVM, memref, and affine.
  • Replaces unsafe store interface casts.
  • Adds VectorType autodiff behavior and regression coverage.
File Summary
enzyme/​test/​MLIR/​ReverseMode/​load_store_cache_guards.mlir Adds load/store regression tests; coverage and check scoping need refinement.
enzyme/​Enzyme/​MLIR/​Implementations/​MemRefAutoDiffOpInterfaceImpl.cpp Updates memref load/store guards.
enzyme/​Enzyme/​MLIR/​Implementations/​LLVMAutoDiffOpInterfaceImpl.cpp Updates LLVM load/store handling; cache guarding remains incomplete.
enzyme/​Enzyme/​MLIR/​Implementations/​BuiltinAutoDiffTypeInterfaceImpl.cpp Adds vector autodiff modeling, with unresolved interface and type-validity issues.
enzyme/​Enzyme/​MLIR/​Implementations/​AffineAutoDiffOpInterfaceImpl.cpp Updates affine guards and removes an unused builder.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@agourakis82

Copy link
Copy Markdown
Author

Updated with fixes addressing the review comments:

  1. AutoDiffTypeInterface Completeness: Implemented zeroInPlace, isZero, and isZeroAttr for VectorTypeInterface.
  2. Method Signatures: Fixed isMutable(Type self) signature to match AutoDiffTypeInterface.td. Removed call to nonexistent isContainedIn.
  3. Batched Shadow Types: getShadowType now uses batchType(self, width) returning RankedTensorType for width > 1, ensuring no invalid nested tensor element types inside vectors.
  4. Element Type Support: Added handling for IntegerType and IndexType in createNullAttr.
  5. Cache Value Alignment: Aligned LLVM::StoreOp::cacheValues to guard address cache pushing with an AutoDiffTypeInterface check, matching MemRef and Affine store rules.
  6. Tests: Updated regression tests in load_store_cache_guards.mlir to verify vector reverse mode for both MemRef and LLVM dialects.

@agourakis82

Copy link
Copy Markdown
Author

Current head 81b656fb addresses the prior review items: VectorTypeInterface now implements the required AutoDiffTypeInterface methods, handles integer/index null attrs, uses batchType(self, width) for shadow types, has the corrected isMutable(Type self) signature, removes the nonexistent interface call, and aligns LLVM store cache guarding with the interface check. I also ran git diff --check origin/main...HEAD locally; it passes. A full lit run is blocked on my local checkout lacking llvm-lit/enzyme-opt, so I would appreciate a fresh maintainer/Copilot review on the updated head.

Demetrios Chiuratto Agourakis added 3 commits October 5, 2026 10:44
… store rules

Fixes EnzymeAD#3240.

- In LLVM, MemRef, and Affine LoadOpInterfaceReverse: mirror the adjoint's
  !iface.isMutable() requirement into cacheValues, preventing dangling address
  cache pushes when loading mutable types (e.g. pointers or nested memrefs).
- In LLVM, MemRef, and Affine StoreOpInterfaceReverse: use dyn_cast instead
  of cast for AutoDiffTypeInterface in createReverseModeAdjoint, avoiding
  assertion failures or popCache on empty caches when the stored type does
  not implement AutoDiffTypeInterface (such as VectorType).
- Remove unused OpBuilder cacheBuilder in AffineStoreOpInterfaceReverse.
- Add regression tests in enzyme/test/MLIR/ReverseMode/load_store_cache_guards.mlir.
…odel

- Implement missing AutoDiffTypeInterface methods: zeroInPlace, isZero, isZeroAttr
- Fix isMutable parameter signature to match interface definition (bool isMutable(Type self))
- Remove call to non-existent isContainedIn interface method
- Fix getShadowType to return RankedTensorType for width > 1 (batchType) avoiding invalid nested tensors
- Add IntegerType and IndexType support to VectorType createNullAttr
- In LLVM StoreOp::cacheValues, guard cache pushes with AutoDiffTypeInterface check matching MemRef/Affine rules
- Update test cases in load_store_cache_guards.mlir with modern MLIR syntax and verify reverse vector stores for both MemRef and LLVM dialects
@agourakis82
agourakis82 force-pushed the fix/mlir-reverse-cache-guards branch from 81b656f to 9340019 Compare October 5, 2026 14:01
@agourakis82

Copy link
Copy Markdown
Author

Quick update: I rebased this branch onto current main (3cd66b79). The new head is 9340019f, and git diff --check origin/main...HEAD passes locally.

This head keeps the fixes for the earlier review points: the VectorType model implements the required AutoDiffTypeInterface hooks, handles index elements, uses a legal batched shadow type, has the corrected isMutable(Type self) signature, removes the nonexistent interface call, and mirrors the LLVM store cache guard.

I still do not have a local llvm-lit / enzyme-opt setup wired in this checkout, so I am not claiming a full MLIR lit run from my side after the rebase.

@agourakis82

Copy link
Copy Markdown
Author

I now have the local MLIR setup working. On a7bfd413, using the LLVM revision pinned in enzyme-mlir.yml (018a9e4a), check-enzymemlir reports 211 passed and 1 expected failure, with no unexpected failures. This was a Release build with assertions on macOS arm64. The focused load_store_cache_guards.mlir regression also passes; the latest commit fixes its activity-attribute/property syntax for the pinned MLIR version.

The MLIR workflow is awaiting maintainer approval. Could someone approve the pending runs so we can check the Linux CI matrix too?

Separately, the Bazel run fails before any jobs start with No event triggers defined in on. Its workflow has the triggers commented out and is byte-for-byte identical to current main; this PR does not change it.

Validate active result and block-argument types before constructing their shadows, propagate failure in forward and reverse differentiation, and discard incomplete cached clones. Cover a Float8 active-store reproducer in both modes.

Assisted-by: Codex
Signed-off-by: Demetrios Agourakis <demetrios@agourakis.med.br>
@agourakis82
agourakis82 requested a review from a team October 9, 2026 21:48
Integrate ad5e418 without rewriting the
published reverse-cache-guard history. Preserve the active-vector preflight
and diagnostic, inactive-control and raw f32 shadow-accumulation regressions.

Rebuild the exact merged source with C++23 tools on the CPU cluster before
publication. Keep the private LLVM construction-order SDK overlay separate
from the Enzyme changes and do not claim an unmodified-SDK CI pass.
@agourakis82

Copy link
Copy Markdown
Author

I've refreshed the branch against main at ad5e418 and pushed 6fbaeed.

I rebuilt and tested the exact published tree on my x86_64 cluster: 213 MLIR tests passed, with 1 expected failure. Both focused regression tests passed. The Float8 and pointer-vector reproducers now emit diagnostics instead of aborting, and removing the f32 shadow accumulation makes the regression check fail as intended.

One qualification: this build used the private LLVM SDK construction-order workaround described in the PR, so it doesn't replace validation against the unmodified SDK in upstream CI.

The workflows are currently waiting for maintainer approval. Could you approve them when you have a chance? I'd appreciate another look at the vector interface and unsupported-active-type handling once CI has run.

Match the four diagnostic expressions reported by the upstream format job.
Only whitespace changes; conditions, string literals, and tests are unchanged.

Validate all 168 files in the workflow's scope using its pinned
clang-format 16.0.3 executable. Compare canonical formatting of all four
modified files against 6fbaeed before publication.
@agourakis82

Copy link
Copy Markdown
Author

The Julia 1.11 failure also occurs on main: earlier run and latest run both fail at kwrrules.jl:231, expecting NonConstantKeywordArgException but receiving no exception.

Both main jobs and this PR use Julia 1.11.9 and Enzyme.jl 69328019. All three builds report found MLIR 0; this PR changes only MLIR implementation and tests. This establishes that the same failure exists on main, not its internal cause. Could you review the MLIR changes separately from this Julia check?

@agourakis82

Copy link
Copy Markdown
Author

Update: Enzyme.jl #3819 has now merged as 49163145, directly after the 69328019 checkout used by the failing jobs. It adjusts this exact keyword-argument regression for Julia 1.11. Could you rerun the Julia 1.11 check with the updated Enzyme.jl checkout? I have not rerun it locally.

Active pointer vectors still diagnose unsupported differentiation. Exercise the zero shadow and its store for the inactive value with duplicated destination.

Assisted-by: OpenAI Codex

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MLIR: cacheValues / createReverseModeAdjoint guard mismatches in the load and store reverse rules

3 participants