Skip to content

Fix nested ForwardAccumulator results when intermediates are reused - #128029

Merged
copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
bhushanasati25:fix-nested-forward-accumulator
Sep 28, 2026
Merged

copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
bhushanasati25:fix-nested-forward-accumulator

Conversation

@bhushanasati25

Copy link
Copy Markdown

Summary

Fixes #127753.

Include the aliasing pattern of primal inputs and packed tangents in the
ConcreteFunction forward/backward function cache key.

JVP wrappers capture external tensors by identity. When several inputs refer to
the same tensor, the generated graph's capture mapping reflects that sharing.
Previously, the cache key included tangent indices but not tensor sharing, so a
later call with distinct tangents could reuse a graph built for shared tangents.
This produces incorrect derivatives, including the reported 2.4 instead of
4.2 for the nested forward derivative of (m * m) * m at x = 0.7.

The new key records normalized alias indices, not actual tensor IDs, so fresh
tensors with the same sharing pattern still reuse the generated functions. The
alias key is only computed when input tangents are present.

Regression coverage includes:

  • Switching between shared and distinct tangents in both orders, with and without
    an active reverse-mode tape, and checking cache reuse with fresh tensors.
  • Nested forward derivatives of reused identity, sine, and square intermediates
    in float32/float64, with eager and tf.function execution.
  • The reused matrix intermediate from the issue.

Validation

Local validation used Python 3.13 on macOS arm64 with
tf-nightly==2.22.0.dev20260923. The source test modules were loaded against the
installed runtime, with the exact edited
ConcreteFunction._select_forward_and_backward_functions method compiled from
the checkout and installed on the runtime class. This is not a full source build.

  • New regressions: 18 passed; 10 fail without the patch.
  • Source forwardprop_test.py: 93 passed, 4 skipped, 2 baseline failures out
    of 99. Both remaining failures occur with and without this patch:
    testNonTensorInputs and testShapeMismatchRaisesError. The Nightly wheel
    lacks the newer input-validation behavior expected by those source tests.
  • Source polymorphic_function/gradients_test.py: 42 passed, 2 skipped.
  • git diff --check: passed.

Bazel and GPU validation were not run locally. The relevant source-build targets
for CI are:

bazel test //tensorflow/python/eager:forwardprop_test \
  //tensorflow/python/eager/polymorphic_function:gradients_test

@google-ml-butler google-ml-butler Bot added size:M CL Change Size: Medium awaiting review Pull request awaiting review labels Sep 25, 2026

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request improves cache reuse for concrete functions under forward propagation by normalizing tensor IDs of inputs and tangents to create a stable cache key, and adds comprehensive tests to verify this behavior. The feedback suggests using itertools.chain instead of sequence concatenation when processing args and input_tangents.tangents to prevent potential TypeErrors and avoid unnecessary memory allocation.

Comment on lines +1599 to +1601
forwardprop_input_aliases = tuple(
tensor_indices.setdefault(ops.tensor_id(t), len(tensor_indices))
for t in args + input_tangents.tangents)

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.

medium

Concatenating args and input_tangents.tangents using the + operator can raise a TypeError if one is a list and the other is a tuple (e.g., TypeError: can only concatenate list (not "tuple") to list).\n\nUsing itertools.chain is more robust as it handles any combination of iterable types, and it is also more efficient because it avoids allocating a temporary concatenated list in memory.

      forwardprop_input_aliases = tuple(\n          tensor_indices.setdefault(ops.tensor_id(t), len(tensor_indices))\n          for t in itertools.chain(args, input_tangents.tangents))
References
  1. Ensure robustness by flagging fragile logic (such as potential TypeErrors from sequence concatenation) and optimizing performance by avoiding unnecessary memory allocations. (link)

@nithyak0204 nithyak0204 self-assigned this Sep 25, 2026
@nithyak0204
nithyak0204 requested a review from a team September 25, 2026 06:04
@nithyak0204 nithyak0204 added python Pull requests that update Python code prtype:bugfix PR to fix a bug labels Sep 25, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Sep 25, 2026

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

The internal presubmit tests have compiled cleanly and passed successfully. Code looks good to me! Approving.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 26, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 28, 2026
@copybara-service
copybara-service Bot merged commit 749b510 into tensorflow:master Sep 28, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

prtype:bugfix PR to fix a bug python Pull requests that update Python code 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.

Nested ForwardAccumulator returns a wrong second derivative in eager mode when an intermediate is reused as an operand

3 participants