Skip to content
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

stopGradient Test added #713

Merged
merged 2 commits into from
Mar 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
*/
package ai.djl.integration.tests.ndarray;

import ai.djl.engine.Engine;
import ai.djl.engine.EngineException;
import ai.djl.ndarray.LazyNDArray;
import ai.djl.ndarray.NDArray;
Expand All @@ -21,6 +22,7 @@
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.testing.Assertions;
import ai.djl.training.GradientCollector;
import ai.djl.util.Hex;
import java.nio.FloatBuffer;
import org.testng.Assert;
Expand Down Expand Up @@ -888,4 +890,28 @@ public void testOneHot() {
Assert.assertEquals(array.oneHot(3), expected);
}
}

@Test
public void testStopGradient() {
try (NDManager manager = NDManager.newBaseManager()) {
// normal gradient
NDArray x = manager.create(new float[] {1.0f}, new Shape(1));
x.attachGradient();
try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
NDArray y = x.mul(x);
gc.backward(y);
NDArray grad = x.getGradient();
Assert.assertEquals(2f, grad.getFloat(0));
}
// stop gradient
x = manager.create(new float[] {1.0f}, new Shape(1));
x.attachGradient();
try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
NDArray z = x.mul(x.stopGradient());
gc.backward(z);
NDArray grad = x.getGradient();
Assert.assertEquals(1f, grad.getFloat(0));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public boolean hasGradient() {
/** {@inheritDoc} */
@Override
public NDArray stopGradient() {
throw new UnsupportedOperationException("Not supported");
return JniUtils.detachGradient(this);
}

/** {@inheritDoc} */
Expand Down