-
Notifications
You must be signed in to change notification settings - Fork 225
Cache graph functions and add If gradient test #637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nfeybesse
wants to merge
1
commit into
tensorflow:master
Choose a base branch
from
nfeybesse:custom/graph-function-cache
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+334
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
278 changes: 278 additions & 0 deletions
278
tensorflow-core/tensorflow-core-api/src/test/java/org/tensorflow/IfGradientTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,278 @@ | ||
| /* | ||
| Copyright 2026 The TensorFlow Authors. All Rights Reserved. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| ============================================================================== | ||
| */ | ||
| package org.tensorflow; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Iterator; | ||
| import java.util.List; | ||
| import java.util.stream.Collectors; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.tensorflow.op.Ops; | ||
| import org.tensorflow.op.core.Gradients; | ||
| import org.tensorflow.op.core.Placeholder; | ||
| import org.tensorflow.op.core.StatefulIf; | ||
| import org.tensorflow.op.core.StatefulPartitionedCall; | ||
| import org.tensorflow.op.core.StatelessIf; | ||
| import org.tensorflow.types.TBool; | ||
| import org.tensorflow.types.TFloat32; | ||
| import org.tensorflow.types.TInt32; | ||
| import org.tensorflow.types.family.TType; | ||
|
|
||
| public class IfGradientTest { | ||
|
|
||
| private static ConcreteFunction thenFn() { | ||
| return ConcreteFunction.create( | ||
| (Ops tf) -> { | ||
| Placeholder<TFloat32> x = tf.placeholder(TFloat32.class); | ||
| Operand<TFloat32> y = tf.math.mul(x, tf.constant(3.0f)); | ||
| return Signature.builder("thenBranch").input("x", x).output("y", y).build(); | ||
| }); | ||
| } | ||
|
|
||
| private static ConcreteFunction elseFn() { | ||
| return ConcreteFunction.create( | ||
| (Ops tf) -> { | ||
| Placeholder<TFloat32> x = tf.placeholder(TFloat32.class); | ||
| Operand<TFloat32> y = tf.math.mul(x, tf.constant(5.0f)); | ||
| return Signature.builder("elseBranch").input("x", x).output("y", y).build(); | ||
| }); | ||
| } | ||
|
|
||
| private static void assertClose(float got, float expected, float eps, String msg) { | ||
| if (Math.abs(got - expected) > eps) { | ||
| throw new AssertionError(msg + " (got=" + got + ", expected=" + expected + ")"); | ||
| } | ||
| } | ||
|
|
||
| private static void primeIfGradFunctions(Graph g) { | ||
|
|
||
| Iterator<GraphOperation> operations = g.operations(); | ||
| while (operations.hasNext()) { | ||
| GraphOperation op = operations.next(); | ||
| String type = op.type(); | ||
| if (!StatefulIf.OP_NAME.equals(type) && !StatelessIf.OP_NAME.equals(type)) continue; | ||
|
|
||
| ConcreteFunction thenFwd = op.attributes().getAttrFunction("then_branch"); | ||
| ConcreteFunction elseFwd = op.attributes().getAttrFunction("else_branch"); | ||
|
|
||
| int nInputs = op.inputListLength("input"); | ||
| int nOut = op.numOutputs(); | ||
|
|
||
| List<Class<? extends TType>> tin = new ArrayList<>(nInputs); | ||
| for (int i = 0; i < nInputs; i++) { | ||
| Class<? extends TType> c = op.input(1 + i).asOutput().type(); | ||
| tin.add(c); | ||
| } | ||
|
|
||
| List<Class<? extends TType>> tout = new ArrayList<>(nOut); | ||
| for (int i = 0; i < nOut; i++) { | ||
| Class<? extends TType> c = op.output(i).type(); | ||
| tout.add(c); | ||
| } | ||
|
|
||
| ConcreteFunction thenGrad = buildBranchGradFn(op.name() + "/then_grad", thenFwd, tin, tout); | ||
| ConcreteFunction elseGrad = buildBranchGradFn(op.name() + "/else_grad", elseFwd, tin, tout); | ||
|
|
||
| g.attachFunction(thenGrad); | ||
| g.attachFunction(elseGrad); | ||
| } | ||
| } | ||
|
|
||
| @SuppressWarnings({"rawtypes", "unchecked"}) | ||
| private static ConcreteFunction buildBranchGradFn( | ||
| String prefix, | ||
| ConcreteFunction branchFn, | ||
| List<Class<? extends TType>> tin, | ||
| List<Class<? extends TType>> toutForward) { | ||
|
|
||
| return ConcreteFunction.create( | ||
| (Ops tf) -> { | ||
| Signature.Builder sig = Signature.builder(prefix); | ||
|
|
||
| List<Operand<?>> x = new ArrayList<>(tin.size()); | ||
| for (int i = 0; i < tin.size(); i++) { | ||
| Placeholder<? extends TType> ph = tf.placeholder((Class) tin.get(i)); | ||
| x.add(ph); | ||
| sig.input("x" + i, ph); | ||
| } | ||
|
|
||
| List<Operand<?>> dy = new ArrayList<>(toutForward.size()); | ||
| for (int i = 0; i < toutForward.size(); i++) { | ||
| Placeholder<? extends TType> ph = tf.placeholder((Class) toutForward.get(i)); | ||
| dy.add(ph); | ||
| sig.input("dy" + i, ph); | ||
| } | ||
|
|
||
| StatefulPartitionedCall yCall = | ||
| StatefulPartitionedCall.create(tf.scope(), x, toutForward, branchFn); | ||
|
|
||
| Operand<?> L = tf.constant(0.0f); | ||
| for (int i = 0; i < toutForward.size(); i++) { | ||
| Operand<?> prod = tf.math.mul((Operand) yCall.output().get(i), (Operand) dy.get(i)); | ||
| L = tf.math.add((Operand) L, (Operand) sumAll(tf, prod)); | ||
| } | ||
|
|
||
| Gradients g = tf.gradients((Iterable) List.of((Operand) L), x); | ||
|
|
||
| for (int i = 0; i < tin.size(); i++) { | ||
| Operand<?> dx = g.dy(i); | ||
| sig.output("dx" + i, dx); | ||
| } | ||
|
|
||
| return sig.build(); | ||
| }); | ||
| } | ||
|
|
||
| @SuppressWarnings({"rawtypes", "unchecked"}) | ||
| private static Operand<?> sumAll(Ops tf, Operand<?> v) { | ||
| Operand<TInt32> r = tf.rank(v); | ||
| Operand<TInt32> axes = tf.range(tf.constant(0), r, tf.constant(1)); | ||
| return tf.reduceSum((Operand) v, axes); | ||
| } | ||
|
|
||
| @Test | ||
| public void testStatefullIfGradient() { | ||
| TensorFlow.registerCustomGradient( | ||
| StatefulIf.OP_NAME, | ||
| (tf, op, gradOutputs) -> { | ||
| OperationAttributeInspector attrs = op.attributes(); | ||
| ConcreteFunction thenBranch = attrs.getAttrFunction("then_branch"); | ||
| ConcreteFunction elseBranch = attrs.getAttrFunction("else_branch"); | ||
|
|
||
| if (thenBranch == null || elseBranch == null) { | ||
| int n = 1 + op.inputListLength("input"); | ||
| List<Operand<?>> no = new ArrayList<>(n); | ||
| for (int i = 0; i < n; i++) { | ||
| no.add(null); | ||
| } | ||
| return no; | ||
| } | ||
|
|
||
| Operand<? extends TType> cond = op.input(0); | ||
| int nInputs = op.inputListLength("input"); | ||
| List<Operand<?>> inputs = new ArrayList<>(nInputs); | ||
| for (int i = 0; i < nInputs; i++) { | ||
| inputs.add(op.input(1 + i)); | ||
| } | ||
|
|
||
| int nOut = op.numOutputs(); | ||
| List<Class<? extends TType>> toutForward = new ArrayList<>(nOut); | ||
| for (int i = 0; i < nOut; i++) { | ||
| toutForward.add(op.output(i).type()); | ||
| } | ||
|
|
||
| List<Class<? extends TType>> tin = | ||
| inputs.stream().map(input -> input.asOutput().type()).collect(Collectors.toList()); | ||
| List<Operand<?>> dys = new ArrayList<>(nOut); | ||
| for (int i = 0; i < nOut; i++) { | ||
| Operand<?> dy = null; | ||
| if (gradOutputs != null && i < gradOutputs.size()) { | ||
| dy = gradOutputs.get(i); | ||
| } | ||
| if (dy == null) { | ||
| dy = | ||
| gradOutputs == null || gradOutputs.isEmpty() | ||
| ? tf.onesLike((Operand) op.output(i)) | ||
| : tf.zerosLike((Operand) op.output(i)); | ||
| } | ||
| dys.add(dy); | ||
| } | ||
|
|
||
| List<Operand<?>> input = new ArrayList<>(nInputs + nOut); | ||
| input.addAll(inputs); | ||
| input.addAll(dys); | ||
|
|
||
| final String thenPrefix = op.name() + "/then_grad"; // op has unique name | ||
| final String elsePrefix = op.name() + "/else_grad"; | ||
|
|
||
| ConcreteFunction thenGrad = op.env().getFunctionCached(thenPrefix); | ||
| ConcreteFunction elseGrad = op.env().getFunctionCached(elsePrefix); | ||
|
|
||
| if (thenGrad == null || elseGrad == null) { | ||
| throw new IllegalStateException("If grad functions not primed for op=" + op.name()); | ||
| } | ||
| StatefulIf dInputsIf = | ||
| StatefulIf.create(tf.scope(), cond, input, tin, thenGrad, elseGrad); | ||
| List<Operand<?>> result = new ArrayList<>(1 + nInputs); | ||
| result.add(null); // no gradient for condition | ||
| result.addAll(dInputsIf.output()); | ||
| return result; | ||
| }); | ||
|
|
||
| Graph g = new Graph(); | ||
| Ops tf = Ops.create(g); | ||
|
|
||
| var x = tf.placeholder(TFloat32.class); // scalar | ||
| var cond = tf.placeholder(TBool.class); // scalar | ||
|
|
||
| try (ConcreteFunction thenBranch = thenFn(); | ||
| ConcreteFunction elseBranch = elseFn()) { | ||
|
|
||
| StatefulIf ifOp = | ||
| StatefulIf.create( | ||
| tf.scope(), | ||
| cond, | ||
| List.of((Operand) x), | ||
| List.of(TFloat32.class), | ||
| thenBranch, | ||
| elseBranch); | ||
|
|
||
| var y = ifOp.output().get(0); | ||
|
|
||
| primeIfGradFunctions(g); | ||
|
|
||
| var dy_dx = g.addGradients(y, new Output[] {x.asOutput()})[0]; | ||
|
|
||
| try (Session session = new Session(g)) { | ||
|
|
||
| try (Result r = | ||
| session | ||
| .runner() | ||
| .feed(x, TFloat32.scalarOf(2.0f)) | ||
| .feed(cond, TBool.scalarOf(true)) | ||
| .fetch(y) | ||
| .fetch(dy_dx) | ||
| .run()) { | ||
|
|
||
| float yVal = ((TFloat32) r.get(0)).getFloat(); | ||
| float gVal = ((TFloat32) r.get(1)).getFloat(); | ||
|
|
||
| assertClose(yVal, 6.0f, 1e-6f, "y mismatch for cond=true"); | ||
| assertClose(gVal, 3.0f, 1e-6f, "grad mismatch for cond=true"); | ||
| } | ||
|
|
||
| // ---- cond=false | ||
| try (Result r = | ||
| session | ||
| .runner() | ||
| .feed(x, TFloat32.scalarOf(2.0f)) | ||
| .feed(cond, TBool.scalarOf(false)) | ||
| .fetch(y) | ||
| .fetch(dy_dx) | ||
| .run()) { | ||
|
|
||
| float yVal = ((TFloat32) r.get(0)).getFloat(); | ||
| float gVal = ((TFloat32) r.get(1)).getFloat(); | ||
| assertClose(yVal, 10.0f, 1e-6f, "y mismatch for cond=false"); | ||
| assertClose(gVal, 5.0f, 1e-6f, "grad mismatch for cond=false"); | ||
| } | ||
| } | ||
| ; | ||
| } | ||
| } | ||
| ; | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the PR @nfeybesse, can you please remove this method? Looks like it is not being used, and it might not be desirable neither since if you have multiple functions with the same prefix, you don't know which one it gonna return (unless you return the whole list of matching functions?)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the feedback, that makes sense regarding the prefix-based lookup.
I tried removing access to the cached functions completely and relying only on Graph.getFunction(exactName), but this makes the implementation substantially more complicated. In particular, during custom gradient construction, calling Graph.getFunction(...) may end up scanning/querying the native function library while the graph is already being manipulated by the gradient builder. In my test case this can hang, so resolving the gradient functions through the native function library does not seem safe in that context.
I can still avoid the ambiguous prefix lookup by keeping an exact-name Java-side map in the test/code that creates the gradient functions. That works, but it means duplicating bookkeeping outside Graph even though Graph already has the information.
Maybe a middle-ground would be to expose a read-only view of the cached function names, for example a keySet() or functionNames() method. Then callers could resolve ambiguity themselves, choose an exact name deterministically, and still avoid exposing a method that returns an arbitrary function for a prefix.
Tell me what you prefer