From 53c6bd3fab62e77dcf451068052d404cfd812f9e Mon Sep 17 00:00:00 2001 From: Gregory Comer Date: Mon, 22 Sep 2025 11:19:31 -0600 Subject: [PATCH] Add pybind extension to the DLL search path on Windows (#14446) ### Summary When installing ExecuTorch from a wheel on Windows, the native pybinding extension DLL fails to load (https://github.com/pytorch/executorch/issues/14443). This is because it's not on the search path. From a quick Google search, it seems like the recommended way to handle this is to call `os.add_dll_directory` prior to loading the extension. I tested this locally by installing from wheel in a clean env and then patching the installed copy in site-packages. With this change, I was able to import executorch.extension.pybindings.portable_lib. I also ran the XNNPACK add op tests as a sanity check, which use pybindings. (cherry picked from commit b1aed62f8ff3ff82bc0be3c728f991de6b0ebee5) --- extension/pybindings/portable_lib.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/extension/pybindings/portable_lib.py b/extension/pybindings/portable_lib.py index da65983cf02..0982d55b474 100644 --- a/extension/pybindings/portable_lib.py +++ b/extension/pybindings/portable_lib.py @@ -13,6 +13,9 @@ This API is experimental and subject to change without notice. """ +import logging +import os +import sys import warnings as _warnings import executorch.exir._warnings as _exir_warnings @@ -28,6 +31,21 @@ # dependencies. import torch as _torch +logger = logging.getLogger(__name__) + +# Update the DLL search path on Windows. This is the recommended way to handle native +# extensions. +if sys.platform == "win32": + try: + # The extension DLL should be in the same directory as this file. + pybindings_dir = os.path.dirname(os.path.abspath(__file__)) + os.add_dll_directory(pybindings_dir) + except Exception as e: + logger.error( + "Failed to add the pybinding extension DLL to the search path. The extension may not work.", + e, + ) + # Let users import everything from the C++ _portable_lib extension as if this # python file defined them. Although we could import these dynamically, it # wouldn't preserve the static type annotations.