2018-09-22 04:12:37 +00:00
|
|
|
#include <gtest/gtest.h>
|
2018-05-01 01:36:35 +00:00
|
|
|
|
2018-07-13 01:45:48 +00:00
|
|
|
#include <torch/nn/init.h>
|
2018-05-30 15:55:34 +00:00
|
|
|
#include <torch/nn/modules/linear.h>
|
|
|
|
|
#include <torch/tensor.h>
|
|
|
|
|
#include <torch/utils.h>
|
2018-05-01 01:36:35 +00:00
|
|
|
|
2018-09-22 04:12:37 +00:00
|
|
|
#include <test/cpp/api/support.h>
|
2018-05-24 19:46:51 +00:00
|
|
|
|
2018-09-22 04:12:37 +00:00
|
|
|
TEST(NoGradTest, SetsGradModeCorrectly) {
|
2018-06-28 03:00:53 +00:00
|
|
|
torch::manual_seed(0);
|
|
|
|
|
torch::NoGradGuard guard;
|
2018-09-22 04:12:37 +00:00
|
|
|
torch::nn::Linear model(5, 2);
|
2018-06-28 03:00:53 +00:00
|
|
|
auto x = torch::randn({10, 5}, torch::requires_grad());
|
|
|
|
|
auto y = model->forward(x);
|
|
|
|
|
torch::Tensor s = y.sum();
|
|
|
|
|
|
|
|
|
|
s.backward();
|
2018-09-22 04:12:37 +00:00
|
|
|
ASSERT_FALSE(model->parameters()["weight"].grad().defined());
|
2018-05-01 01:36:35 +00:00
|
|
|
}
|
2018-05-17 21:10:15 +00:00
|
|
|
|
2018-09-22 04:12:37 +00:00
|
|
|
struct AutogradTest : torch::test::SeedingFixture {
|
|
|
|
|
AutogradTest() {
|
|
|
|
|
x = torch::randn({3, 3}, torch::requires_grad());
|
|
|
|
|
y = torch::randn({3, 3});
|
|
|
|
|
z = x * y;
|
2018-05-25 00:31:41 +00:00
|
|
|
}
|
2018-09-22 04:12:37 +00:00
|
|
|
torch::Tensor x, y, z;
|
|
|
|
|
};
|
2018-05-25 00:31:41 +00:00
|
|
|
|
2018-09-22 04:12:37 +00:00
|
|
|
TEST_F(AutogradTest, CanTakeDerivatives) {
|
|
|
|
|
z.backward();
|
|
|
|
|
ASSERT_TRUE(x.grad().allclose(y));
|
2018-07-13 01:45:48 +00:00
|
|
|
}
|
|
|
|
|
|
2018-09-22 04:12:37 +00:00
|
|
|
TEST_F(AutogradTest, CanTakeDerivativesOfZeroDimTensors) {
|
|
|
|
|
z.sum().backward();
|
|
|
|
|
ASSERT_TRUE(x.grad().allclose(y));
|
2018-05-17 21:10:15 +00:00
|
|
|
}
|
2018-05-24 19:46:51 +00:00
|
|
|
|
2018-09-22 04:12:37 +00:00
|
|
|
TEST_F(AutogradTest, CanPassCustomGradientInputs) {
|
|
|
|
|
z.sum().backward(torch::ones({}) * 2);
|
|
|
|
|
ASSERT_TRUE(x.grad().allclose(y * 2));
|
2018-05-24 19:46:51 +00:00
|
|
|
}
|
2018-06-05 18:29:09 +00:00
|
|
|
|
2018-09-22 04:12:37 +00:00
|
|
|
TEST(NNInitTest, CanInitializeTensorThatRequiresGrad) {
|
|
|
|
|
auto tensor = torch::empty({3, 4}, torch::requires_grad());
|
|
|
|
|
ASSERT_THROWS_WITH(
|
|
|
|
|
tensor.fill_(1),
|
|
|
|
|
"a leaf Variable that requires grad "
|
|
|
|
|
"has been used in an in-place operation");
|
|
|
|
|
ASSERT_EQ(torch::nn::init::ones_(tensor).sum().toCInt(), 12);
|
2018-06-05 18:29:09 +00:00
|
|
|
}
|