← Back to Pull requests

[mlir] Multi-result reverse mode tablegen implementation #3538

Open
Pangoraw opened this pull request with 185 lines diff across 4 files
View on GitHub
Pangoraw Pangoraw commented on Oct 30, 2026 08:48 UTC
Author

No description provided by author.

Diff: 185 lines (+172 / -13) across 4 files Reviewer: ftynse Review duration: 9294m
All Vouch review confidence checks passed
Residual risk 0.04 = Change Risk (0.39) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.39 · 185 lines diff across 4 files
0.39
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.88 · 5 substantive comment(s)
0.88
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
90%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.313
Empty Description empty_description
0.060
Real PR Conversation Timeline
15 items
ftynse ftynse commented on code on Oct 30, 2026 10:23 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1664,6 +1673,10 @@ void printDiffUse(
   }
 }
 
+static constexpr const char *allResultsInactiveMLIR =

Use llvm::StringLiteral

ftynse ftynse commented on code on Oct 30, 2026 10:24 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {
+  const Record *Def = nullptr;

Be consistent about CamelCase and camelBack

ftynse ftynse commented on code on Oct 30, 2026 10:25 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {

Why hardcode the 2 smallset size?

ftynse ftynse commented on code on Oct 30, 2026 10:27 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {
+  const Record *Def = nullptr;
+  auto resultRoot = dyn_cast<DagInit>(init);
+  if (resultRoot)
+    Def = cast<DefInit>(resultRoot->getOperator())->getDef();
+  else if (auto DefArg = dyn_cast<DefInit>(init))
+    Def = DefArg->getDef();
+  if (Def && Def->isSubClassOf("DiffeRetIndex")) {
+    auto index = Def->getValueAsInt("index");
+    if (index < -1)
+      PrintFatalError(pattern->getLoc(),
+                      "DiffeRetIndex takes a result index or -1");
+    results.insert(index == -1 ? 0 : index);

Why do we need this dance with -1 instead of just using 0 for DiffeRet? Or is -1 somehow intended to mean "all results", which it doesn't here.

ftynse ftynse commented on code on Oct 30, 2026 10:28 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {
+  const Record *Def = nullptr;
+  auto resultRoot = dyn_cast<DagInit>(init);
+  if (resultRoot)
+    Def = cast<DefInit>(resultRoot->getOperator())->getDef();
+  else if (auto DefArg = dyn_cast<DefInit>(init))
+    Def = DefArg->getDef();
+  if (Def && Def->isSubClassOf("DiffeRetIndex")) {
+    auto index = Def->getValueAsInt("index");
+    if (index < -1)
+      PrintFatalError(pattern->getLoc(),
+                      "DiffeRetIndex takes a result index or -1");
+    results.insert(index == -1 ? 0 : index);
+    return;
+  }
+  if (resultRoot)
+    for (auto arg : resultRoot->getArgs())
+      collectDiffeRetResults(pattern, arg, results);
+}
+
 static void emitReverseCommon(raw_ostream &os, const Record *pattern,
                               const DagInit *tree, ActionType intrinsic,
                               StringRef origName, const ListInit *argOps) {
   auto nameToOrdinal = parseVariables(tree, intrinsic, origName);
 
+  // Each adjoint read by the rule is loaded into difs, and an active result
+  // that no rule reads is refused below rather than having its adjoint dropped.
+  std::string usedResults;
+  bool readsAdjoint = false;
+  if (intrinsic == MLIRDerivatives) {
+    SmallSet<unsigned, 2> results;
+    for (auto arg : *argOps)
+      collectDiffeRetResults(pattern, arg, results);
+    SmallVector<unsigned, 2> sorted(results.begin(), results.end());

Thou shalt not hardcode SmallVector stack size without reason.

ftynse ftynse commented on code on Oct 30, 2026 10:29 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {
+  const Record *Def = nullptr;
+  auto resultRoot = dyn_cast<DagInit>(init);
+  if (resultRoot)
+    Def = cast<DefInit>(resultRoot->getOperator())->getDef();
+  else if (auto DefArg = dyn_cast<DefInit>(init))
+    Def = DefArg->getDef();
+  if (Def && Def->isSubClassOf("DiffeRetIndex")) {
+    auto index = Def->getValueAsInt("index");
+    if (index < -1)
+      PrintFatalError(pattern->getLoc(),
+                      "DiffeRetIndex takes a result index or -1");
+    results.insert(index == -1 ? 0 : index);
+    return;
+  }
+  if (resultRoot)
+    for (auto arg : resultRoot->getArgs())
+      collectDiffeRetResults(pattern, arg, results);
+}
+
 static void emitReverseCommon(raw_ostream &os, const Record *pattern,
                               const DagInit *tree, ActionType intrinsic,
                               StringRef origName, const ListInit *argOps) {
   auto nameToOrdinal = parseVariables(tree, intrinsic, origName);
 
+  // Each adjoint read by the rule is loaded into difs, and an active result
+  // that no rule reads is refused below rather than having its adjoint dropped.
+  std::string usedResults;
+  bool readsAdjoint = false;
+  if (intrinsic == MLIRDerivatives) {
+    SmallSet<unsigned, 2> results;
+    for (auto arg : *argOps)
+      collectDiffeRetResults(pattern, arg, results);
+    SmallVector<unsigned, 2> sorted(results.begin(), results.end());
+    llvm::sort(sorted);
+    usedResults = "{" +
+                  llvm::join(llvm::map_range(sorted,
+                                             [](unsigned i) {
+                                               return std::to_string(i) + "u";
+                                             }),
+                             ", ") +
+                  "}";

This is highly inefficient due to excessive dynamic allocation in std string concatenation. Use raw_string_ostream instead.

ftynse ftynse commented on code on Oct 30, 2026 10:30 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {
+  const Record *Def = nullptr;
+  auto resultRoot = dyn_cast<DagInit>(init);
+  if (resultRoot)
+    Def = cast<DefInit>(resultRoot->getOperator())->getDef();
+  else if (auto DefArg = dyn_cast<DefInit>(init))
+    Def = DefArg->getDef();
+  if (Def && Def->isSubClassOf("DiffeRetIndex")) {
+    auto index = Def->getValueAsInt("index");
+    if (index < -1)
+      PrintFatalError(pattern->getLoc(),
+                      "DiffeRetIndex takes a result index or -1");
+    results.insert(index == -1 ? 0 : index);
+    return;
+  }
+  if (resultRoot)
+    for (auto arg : resultRoot->getArgs())
+      collectDiffeRetResults(pattern, arg, results);
+}
+
 static void emitReverseCommon(raw_ostream &os, const Record *pattern,
                               const DagInit *tree, ActionType intrinsic,
                               StringRef origName, const ListInit *argOps) {
   auto nameToOrdinal = parseVariables(tree, intrinsic, origName);
 
+  // Each adjoint read by the rule is loaded into difs, and an active result
+  // that no rule reads is refused below rather than having its adjoint dropped.
+  std::string usedResults;
+  bool readsAdjoint = false;
+  if (intrinsic == MLIRDerivatives) {
+    SmallSet<unsigned, 2> results;
+    for (auto arg : *argOps)
+      collectDiffeRetResults(pattern, arg, results);
+    SmallVector<unsigned, 2> sorted(results.begin(), results.end());
+    llvm::sort(sorted);
+    usedResults = "{" +
+                  llvm::join(llvm::map_range(sorted,
+                                             [](unsigned i) {
+                                               return std::to_string(i) + "u";
+                                             }),
+                             ", ") +
+                  "}";
+    readsAdjoint = !results.empty();
+    if (readsAdjoint) {
+      os << "        if (" << origName
+         << "->getNumResults() <= " << sorted.back() << ")\n";
+      os << "          return " << origName
+         << "->emitError() << \"Derivative rule reads the adjoint of result "

Error messages should start from a lower case

ftynse ftynse commented on code on Oct 30, 2026 10:32 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {
+  const Record *Def = nullptr;
+  auto resultRoot = dyn_cast<DagInit>(init);
+  if (resultRoot)
+    Def = cast<DefInit>(resultRoot->getOperator())->getDef();
+  else if (auto DefArg = dyn_cast<DefInit>(init))
+    Def = DefArg->getDef();
+  if (Def && Def->isSubClassOf("DiffeRetIndex")) {
+    auto index = Def->getValueAsInt("index");
+    if (index < -1)
+      PrintFatalError(pattern->getLoc(),
+                      "DiffeRetIndex takes a result index or -1");
+    results.insert(index == -1 ? 0 : index);
+    return;
+  }
+  if (resultRoot)
+    for (auto arg : resultRoot->getArgs())
+      collectDiffeRetResults(pattern, arg, results);
+}
+
 static void emitReverseCommon(raw_ostream &os, const Record *pattern,
                               const DagInit *tree, ActionType intrinsic,
                               StringRef origName, const ListInit *argOps) {
   auto nameToOrdinal = parseVariables(tree, intrinsic, origName);
 
+  // Each adjoint read by the rule is loaded into difs, and an active result
+  // that no rule reads is refused below rather than having its adjoint dropped.
+  std::string usedResults;
+  bool readsAdjoint = false;
+  if (intrinsic == MLIRDerivatives) {
+    SmallSet<unsigned, 2> results;
+    for (auto arg : *argOps)
+      collectDiffeRetResults(pattern, arg, results);
+    SmallVector<unsigned, 2> sorted(results.begin(), results.end());
+    llvm::sort(sorted);
+    usedResults = "{" +
+                  llvm::join(llvm::map_range(sorted,
+                                             [](unsigned i) {
+                                               return std::to_string(i) + "u";
+                                             }),
+                             ", ") +
+                  "}";
+    readsAdjoint = !results.empty();
+    if (readsAdjoint) {
+      os << "        if (" << origName
+         << "->getNumResults() <= " << sorted.back() << ")\n";
+      os << "          return " << origName
+         << "->emitError() << \"Derivative rule reads the adjoint of result "
+         << sorted.back() << " of op \" << *" << origName << " << \"\\n\";\n";

I'd highly suggest combining a raw string literal with formatv here, can't parse all the backslash escaping...

Pangoraw Pangoraw commented on code on Oct 30, 2026 11:28 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {

Moved to a SetVector since we need the vector afterwards.

Pangoraw Pangoraw commented on code on Oct 30, 2026 11:29 UTC
Code Review
enzyme/tools/enzyme-tblgen/enzyme-tblgen.cpp:1
@@ -1772,11 +1785,62 @@ static void emitMLIRReverse(raw_ostream &os, const Record *pattern,
     os << "        (void)dif;\n";
 }
 
+// Collects the op results whose adjoints an MLIR rule reads.
+static void collectDiffeRetResults(const Record *pattern, const Init *init,
+                                   SmallSet<unsigned, 2> &results) {
+  const Record *Def = nullptr;
+  auto resultRoot = dyn_cast<DagInit>(init);
+  if (resultRoot)
+    Def = cast<DefInit>(resultRoot->getOperator())->getDef();
+  else if (auto DefArg = dyn_cast<DefInit>(init))
+    Def = DefArg->getDef();
+  if (Def && Def->isSubClassOf("DiffeRetIndex")) {
+    auto index = Def->getValueAsInt("index");
+    if (index < -1)
+      PrintFatalError(pattern->getLoc(),
+                      "DiffeRetIndex takes a result index or -1");
+    results.insert(index == -1 ? 0 : index);

This is an artifact of the llvm DiffeRetIndex where -1 is a sentinel that signifies the result value whereas in mlir the result could always be considered a tuple. I removed it.

wsmoses wsmoses commented on Oct 30, 2026 12:38 UTC
Contributor

so @Antipath1 and I talked about this the other week during the weekly enzyme call and came up with a slightly different array of array design

Pangoraw Pangoraw commented on Nov 03, 2026 17:15 UTC
Author

Could you give more details or have a draft somewhere?

Antipath1 Antipath1 commented on Nov 03, 2026 23:15 UTC
Contributor

Could you give more details or have a draft somewhere?

I did not really write down anything. From my recollection of the meeting (@wsmoses, correct me if I forgot something): for an op with several results, the reverse rule should be an array of arrays. The outer array has one entry per result, so [i][j] is result i’s contribution to operand j, with (DiffeRet) in row i meaning result i’s adjoint. The generated code only evaluates the rows of active results and sums them per operand, so inactive results never produce a term.

For sincos (one operand, two results):

[
  [ (CheckedMulF (DiffeRet), (CosF $x)) ],          // sin
  [ (NegF (CheckedMulF (DiffeRet), (SinF $x))) ]    // cos
]

The design matters a bit more for ops with multiple arguments and return values. For example, (r, θ) -> (x, y) = (r·cos θ, r·sin θ) has a full 2*2 table, one row per result:
[
  [ dx·cos θ,  -dx·r·sin θ ],   // x = r·cos θ
  [ dy·sin θ,   dy·r·cos θ ]    // y = r·sin θ
]

Single-result rules stay as they are (a flat list is the one-row case). Idk if that is the final syntax of this that we would want, but like along these lines. We basically want to avoid multiplying by 0 in the case of an inactive result.

For this to work, we would probably also need to have the number of return values (we already have the number of operands).

Happy to implement it myself if that is easier.

ftynse ftynse commented on Nov 04, 2026 09:52 UTC
Contributor

with (DiffeRet) in row i meaning result i’s adjoint.

This is reasonable to avoid accidentally referencing irrelevant adjoints. However, we'd better have detailed error messages to check that we have the right array-of-arrays structure.

Reviewers
Assignees
Pangoraw Pangoraw
Labels
risk: low confidence: 90.1% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 38.6% (MEDIUM) · Higher = larger blast radius
38.6%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 90.1% · Lower = rushed or shallow review
90.1%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 3.8% · Safe to merge
3.8%