onnxruntime
4d7bcf67 - Enable Free-threaded Python (PEP 703) support for Python 3.13t+ (#26786)

Commit
9 days ago
Enable Free-threaded Python (PEP 703) support for Python 3.13t+ (#26786) This PR resolves the `RuntimeWarning` encountered when importing `onnxruntime` in free-threaded Python environments (e.g., Python 3.13t, 3.14t). Previously, the module did not explicitly declare that it could run safely without the GIL, causing the interpreter to re-enable the GIL at runtime. ### The Warning ```text RuntimeWarning: The global interpreter lock (GIL) has been enabled to load module 'onnxruntime.capi.onnxruntime_pybind11_state', which has not declared that it can run safely without the GIL. ```` ## Changes ### 1. Build System (`cmake/onnxruntime_python.cmake`) * Added robust detection logic to check if the current Python interpreter is free-threaded. **Detection strategy:** * **Primary:** Check `sysconfig.get_config_var('Py_GIL_DISABLED')` (PEP 703 standard). * **Fallback:** Inspect ABI flags (`ABIFLAGS` or `SOABI`) for the `t` suffix (e.g., `cp313t`), handling cases on Windows where config variables may return `None` or empty strings. * **Caching:** Cache the result as `ORT_PYTHON_FREE_THREADED_DETECTED` (`BOOL`) to avoid re-running detection on every configure. --- ### 2. C++ Source (`onnxruntime/python/onnxruntime_pybind_module.cc`) * Updated the `PYBIND11_MODULE` definition to conditionally enable the GIL-free slot. * Uses `py::mod_gil_not_used()` (available in pybind11 ≥ 2.13) when `Py_GIL_DISABLED` is defined. --- ## Verification **Environment:** * Python 3.14t (Free-threaded) * Windows & Linux ### Before Change ```bash python3.14t -c "import onnxruntime" ``` Resulted in the `RuntimeWarning` shown above. ### After Change 1. **Build log confirms correct detection:** ```text -- Python_EXECUTABLE: D:\py314t\Scripts\python.exe -- Checking for Free-threaded Python environment... -- Py_GIL_DISABLED=1 detected: Enabling free-threaded support for onnxruntime_pybind11_state ``` 2. **Runtime behavior:** ```bash python3.14t -c "import onnxruntime" ``` Runs silently with no warnings, confirming the module loads successfully with the GIL disabled. ## Related Issue * [https://github.com/microsoft/onnxruntime/issues/26780](https://github.com/microsoft/onnxruntime/issues/26780)
Author
Parents
Loading