Skip to content

Replace static recomputation op list with dynamic cost model - #109358

Merged
copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
ayushozha:feature/grappler-dynamic-recompute-cost-model
Jul 16, 2026
Merged

copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
ayushozha:feature/grappler-dynamic-recompute-cost-model

Conversation

@ayushozha

Copy link
Copy Markdown
Contributor

Summary

  • The Grappler memory optimizer used a hardcoded static list of "cheap to recompute" ops (GetCheapToRecomputeOps), which could not account for actual tensor sizes
  • Added IsCheapToRecompute() which uses OpLevelCostEstimator to dynamically estimate compute cost based on shape information from GraphProperties
  • Nodes with estimated compute time below 100 microseconds are considered cheap; falls back to the static list when shape inference fails or cost estimates are inaccurate
  • This resolves the long-standing TODO in the code: "Replace this list with a cost model"

Test plan

  • Element-wise ops with small tensors are still marked as cheap to recompute
  • Large tensor operations are no longer unconditionally marked as cheap
  • Static list fallback works correctly when shape inference fails
  • Existing memory optimizer tests continue to pass

Fixes #94653

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Feb 2, 2026
@keerthanakadiri keerthanakadiri added the comp:core issues related to core part of tensorflow label Feb 2, 2026
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Feb 2, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Feb 2, 2026
@keerthanakadiri

Copy link
Copy Markdown
Contributor

Hi @ayush10, Could you kindly try to resolve the conflicts? Thanks !

@keerthanakadiri keerthanakadiri added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Mar 2, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 14 days with no activity. It will be closed if no further activity occurs. Thank you.

@github-actions github-actions Bot added the stale This label marks the issue/pr stale - to be closed automatically if no activity label Mar 17, 2026
@ayushozha

Copy link
Copy Markdown
Contributor Author

Hi @ayush10, Could you kindly try to resolve the conflicts? Thanks !

Hi, I was busy with hackathons, so I couldn't do it. Finishing it right now.

@google-ml-butler google-ml-butler Bot removed stale This label marks the issue/pr stale - to be closed automatically if no activity stat:awaiting response Status - Awaiting response from author labels Mar 18, 2026
@ayushozha
ayushozha force-pushed the feature/grappler-dynamic-recompute-cost-model branch from b278456 to 4d1862b Compare March 18, 2026 08:06
@ayushozha

Copy link
Copy Markdown
Contributor Author

Resolved merge conflicts by rebasing onto latest master.

@ayushozha
ayushozha force-pushed the feature/grappler-dynamic-recompute-cost-model branch 2 times, most recently from e91c9bd to a86790d Compare March 18, 2026 09:47
@ayushozha

Copy link
Copy Markdown
Contributor Author

@googlebot I signed it!

…y optimizer

The Grappler memory optimizer previously used a hardcoded list of "cheap
to recompute" ops (GetCheapToRecomputeOps). This was inadequate because
it could not account for actual tensor sizes -- e.g. a Tile op on a
small tensor is cheap, but on a large tensor it is expensive.

This change adds IsCheapToRecompute() which uses OpLevelCostEstimator
to dynamically estimate the compute cost of each candidate node based on
its shape information from GraphProperties. Nodes with estimated compute
time below 100 microseconds are considered cheap to recompute. When shape
inference fails or the cost estimate is marked inaccurate, the function
falls back to the original static op list.

Fixes tensorflow#94653
@ayushozha
ayushozha force-pushed the feature/grappler-dynamic-recompute-cost-model branch from a86790d to 3e3bd03 Compare March 18, 2026 22:31
@keerthanakadiri keerthanakadiri added the awaiting review Pull request awaiting review label Mar 30, 2026
@dmiltr3
dmiltr3 self-requested a review June 29, 2026 00:19

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

Thanks for the PR! This is a great improvement to make the recomputation decisions dynamic based on estimated execution costs.

However, during verification against the TensorFlow test suites, we identified a critical design defect in the IsCheapToRecompute implementation that causes test regressions (e.g., Attempting to use uninitialized value Recomputed/filter and scope matching errors).


Core Finding & Fix

The Issue:
In the proposed implementation of IsCheapToRecompute, if input shape properties are available and the cost model successfully predicts a cost (!costs.inaccurate), the function evaluates:
return costs.compute_time.count() < kRecomputeCostThresholdNs;

This check returns true for any operation that is cheap, regardless of its operation type. As a result, safe-guards are bypassed for non-recomputable ops (e.g., stateful ops, variable reads like VariableV2 or weights, and helper ops), marking them for recomputation which is invalid.

The Solution:
We must restrict dynamic cost estimation specifically to operations in the static GetCheapToRecomputeOps() list. The dynamic cost estimation should decide whether a candidate op is cheap enough to recompute, rather than opening recomputation to any arbitrary op under the cost threshold.

Here is the updated implementation of IsCheapToRecompute that resolves this issue:

bool IsCheapToRecompute(
    const NodeDef& node,
    const GraphProperties& properties,
    const std::unordered_map<std::string, const NodeDef*>& name_to_node,
    const OpLevelCostEstimator& estimator) {
  // Only evaluate ops that are in the static cheap ops list.
  if (GetCheapToRecomputeOps().count(node.op()) == 0) {
    return false;
  }

  // Try dynamic cost estimation if input properties are available.
  if (properties.HasInputProperties(node.name())) {
    const auto& input_properties = properties.GetInputProperties(node.name());
    OpInfo op_info =
        BuildOpInfoWithoutDevice(node, name_to_node, input_properties);
    OpContext op_context;
    op_context.name = node.name();
    op_context.op_info = op_info;
    Costs costs = estimator.PredictCosts(op_context);
    if (!costs.inaccurate) {
      return costs.compute_time.count() < kRecomputeCostThresholdNs;
    }
  }

  // Fallback to static list (which we already checked) for ops without
  // reliable cost estimates.
  return true;
}

Unit Verification

To protect this behavior, we added a C++ unit test in tensorflow/core/grappler/optimizers/memory_optimizer_test.cc. This test verifies that:

  1. A small Relu op (e.g., shape {2, 3, 4}) is successfully recomputed because its dynamic cost is below the 100 microseconds threshold.
  2. A large Relu op (e.g., shape {1000, 1000}) with 1M elements is not recomputed because its dynamic cost exceeds the threshold.

Please add the following test case:

TEST_F(RecomputeSubgraphTest, DynamicHeuristicRecomputation) {
  // 1. Small Tensor: Should be recomputed because compute cost is under
  // threshold.
  {
    tensorflow::Scope s = tensorflow::Scope::NewRootScope();
    Output a = ops::Variable(s.WithOpName("a"), {2, 3, 4}, DT_FLOAT);
    Output b = ops::Identity(s.WithOpName("b"), a);
    Output c = ops::AddN(s.WithOpName("gradients/c"), {b});

    GrapplerItem item;
    TF_CHECK_OK(s.ToGraphDef(&item.graph));
    NodeMap pre_transform_node_map(&item.graph);
    // Change op type to one listed in GetCheapToRecomputeOps
    pre_transform_node_map.GetNode("b")->set_op("Relu");

    MemoryOptimizer optimizer(RewriterConfig::RECOMPUTATION_HEURISTICS);
    GraphDef output;
    TF_EXPECT_OK(optimizer.Optimize(nullptr, item, &output));

    NodeMap post_transform_node_map(&output);
    EXPECT_NE(post_transform_node_map.GetNode("Recomputed/b"), nullptr);
  }

  // 2. Large Tensor: Should NOT be recomputed because compute cost exceeds
  // threshold.
  {
    tensorflow::Scope s = tensorflow::Scope::NewRootScope();
    Output a = ops::Variable(s.WithOpName("a"), {1000, 1000}, DT_FLOAT);
    Output b = ops::Identity(s.WithOpName("b"), a);
    Output c = ops::AddN(s.WithOpName("gradients/c"), {b});

    GrapplerItem item;
    TF_CHECK_OK(s.ToGraphDef(&item.graph));
    NodeMap pre_transform_node_map(&item.graph);
    // Change op type to one listed in GetCheapToRecomputeOps
    pre_transform_node_map.GetNode("b")->set_op("Relu");

    MemoryOptimizer optimizer(RewriterConfig::RECOMPUTATION_HEURISTICS);
    GraphDef output;
    TF_EXPECT_OK(optimizer.Optimize(nullptr, item, &output));

    NodeMap post_transform_node_map(&output);
    EXPECT_EQ(post_transform_node_map.GetNode("Recomputed/b"), nullptr);
  }
}

Please update the pull request with these corrections and the new unit test. Let us know when it's updated!

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Jun 29, 2026
@keerthanakadiri keerthanakadiri added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Jun 29, 2026
@ayushozha

Copy link
Copy Markdown
Contributor Author

@dmiltr3 Updated this PR to address the recomputation-safety issue from your review.

What changed:

  • IsCheapToRecompute now first rejects ops not in GetCheapToRecomputeOps() before consulting the dynamic cost estimator
  • dynamic cost estimation now only decides whether an already-allowlisted op is cheap enough, instead of allowing arbitrary low-cost ops
  • added DynamicHeuristicRecomputation coverage for:
    • a non-allowlisted cheap Identity op not being recomputed
    • a small allowlisted Relu being recomputed
    • a large allowlisted Relu not being recomputed when estimated over the threshold

Validation performed locally:

  • git diff --check origin/master...HEAD
  • reviewed final PR diff: memory_optimizer.cc, memory_optimizer_test.cc, and the existing BUILD dependency additions
  • secret/path sanity check on changed filenames

I could not run the Bazel target locally because bazel is not installed on this Windows host.

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Jul 5, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 July 9, 2026 03:40
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 9, 2026
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Jul 14, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Jul 14, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Jul 14, 2026
@copybara-service
copybara-service Bot merged commit 27c8704 into tensorflow:master Jul 16, 2026
17 of 18 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Jul 16, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Jul 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:core issues related to core part of tensorflow ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

Enhance Memory Optimizer with Dynamic Cost Model for Operation Recomputation

6 participants