Ensure compatibility between libtorch and PyTorch

I am writing a simple c++ code to generate random torch::Tensor. Later, I will compile the library to .so and load it into my python code using torch.ops.load_library(<path>.so)

I compile libtorch (cxx ABI) 2.1.2 from source and PyTorch 2.1.2 from pip from the link. Both use CUDA 12.1.

I have a op.cpp which defines my C++ operator, a CMakeLists.txt file to build a .so.
Finally, I load the .so in my test.py file

  1. CMakeLists.txt
cmake_minimum_required(VERSION 3.1 FATAL_ERROR)

SET(CMAKE_PREFIX_PATH /home/saandeepaath-admin/projects/learning/cpp_cmake/example2/libtorch)
find_package(Torch REQUIRED)

# Define our library target
add_library(warp_perspective SHARED op.cpp)
# Enable C++14
target_compile_features(warp_perspective PRIVATE cxx_std_14)
# Link against LibTorch
target_link_libraries(warp_perspective "${TORCH_LIBRARIES}")
  1. op.cpp
#include <torch/torch.h>
#include <iostream>

torch::Tensor create_rand(){
  torch::Tensor ten = torch::rand({5});
  std::cout<<"TENSOR: "<<ten<<std::endl;
  return ten;

TORCH_LIBRARY(op_cpp, m) {
  m.def("create_rand", create_rand);

  1. test.py
import sys
import torch
# import torch.utils


Output of running cmake

However, when I try to load my .so file into my test.py file, I get the following error

OSError: <path>/libwarp_perspective.so: undefined symbol: _ZN5torch3jit17parseSchemaOrNameERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE

Please advise.

I realized I can compile PyTorch directly from source and also use libtorch without additional installation. I set the CMAKE_PREFIX_PATH to pytorch directory and enabled CXX_ABI during installation.