mirror of
https://github.com/pytorch/pytorch.git
synced 2026-11-20 09:04:25 +08:00
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:
committed by
Facebook Github Bot
parent
72aeafd3d0
commit
98ccae09af
@@ -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)));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user