安装
首先下载libtorch安装包,我选在了debug版本的用于学习:
https://pytorch.org/get-started/locally/
解压到某一目录,比如:I:\pytorch\1.5.1\debug
配置VS2017
创建一个VS2017 console project, 选择Debug|x64,然后配置include, libpath和link libraries:
比如在我的Windows 10:c10.lib;torch.lib;caffe2_module_test_dynamic.lib;torch_cpu.lib;fbgemm.lib;cpuinfo.lib;clog.lib;libprotocd.lib;libprotobufd.lib;mkldnn.lib
测试代码
#include <stdio.h>
#include <ATen/ATen.h>
#include <ATen/Tensor.h>
#include <torch/torch.h>
#include <iostream>
#include <tuple>
struct Net : torch::nn::Module
{
Net(int64_t N, int64_t M)
:linear(register_module("linear", torch::nn::Linear(N, M))) {
another_bias = register_parameter("b", torch::randn(M));
}
torch::Tensor forward(torch::Tensor input) {
return linear(input) + another_bias;
}
torch::nn::Linear linear;
torch::Tensor another_bias;
};
int main()
{
// vector -> tensor
{
std::vector<float> scales = { 1, 1, 1, 1, 1, 1 };
auto tscales = torch::tensor(scales);
std::cout << tscales << std::endl;
std::cout << tscales.sizes().size() << ":" << tscales.sizes()[0] << std::endl;
std::cout << tscales.squeeze() << std::endl;
}
// select
{
auto a = torch::randn({ 2, 3 });
std::cout << a << std::endl;
auto b = a.select(1, 2);
std::cout << b << std::endl;
}
// index select and max
{
auto indices = torch::tensor({ 0, 3, 1, 2 });
std::cout << indices << std::endl;
auto a = torch::randint(100, { 6, 4 });
std::cout << a << std::endl;
auto b = torch::index_select(a, 0, indices);
std::cout << b << std::endl;
auto max_classes = torch::max(a, 1);
std::cout << std::get<0>(max_classes) << std::endl;
std::cout << std::get<1>(max_classes) << std::endl;
}
// compare
{
auto a = torch::randn({ 2, 3 });
auto b = a * 100;
std::cout << "a:\n" << a << "b:\n" << b << std::endl;
std::cout << (b < 10) << std::endl;
}
// stack
{
auto a = torch::randn(10);
auto b = torch::randn(10);
std::cout << "a:\n" << a << "b:\n" << b << std::endl;
auto c = torch::stack({ a, b }, 0);
std::cout << c << std::endl;
}
// nn test
{
Net net(4, 5);
for (auto const& p : net.named_parameters())
{
std::cout << p.key() << ":\n" << p.value() << std::endl;
}
}
{
Net net(4, 5);
std::cout << net.forward(torch::ones({ 2, 4 })) << std::endl;
}
return 0;
}