目录

C++ 前端中的 autograd

创建时间: Apr 01, 2020 |上次更新时间:2022 年 9 月 12 日 |上次验证时间:未验证

该包对于构建高度灵活和动态的神经至关重要 网络。PyTorch Python 前端中的大多数 autograd API 也可用 在 C++ 前端,允许轻松地将 autograd 代码从 Python 转换为 C++。autograd

在本教程中,探讨了在 PyTorch C++ 前端执行 autograd 的几个示例。 请注意,本教程假定您已经对 autograd 的 Python 前端。如果不是这种情况,请先阅读 Autograd:自动微分

基本 autograd 操作

(改编自本教程)

创建一个张量并设置为使用它跟踪计算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

现在让我们反向传播。因为包含单个标量,所以等价于 。outout.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} ]

您还可以阻止 autograd 跟踪需要梯度的张量的历史记录 通过放入代码块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++ 张量 autograd API 的更多信息,例如 / / / , 请参阅相应的 C++ API 文档gradrequires_gradis_leafbackwarddetachdetach_register_hookretain_grad

在 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} ]

请参阅 (link) 的文档 和 (链接) ,了解有关如何使用它们的更多信息。torch::autograd::backwardtorch::autograd::grad

在 C++ 中使用自定义 autograd 函数

(改编自本教程)

添加新的 elementary operation 需要为每个 operation 实现一个新的 subclass。 S 用于计算结果和梯度,并对操作历史进行编码。每 new 函数需要你实现 2 个方法:AND 、 和 有关详细要求,请参阅此链接torch::autogradtorch::autograd::Functiontorch::autograd::Functiontorch::autogradforwardbackward

您可以从下面找到函数的代码:Lineartorch::nn

#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

将 autograd 代码从 Python 转换为 C++

概括地说,在 C++ 中使用 autograd 的最简单方法是将 autograd 代码,然后将 autograd 代码从 Python 转换为 C++ 使用下表:

C++

torch.autograd.backward

torch::autograd::backward (链接)

torch.autograd.grad

torch::autograd::grad (链接)

torch.Tensor.detach

torch::Tensor::detach (链接)

torch.Tensor.detach_

torch::Tensor::detach_ (链接)

torch.Tensor.backward

torch::Tensor::backward (链接)

torch.Tensor.register_hook

torch::Tensor::register_hook (链接)

torch.Tensor.requires_grad

torch::Tensor::requires_grad_ (链接)

torch.Tensor.retain_grad

torch::Tensor::retain_grad (链接)

torch.Tensor.grad

torch::Tensor::grad (链接)

torch.Tensor.grad_fn

torch::Tensor::grad_fn (链接)

torch.Tensor.set_data

torch::Tensor::set_data (链接)

torch.Tensor.data

torch::Tensor::data (链接)

torch.Tensor.output_nr

torch::Tensor::output_nr (链接)

torch.Tensor.is_leaf

torch::Tensor::is_leaf (链接)

转换后,您的大多数 Python autograd 代码应该可以在 C++ 中运行。 如果不是这种情况,请在 GitHub issues 上提交错误报告,我们将尽快修复它。

结论

现在,您应该对 PyTorch 的 C++ autograd API 有一个很好的了解。 您可以在此处找到本说明中显示的代码示例。与往常一样,如果您遇到任何 问题或有疑问,您可以使用我们的 论坛GitHub 问题与我们联系。

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源