libtorch知识总结
- 一, libtorch api
-
- 1. 创建张量
- 2. 属性
- 3. 运算
- 4. 形状变换
- 5. 选择和切片
- 6. 其它函数
- 二,深度学习相关函数
- 三,编译相关文件和命令
-
- 1. g++命令
- 2. Makefile
- 3. CMakeLists.txt
-
- 3.1 基本
- 3.2 打包库
-
- (1) CMakeLists.txt主文件
- (2) sub CMakeLists.txt文件
一, libtorch api
1. 创建张量
torch::Tensor = torch::tensor({1,2,3}, torch::dtype(torch::kFLoat));
t1 = torch::arange(10);
t1 = torch::arange(1, 10);
t1 = torch::arange(1, 10, 2);
t1 = torch::arange(1, 10, 2, torch::kFloat);
t1 = torch::randn({3, 3});
t1 = torch::rand({1, 3, 2, 3});
t1 = torch::randint(0, 2, {3, 3});
t1 = torch::ones({2, 2});
t2 = torch::ones_like(t1, 1);
t1 = torch::zeros({2, 2});
t2 = torch::zeros_like(t1, 1);
t1 = torch::empty({2, 2});
t2 = torch::empty_like(t1, 1);
t1 = torch::full({2, 2}, -1, torch::dtype(torch::kLong));
t2 = torch::full_like(t1, 1);
t1 = torch::empty({2, 2}).fill_(-2).to(torch::kCPU);
t2 = t1.clone();
d = torch::where(a > 0.5, b, c);
2. 属性
dtype()
device()
numel()
element_size()
data_ptr()
ndimension()
dim()
sizes()
size(0)
numpy_T().sizes()
t()
3. 运算
add()
sub()
mul()
div()
true_divide()
floor_divide()
matmul()
mm()
4. 形状变换
a = torch::arange(12, torch::kFloat).reshape({4, 3});
c = torch::cat({a, b}, 0);
d = torch::stack({a, b}, 0);
b = a.squeeze();
c = torch::squeeze(a, 0);
d = a.squeeze_(0);
b = a.unsqueeze(0);
c = torch::unsqueeze(a, 2);
d = a.transpose(1, 0);
a = a.permute({2, 0, 1});
b = a.flatten();
c = a.flatten(1);
f = e.expand_as(a);
a = torch::tensor({1, 2, 3});
b = a.repeat({2, 2, 1});
5. 选择和切片
b = a.select(1, 2)
d = torch::select(a, 1, 2);
torch::Tensor idx = torch::tensor({1, 0}, torch::kLong);
b = a.index_select(1, idx);
b = a.slice(0, 0, 4, 2);
c = a.narrow(0, 1, 2);
d = a.narrow_copy(1, 1, 3);
a = torch::rand({2, 3});
b = (a > 0.25);
c = a.masked_select(b);
d.masked_fill_(a > 0.5, -2);
6. 其它函数
a.argsort(dim, descending)
b = torch::nonzero(a);
c = a[0][0].item().toFloat();
a.to(torch::kCPU)
a.to(torch::kCUDA, 1)
inline at::Tensor from_blob(
void* data,
at::IntArrayRef sizes,
const at::TensorOptions& options = at::TensorOptions())
torch::Tensor imgtensor = torch::from_blob(img.data, {img.rows, img.cols, 3}, torch::kByte);
b = a.clamp(3, 7);
std::tuple<torch::Tensor, torch::Tensor> sort_ret = torch::sort(scores, 0, 1);
torch::Tensor v = std::get<0>(sort_ret).to(scores.device());
torch::Tensor idx = std::get<1>(sort_ret).to(scores.device());
b = torch::max(a);
std::tuple<torch::Tensor, torch::Tensor> c = torch::max(a, 1);
auto max_val = std::get<0>(c);
auto index = std::get<1>(c);
torch::Tensor scales = torch::tensor({1, 2});
torch::Tensor ratios = torch::tensor({3, 4});
std::vector<torch::Tensor> mesh = torch::meshgrid({scales, ratios});
二,深度学习相关函数
auto device = torch::device(torch::kCUDA);
auto device = torch::Device(torch::kCUDA,1);
int cudanum = torch::cuda::device_count();
torch::Device device = torch::cuda::is_available() ? torch::Device(torch::kCUDA,1) : torch::Device(torch::kCPU);
int load_module(torch::jit::script::Module &module, const string &path, torch::Device device)
{
try
{
module = torch::jit::load(path);
module.to(device);
}
catch (c10::Error &e)
{
std::cerr << "error loading the model\n";
return -1;
}
return 0;
}
int load_image(cv::Mat &img, const string &path, int w, int type)
{
img = cv::imread(path, type > 0 ? 1 : 0);
int width, height;
width = img.cols;
height = img.rows;
if (img.empty())
{
std::cerr << "error loading image";
return -1;
}
resize(img, img, cv::Size(w, height * w / width));
return 0;
}
int module_forward(torch::Tensor &y, const torch::Tensor &x, torch::jit::script::Module module)
{
std::vector<torch::jit::IValue> inputs;
inputs.emplace_back(x);
try
{
y = module.forward(inputs).toTensor();
}
catch (c10::Error &e)
{
std::cerr << "error forwarding the model\n";
return -1;
}
return 0;
}
int module_forward(std::vector<torch::Tensor> &vts_y, const torch::Tensor &x, torch::jit::script::Module module)
{
torch::IValue iv_y;
std::vector<torch::jit::IValue> inputs;
inputs.emplace_back(x);
try
{
iv_y = module.forward(inputs);
}
catch (c10::Error &e)
{
std::cerr << "error forwarding the model\n";
return -1;
}
auto at_y = iv_y.toTuple()->elements();
int n_ySize = at_y.size();
for (int i = 0; i < n_ySize; i++)
{
vts_y.push_back(at_y[i].toTensor());
}
return 0;
}
int module_forward(std::vector<torch::Tensor> &vts_y, const torch::Tensor &x, torch::jit::script::Module module)
{
torch::IValue iv_y;
std::vector<torch::jit::IValue> inputs;
inputs.emplace_back(x);
try
{
iv_y = module.forward(inputs);
}
catch (c10::Error &e)
{
std::cerr << "error forwarding the model\n";
return -1;
}
auto at_y = iv_y.toTensorList();
int n_ySize = at_y.size();
for (int i = 0; i < n_ySize; i++)
{
vts_y.push_back((torch::Tensor) at_y[i]);
}
return 0;
}
void mat2tensor(torch::Tensor &img_tensor, const cv::Mat &img, torch::Device device)
{
img_tensor = torch::from_blob(img.data, {1, img.rows, img.cols, img.channels()}, torch::kByte);
img_tensor = img_tensor.toType(torch::kFloat);
img_tensor = img_tensor.permute({0, 3, 1, 2});
img_tensor = img_tensor.div_(255.0);
img_tensor = img_tensor.sub_(0.5);
img_tensor = img_tensor.div_(0.5);
img_tensor = img_tensor.to(device);
}
void tensor2mat(cv::Mat &tensor_img, const torch::Tensor &img_tensor)
{
tensor_img.create(cv::Size(img_tensor.size(-1), img_tensor.size(-2)), CV_8UC1);
torch::Tensor img_tensor_ = img_tensor.to(torch::kU8);
std::memcpy((void *)tensor_img.data, img_tensor_.data_ptr(), img_tensor.element_size() * img_tensor_.numel());
}
cv::Mat img(img_tensor.size(1), img_tensor.size(2), CV_8UC1, img_tensor.data_ptr());
三,编译相关文件和命令
1. g++命令
g++ -o alibtorch main.cpp utils.cpp -I/home/wen/libtorch/include -I/home/wen/libtorch/include/torch/csrc/api/include -I/usr/local/include/opencv4 -L/home/wen/libtorch/lib -L/usr/local/lib -lc10 -ltorch_cpu -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs
2. Makefile
OBJS:=main.o utils.o demo.o
CXXFLAGS=-g -Wall -I/home/wen/libtorch/include -I/home/wen/libtorch/include/torch/csrc/api/include -I/usr/local/include/opencv4
LDFLAGS=-L/home/wen/libtorch/lib -L/usr/local/lib
LIBS=-lc10 -ltorch_cpu -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs
main:$(OBJS)
$(CXX) -o $@ $^ $(LDFLAGS) $(LIBS)
.PHONY:clean
clean:
find ./ -name "*.o" -exec rm {} \; ; rm main
3. CMakeLists.txt
3.1 基本
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(torch)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_PREFIX_PATH ~/libtorch)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_INSTALL_PREFIX install)
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
set(SRC_LIST main.cpp utils.cpp demo.cpp)
add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} ${TORCH_LIBRARIES} ${OpenCV_LIBS})
# set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 14)
install(TARGETS ${PROJECT_NAME}
DESTINATION bin
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
GROUP_READ GROUP_EXECUTE)
if (MSVC)
file(GLOB TORCH_DLLS "${TORCH_INSTALL_PREFIX}/lib/*.dll")
add_custom_command(TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${TORCH_DLLS}
$<TARGET_FILE_DIR:${PROJECT_NAME}>)
file(GLOB OPENCV_DLLS "D:/lib/opencv/build/x64/vc15/bin/*.dll")
add_custom_command(TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${OPENCV_DLLS}
$<TARGET_FILE_DIR:${PROJECT_NAME}>)
endif ()
3.2 打包库
(1) CMakeLists.txt主文件
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(atorch)
add_subdirectory(lib)
set(CMAKE_PREFIX_PATH ~/libtorch)
set(EXECUTABLE_OUTPUT_PATH ~/bin)
SET(CMAKE_INSTALL_PREFIX install)
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
set(SRC_LIST main.cpp utils.cpp demo.cpp test.cpp)
add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} ${TORCH_LIBRARIES} ${OpenCV_LIBS})
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 14)
install(TARGETS ${PROJECT_NAME}
RUNTIME DESTINATION bin
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
GROUP_READ GROUP_EXECUTE)
install(TARGETS utils utils_static
LIBRARY DESTINATION lib)
(2) sub CMakeLists.txt文件
set(LIBUTILS_SRC utils.cpp)
set(LIBRARY_OUTPUT_PATH ~/lib)
set(CMAKE_PREFIX_PATH ~/libtorch)
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)
add_library(utils SHARED ${LIBUTILS_SRC})
add_library(utils_static STATIC ${LIBUTILS_SRC})
target_link_libraries(utils ${TORCH_LIBRARIES} ${OpenCV_LIBS})
target_link_libraries(utils_static ${TORCH_LIBRARIES} ${OpenCV_LIBS})
set_target_properties(utils_static PROPERTIES OUTPUT_NAME utils)