@@ -68,16 +68,49 @@ function(TorchMLIRConfigurePyTorch)
6868 message (STATUS "PyTorch C++ Dual ABI setting: \" ${_use_cxx11_abi} \" " )
6969
7070 # Check ABI compatibility version
71+ # Note: _PYBIND11_BUILD_ABI was removed in PyTorch 2.5+
72+ # First, try the new method (checking libtorch_python.so)
7173 execute_process (
7274 COMMAND ${Python3_EXECUTABLE}
73- -c "import torch; import sys; abi= torch._C._PYBIND11_BUILD_ABI; abi.startswith('_cxxabi10') or sys.exit(1 ); sys.stdout.write(str(abi[-2:]) )"
75+ -c "import torch; import sys; abi = getattr( torch._C, '_PYBIND11_BUILD_ABI', None ); sys.stdout.write(str(abi) if abi else '' )"
7476 RESULT_VARIABLE _result
7577 WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
76- OUTPUT_VARIABLE _cxx_abi_version)
77- if (_result)
78- message (FATAL_ERROR "Failed to determine C++ ABI version" )
78+ OUTPUT_VARIABLE _pybind11_abi)
79+
80+ if (_result EQUAL "0" AND _pybind11_abi AND _pybind11_abi MATCHES "^_cxxabi10" )
81+ # Old method worked - extract ABI version from the string
82+ string (REGEX REPLACE "^_cxxabi10(..)$" "\\ 1" _cxx_abi_version "${_pybind11_abi} " )
83+ message (STATUS "PyTorch C++ ABI version (from _PYBIND11_BUILD_ABI): \" ${_cxx_abi_version} \" " )
84+ else ()
85+ # Fallback: try to extract from libtorch_python.so
86+ message (STATUS "PyTorch _PYBIND11_BUILD_ABI not available, checking libtorch_python.so..." )
87+ execute_process (
88+ COMMAND ${Python3_EXECUTABLE}
89+ -c "import torch; import os; print(os.path.join(os.path.dirname(torch.__file__), 'lib', 'libtorch_python.so'), end='')"
90+ RESULT_VARIABLE _result
91+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
92+ OUTPUT_VARIABLE _libtorch_python_path)
93+
94+ if (_result EQUAL "0" AND EXISTS "${_libtorch_python_path} " )
95+ execute_process (
96+ COMMAND bash "-c" "strings ${_libtorch_python_path} | grep -E '^_cxxabi[0-9]{4}' | head -1 | grep -oE '..$'"
97+ RESULT_VARIABLE _result
98+ OUTPUT_VARIABLE _cxx_abi_version
99+ OUTPUT_STRIP_TRAILING_WHITESPACE)
100+
101+ if (_result EQUAL "0" AND _cxx_abi_version)
102+ message (STATUS "PyTorch C++ ABI version (from libtorch_python.so): \" ${_cxx_abi_version} \" " )
103+ else ()
104+ # Final fallback: use a sensible default (ABI version 11 is most common)
105+ set (_cxx_abi_version "11" )
106+ message (WARNING "Could not determine PyTorch C++ ABI version, using default: \" ${_cxx_abi_version} \" " )
107+ endif ()
108+ else ()
109+ # Final fallback: use a sensible default
110+ set (_cxx_abi_version "11" )
111+ message (WARNING "Could not find libtorch_python.so, using default ABI version: \" ${_cxx_abi_version} \" " )
112+ endif ()
79113 endif ()
80- message (STATUS "PyTorch C++ ABI version: \" ${_cxx_abi_version} \" " )
81114
82115 # Specialize compile flags for compiler
83116 if (${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU" )
0 commit comments