Shortcuts

C++前端中的自动求导

创建于:2020年4月1日 | 最后更新:2022年9月12日 | 最后验证:未验证

autograd 包对于在 PyTorch 中构建高度灵活和动态的神经网络至关重要。PyTorch Python 前端中的大多数 autograd API 在 C++ 前端中也可用,这使得将 autograd 代码从 Python 转换为 C++ 变得容易。

在本教程中,探索了在PyTorch C++前端中进行自动求导的几个示例。 请注意,本教程假设您已经对Python前端的自动求导有基本的了解。 如果不是这样,请先阅读 Autograd: Automatic Differentiation

基本自动梯度操作

(改编自本教程

创建一个张量并设置torch::requires_grad()以跟踪其计算

auto x = torch::ones({2, 2}, torch::requires_grad());
std::cout << x << std::endl;

输出:

1 1
1 1
[ CPUFloatType{2,2} ]

执行一个张量操作:

auto y = x + 2;
std::cout << y << std::endl;

输出:

 3  3
 3  3
[ CPUFloatType{2,2} ]

y 是由于操作而创建的,因此它有一个 grad_fn

std::cout << y.grad_fn()->name() << std::endl;

输出:

AddBackward1

y 上进行更多操作

auto z = y * y * 3;
auto out = z.mean();

std::cout << z << std::endl;
std::cout << z.grad_fn()->name() << std::endl;
std::cout << out << std::endl;
std::cout << out.grad_fn()->name() << std::endl;

输出:

 27  27
 27  27
[ CPUFloatType{2,2} ]
MulBackward1
27
[ CPUFloatType{} ]
MeanBackward0

.requires_grad_( ... ) 就地更改现有张量的 requires_grad 标志。

auto a = torch::randn({2, 2});
a = ((a * 3) / (a - 1));
std::cout << a.requires_grad() << std::endl;

a.requires_grad_(true);
std::cout << a.requires_grad() << std::endl;

auto b = (a * a).sum();
std::cout << b.grad_fn()->name() << std::endl;

输出:

false
true
SumBackward0

现在让我们进行反向传播。因为 out 包含一个标量,out.backward() 等同于 out.backward(torch::tensor(1.))

out.backward();

打印梯度 d(out)/dx

std::cout << x.grad() << std::endl;

输出:

 4.5000  4.5000
 4.5000  4.5000
[ CPUFloatType{2,2} ]

你应该得到了一个4.5的矩阵。关于我们如何得出这个值的解释,请参见本教程中的相应部分

现在让我们来看一个向量-雅可比积的例子:

x = torch::randn(3, torch::requires_grad());

y = x * 2;
while (y.norm().item<double>() < 1000) {
  y = y * 2;
}

std::cout << y << std::endl;
std::cout << y.grad_fn()->name() << std::endl;

输出:

-1021.4020
  314.6695
 -613.4944
[ CPUFloatType{3} ]
MulBackward1

如果我们想要向量-雅可比积,将向量作为参数传递给 backward

auto v = torch::tensor({0.1, 1.0, 0.0001}, torch::kFloat);
y.backward(v);

std::cout << x.grad() << std::endl;

输出:

  102.4000
 1024.0000
    0.1024
[ CPUFloatType{3} ]

你也可以通过在代码块中放置torch::NoGradGuard来阻止自动梯度跟踪需要梯度的张量的历史记录

std::cout << x.requires_grad() << std::endl;
std::cout << x.pow(2).requires_grad() << std::endl;

{
  torch::NoGradGuard no_grad;
  std::cout << x.pow(2).requires_grad() << std::endl;
}

输出:

true
true
false

或者通过使用.detach()来获取一个具有相同内容但不需要梯度的新张量:

std::cout << x.requires_grad() << std::endl;
y = x.detach();
std::cout << y.requires_grad() << std::endl;
std::cout << x.eq(y).all().item<bool>() << std::endl;

输出:

true
false
true

有关C++张量自动求导API的更多信息,例如grad / requires_grad / is_leaf / backward / detach / detach_ / register_hook / retain_grad, 请参阅相应的C++ API文档

在C++中计算高阶梯度

高阶梯度的一个应用是计算梯度惩罚。 让我们看一个使用 torch::autograd::grad 的例子:

#include <torch/torch.h>

auto model = torch::nn::Linear(4, 3);

auto input = torch::randn({3, 4}).requires_grad_(true);
auto output = model(input);

// Calculate loss
auto target = torch::randn({3, 3});
auto loss = torch::nn::MSELoss()(output, target);

// Use norm of gradients as penalty
auto grad_output = torch::ones_like(output);
auto gradient = torch::autograd::grad({output}, {input}, /*grad_outputs=*/{grad_output}, /*create_graph=*/true)[0];
auto gradient_penalty = torch::pow((gradient.norm(2, /*dim=*/1) - 1), 2).mean();

// Add gradient penalty to loss
auto combined_loss = loss + gradient_penalty;
combined_loss.backward();

std::cout << input.grad() << std::endl;

输出:

-0.1042 -0.0638  0.0103  0.0723
-0.2543 -0.1222  0.0071  0.0814
-0.1683 -0.1052  0.0355  0.1024
[ CPUFloatType{3,4} ]

请参阅文档以获取更多关于如何使用torch::autograd::backward (link) 和torch::autograd::grad (link) 的信息。

在C++中使用自定义自动梯度函数

(改编自本教程

torch::autograd添加一个新的基本操作需要为每个操作实现一个新的torch::autograd::Function子类。torch::autograd::Functiontorch::autograd用来计算结果和梯度,并编码操作历史的东西。每个新函数都需要你实现2个方法:forwardbackward,详情请参阅此链接

下面你可以找到来自torch::nnLinear函数的代码:

#include <torch/torch.h>

using namespace torch::autograd;

// Inherit from Function
class LinearFunction : public Function<LinearFunction> {
 public:
  // Note that both forward and backward are static functions

  // bias is an optional argument
  static torch::Tensor forward(
      AutogradContext *ctx, torch::Tensor input, torch::Tensor weight, torch::Tensor bias = torch::Tensor()) {
    ctx->save_for_backward({input, weight, bias});
    auto output = input.mm(weight.t());
    if (bias.defined()) {
      output += bias.unsqueeze(0).expand_as(output);
    }
    return output;
  }

  static tensor_list backward(AutogradContext *ctx, tensor_list grad_outputs) {
    auto saved = ctx->get_saved_variables();
    auto input = saved[0];
    auto weight = saved[1];
    auto bias = saved[2];

    auto grad_output = grad_outputs[0];
    auto grad_input = grad_output.mm(weight);
    auto grad_weight = grad_output.t().mm(input);
    auto grad_bias = torch::Tensor();
    if (bias.defined()) {
      grad_bias = grad_output.sum(0);
    }

    return {grad_input, grad_weight, grad_bias};
  }
};

然后,我们可以通过以下方式使用 LinearFunction

auto x = torch::randn({2, 3}).requires_grad_();
auto weight = torch::randn({4, 3}).requires_grad_();
auto y = LinearFunction::apply(x, weight);
y.sum().backward();

std::cout << x.grad() << std::endl;
std::cout << weight.grad() << std::endl;

输出:

 0.5314  1.2807  1.4864
 0.5314  1.2807  1.4864
[ CPUFloatType{2,3} ]
 3.7608  0.9101  0.0073
 3.7608  0.9101  0.0073
 3.7608  0.9101  0.0073
 3.7608  0.9101  0.0073
[ CPUFloatType{4,3} ]

在这里,我们提供了一个由非张量参数参数化的函数的额外示例:

#include <torch/torch.h>

using namespace torch::autograd;

class MulConstant : public Function<MulConstant> {
 public:
  static torch::Tensor forward(AutogradContext *ctx, torch::Tensor tensor, double constant) {
    // ctx is a context object that can be used to stash information
    // for backward computation
    ctx->saved_data["constant"] = constant;
    return tensor * constant;
  }

  static tensor_list backward(AutogradContext *ctx, tensor_list grad_outputs) {
    // We return as many input gradients as there were arguments.
    // Gradients of non-tensor arguments to forward must be `torch::Tensor()`.
    return {grad_outputs[0] * ctx->saved_data["constant"].toDouble(), torch::Tensor()};
  }
};

然后,我们可以通过以下方式使用MulConstant

auto x = torch::randn({2}).requires_grad_();
auto y = MulConstant::apply(x, 5.5);
y.sum().backward();

std::cout << x.grad() << std::endl;

输出:

 5.5000
 5.5000
[ CPUFloatType{2} ]

有关torch::autograd::Function的更多信息,请参阅 其文档

将自动梯度代码从Python翻译到C++

在高层次上,在C++中使用autograd的最简单方法是首先在Python中编写有效的autograd代码,然后使用下表将你的autograd代码从Python翻译到C++:

Python

C++

torch.autograd.backward

torch::autograd::backward (link)

torch.autograd.grad

torch::autograd::grad (link)

torch.Tensor.detach

torch::Tensor::detach (link)

torch.Tensor.detach_

torch::Tensor::detach_ (link)

torch.Tensor.backward

torch::Tensor::backward (link)

torch.Tensor.register_hook

torch::Tensor::register_hook (link)

torch.Tensor.requires_grad

torch::Tensor::requires_grad_ (link)

torch.Tensor.retain_grad

torch::Tensor::retain_grad (link)

torch.Tensor.grad

torch::Tensor::grad (link)

torch.Tensor.grad_fn

torch::Tensor::grad_fn (link)

torch.Tensor.set_data

torch::Tensor::set_data (link)

torch.Tensor.data

torch::Tensor::data (link)

torch.Tensor.output_nr

torch::Tensor::output_nr (link)

torch.Tensor.is_leaf

torch::Tensor::is_leaf (link)

翻译后,您的大部分Python自动求导代码应该可以直接在C++中使用。 如果不是这样,请在GitHub issues提交错误报告,我们将尽快修复。

结论

你现在应该对PyTorch的C++自动求导API有了一个很好的概览。 你可以找到本笔记中展示的代码示例这里。一如既往,如果你遇到任何问题或有疑问,你可以使用我们的论坛GitHub问题来联系我们。