C++ API parity: at::Tensor::grad

Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/26150

Test Plan: Imported from OSS

Differential Revision: D17427579

Pulled By: pbelevich

fbshipit-source-id: 68d012076aa86dee9f23fad71a2d265d75f56d22
This commit is contained in:
Pavel Belevich
2019-09-18 09:19:00 -07:00
committed by Facebook Github Bot
parent 72aeafd3d0
commit 98ccae09af
6 changed files with 34 additions and 22 deletions
+20
View File
@@ -1,4 +1,5 @@
#include <gtest/gtest.h>
#include <test/cpp/api/support.h>
#include <torch/types.h>
@@ -319,3 +320,22 @@ TEST(TensorTest, Data) {
const auto tensor2 = at::empty({3, 3});
ASSERT_THROW(tensor2.data(), c10::Error);
}
TEST(TensorTest, BackwardAndGrad) {
auto x = torch::tensor({5}, at::TensorOptions().requires_grad(true));
auto y = x * x;
y.backward();
ASSERT_EQ(x.grad().item<float>(), 10.0);
x = at::tensor({5});
y = x * x;
ASSERT_THROWS_WITH(y.backward(), "backward is not implemented for Tensor");
ASSERT_THROWS_WITH(x.grad(), "grad is not implemented for Tensor");
}
TEST(TensorTest, BackwardCreatesOnesGrad) {
const auto x = torch::tensor({5}, at::TensorOptions().requires_grad(true));
x.backward();
ASSERT_TRUE(torch::equal(x.grad(),
torch::ones_like(x)));
}