Repository navigation
Use Unicode friendly API in fused kernel related code - #49781
skyline75489 wants to merge 12 commits into
Conversation
💊 CI failures summary and remediationsAs of commit d85b66f (more details on the Dr. CI page):
🕵️ 1 new failure recognized by patternsThe following CI failures do not appear to be due to upstream breakages:
|
|
@peterjc123 This is me trying to add more supports for Unicode. Once again I'm not sure how can I test this. The |
|
@skyline75489 This is pretty easy. Since |
|
@peterjc123 I tried to find a proper place to put the tests. I couldn't find the test case which is specifically for temp path in https://github.com/pytorch/pytorch/blob/master/test/test_jit_fuser.py . Is this the right place? |
Yep. |
|
@peterjc123 I checked the file and found most of the tests are for CUDA instead of CPU. I found one case Am I missing something? I'm simply using |
|
@skyline75489 I guess you'll need to activate the VC env first. In run_test.py, we skip this test script if VC env is not activated. |
|
I'm trying |
|
OK I kinda understand. It needs the env var |
| env.s("program", program); | ||
| std::string cmd = format(check_exists_string, env); | ||
| #ifdef _MSC_VER | ||
| return (run(cmd.c_str()) == 0); |
There was a problem hiding this comment.
@peterjc123 This one is kinda a bugfix/improvement. On Windows using system will not find cl correctly. Do you feel comfortable I add this in the PR?
|
@peterjc123 So I managed to make |
Summary: The command used here is essentially `where cl.exe`. By using `system()` we will not be able to find cl.exe unless we are using VS Developer Prompt, which makes `activate()` meaningless. Change `system()` to `run()` fixes this. Found during #49781. Pull Request resolved: #50085 Reviewed By: smessmer Differential Revision: D25782054 Pulled By: ezyang fbshipit-source-id: e8e3cac903a73f3bd78def667ebe0e93201814c8
| cmd = [sys.executable, os.path.basename(__file__), 'TestFuser.test_abs_cpu'] | ||
| legacy_jit_flag = '--jit_executor=legacy' | ||
| for v in sys.argv: | ||
| if v == legacy_jit_flag: |
There was a problem hiding this comment.
This is bad. I don't know how to do this correctly without breaking other things.
There was a problem hiding this comment.
It is not that bad. A slightly better way is to use multiprocessing, but it is way more complex here. If you want to do that, you may write sth like the following.
import multiprocessing as mp
def test_abs_cpu_unicode_temp_dir(self):
### It is a bit tricky in the next line that `xxx` has to be a global function instead of a class function.
pre_tmp_value = os.environ.get("TMP", None)
os.environ["TMP"] = "中文路径"
p = mp.Process(target=xxx)
p.start()
os.environ["TMP"] = pre_tmp_value
p.join()
self.assertEqual(p.exitcode, 0)There was a problem hiding this comment.
I don't like the idea of messing the original structures of the test cases so I didn't use multiprocessing. That should also be a valid way.
There was a problem hiding this comment.
Another way to do this is just make a hermetic Python file (not a full test script) to run the test in question. There are a few examples of this in the test suite currently
There was a problem hiding this comment.
I did give it a try, but I found it tedious to create another file for just this one case. This is one of those cases we know it should work (the A to W conversion). I think we can leave this as it is for now.
| self._test_fused_abs() | ||
|
|
||
| @unittest.skipIf(IS_SANDCASTLE, "NYI: fuser CPU support for Sandcastle") | ||
| @enable_cpu_fuser |
There was a problem hiding this comment.
Nit: should we mark this test as Windows only, as it is a bit useless for other platform that use the hardcoded tmp path /tmp?
There was a problem hiding this comment.
That's a valid point. On Windows the login user name may very likely contain Unicode characters, and the default temp path is C:\Users\USERNAME\AppData\Local\Temp. On other platforms I cannot think of a way it will contains Unicode characters, either.
There was a problem hiding this comment.
@skyline75489 That's not the point. Since the jit fuser uses /tmp/ as the temporary directory (see https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.cpp#L41-L42), there is no way it will get a Unicode-related problem on platforms except Windows. So would you please skip this test case for those platforms?
| cmd = [sys.executable, os.path.basename(__file__), 'TestFuser.test_abs_cpu'] | ||
| legacy_jit_flag = '--jit_executor=legacy' | ||
| for v in sys.argv: | ||
| if v == legacy_jit_flag: |
There was a problem hiding this comment.
It is not that bad. A slightly better way is to use multiprocessing, but it is way more complex here. If you want to do that, you may write sth like the following.
import multiprocessing as mp
def test_abs_cpu_unicode_temp_dir(self):
### It is a bit tricky in the next line that `xxx` has to be a global function instead of a class function.
pre_tmp_value = os.environ.get("TMP", None)
os.environ["TMP"] = "中文路径"
p = mp.Process(target=xxx)
p.start()
os.environ["TMP"] = pre_tmp_value
p.join()
self.assertEqual(p.exitcode, 0)|
I have also personally confirmed that without this PR, the test case will break. |
Codecov Report
@@ Coverage Diff @@
## master #49781 +/- ##
=======================================
Coverage 80.68% 80.68%
=======================================
Files 1901 1901
Lines 206255 206255
=======================================
+ Hits 166421 166425 +4
+ Misses 39834 39830 -4 |
| size_needed); | ||
| return wstr; | ||
| } | ||
| inline std::string u16u8(const std::wstring& wstr) { |
There was a problem hiding this comment.
FWIW, probably don't actually want to inline this
|
This all looks plausible but it's all terrifically fiddly string manipulation code. I'll go ahead and merge as soon as @peterjc123 gives the goahead. |
| if (GetProcAddress(GetModuleHandle("KERNEL32.DLL"), "AddDllDirectory") != NULL) { | ||
| theModule = LoadLibraryExA( | ||
| name, | ||
| if (GetProcAddress(GetModuleHandleW(L"KERNEL32.DLL"), "AddDllDirectory") != NULL) { |
There was a problem hiding this comment.
nit: This change is not necessary, right?
There was a problem hiding this comment.
Yeah I just want to make sure other people would choose GetModuleHandleW in similar places in the future.
|
|
||
| // Checking whether the environment is already activated | ||
| if (getenv("VSCMD_ARG_TGT_ARCH")) { | ||
| if (_wgetenv(L"VSCMD_ARG_TGT_ARCH")) { |
There was a problem hiding this comment.
Yeah I just like to make the W usage unified in this method.
| struct stat st; | ||
| if (stat(path.c_str(), &st) == -1 || !(st.st_mode & _S_IFDIR)) { | ||
| path += L"\\VC\\Auxiliary\\Build"; | ||
| struct _stati64 st; |
There was a problem hiding this comment.
Strictly speaking, _stat64 should be used here. See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/stat-functions?view=msvc-160.
Yes, I agree. It could be made simpler by limiting the usages to only the callers of the Windows API without messing them everywhere. But it could be done in subsequent PRs. |
| if (stat(path.c_str(), &st) == -1 || !(st.st_mode & _S_IFDIR)) { | ||
| path += L"\\VC\\Auxiliary\\Build"; | ||
| struct _stati64 st; | ||
| if (_wstati64(path.c_str(), &st) == -1 || !(st.st_mode & _S_IFDIR)) { |
There was a problem hiding this comment.
And here, _wstat64 is better.
facebook-github-bot
left a comment
There was a problem hiding this comment.
@ezyang has imported this pull request. If you are a Facebook employee, you can view this diff on Phabricator.
Summary: The command used here is essentially `where cl.exe`. By using `system()` we will not be able to find cl.exe unless we are using VS Developer Prompt, which makes `activate()` meaningless. Change `system()` to `run()` fixes this. Found during pytorch#49781. Pull Request resolved: pytorch#50085 Reviewed By: smessmer Differential Revision: D25782054 Pulled By: ezyang fbshipit-source-id: e8e3cac903a73f3bd78def667ebe0e93201814c8
On Windows, `_load_dll_libraries` loads every DLL in torch/lib at import time. The glob was added in pytorch#35362 (2020-03) because `caffe2_nvrtc.dll` was loaded lazily by name from `CUDAHooks.cpp`, and plain `LoadLibraryW` does not search directories registered with `AddDllDirectory`, so the by-name load failed on Python 3.8. Two later changes made that moot: pytorch#45674 (2020-10) switched CUDA builds to the in-tree LazyNVRTC, so `caffe2_nvrtc.dll` is only loaded by name on ROCm, and pytorch#49781 (2021-01) switched `at::DynamicLibrary` to `LoadLibraryExW` with `LOAD_LIBRARY_SEARCH_DEFAULT_DIRS`, which does search the directories that `os.add_dll_directory` registers. The preload also has a cost: it loads libraries that are only meant to be loaded on demand, such as the INSTALL_TEST libraries (`aoti_custom_ops`, `torchbind_test`, `jitbackend_test`, `backend_with_compiler`), and any failure in one of them aborts `import torch` (pytorch#199894, pytorch#179024, pytorch#182123). This PR removes the glob and the fallback PATH patching that only mattered on systems without `AddDllDirectory`, keeping `os.add_dll_directory` for torch/lib and the other DLL directories. Everything that remains in torch/lib is a link-time dependency of `_C.pyd` or of a library it pulls in, which Windows resolves through the registered directories. Test Plan Trunk CI has no Windows CUDA test shards (removed in pytorch#139336); the Windows CPU build and all its test shards pass with this change, and the Windows CUDA build passes. The CUDA side was verified on a Windows 11 VM with an RTX 2060 (driver 610.88) using the 2026-10-26 cu132 nightly wheel with this change applied to its `torch/__init__.py`: import, `torch.cuda.is_available()`, cuDNN conv2d, cuBLAS matmul, cuFFT, cuRAND, cuSOLVER and a jiterator (NVRTC) kernel all pass, 8 of the 13 DLLs in torch/lib end up resident, and a deliberately broken stray DLL in torch/lib no longer aborts the import (with the glob it fails with WinError 193). Lint: ``` lintrunner -a torch/__init__.py ``` Authored with an AI assistant (Claude Code); the analysis and the change were reviewed by the human author. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Linked issue or supporting maintainer Part of #199894. Supersedes #200856 and #199925: without the preload there is no list of test-only DLLs to maintain. ## BC-breaking? No for the supported configurations. `import torch` no longer preloads every DLL in `torch/lib`; libraries that are loaded on demand are now loaded only on demand, and the `PATH` fallback for systems without `AddDllDirectory` (pre Windows 8 without KB2533623) is gone. ## Summary (human written only) On Windows we are preloading all libraries in torch/lib. This is somewhat costly and leads to occasional problems. Furthermore, it is likely no longer necessary because the loading code has become smarter and is now able to load dependencies on demand. This PR is here to test that hypothesis in CI. ## Agent details (if applicable) Analysis and change prepared with Claude Code, reviewed by me. The commit message carries the full reasoning. Agent notes: The Windows loader has preloaded every DLL in `torch/lib` since #35362, because `caffe2_nvrtc.dll` was loaded by name from `CUDAHooks.cpp` and plain `LoadLibraryW` did not search directories registered with `AddDllDirectory`. Two later changes made that moot: #45674 (2020-10) switched CUDA builds to the in-tree LazyNVRTC, so `caffe2_nvrtc.dll` is only loaded by name on ROCm, and #49781 (2021-01) moved `at::DynamicLibrary` to `LoadLibraryExW` with `LOAD_LIBRARY_SEARCH_DEFAULT_DIRS`, which searches what `os.add_dll_directory` registers. Meanwhile the preload keeps turning on-demand libraries into import-time failures (#199894, #179024, #182123). The glob only ever preloaded torch's own DLLs with the default search flags; the NVIDIA wheel directories come from the cuda-pathfinder loop (and, on CI, from the toolkit bin dir fallback), which this PR does not touch. Tested on hardware, since trunk has had no Windows CUDA test shards since #139336: Windows 11 VM with an RTX 2060 (driver 610.88), 2026-10-26 cu132 nightly wheel, `torch/__init__.py` replaced by this PR's version (hash-checked against the base commit). Results: - With the stock cuda-pathfinder 1.8.4 the import fails on a clean machine with and without this change, for a reason outside this PR (below). The failure point moves from a `WinError 126` on `shm.dll` in the glob to "DLL load failed while importing _C". - With a per-library `try` in the pathfinder loop (not part of this PR), import, `torch.cuda.is_available()`, cuDNN conv2d, cuBLAS matmul, cuFFT, cuRAND, cuSOLVER and a jiterator kernel (NVRTC) all pass with the glob removed. 8 of 13 `torch/lib` DLLs are resident afterwards; `caffe2_nvrtc`, `torch_global_deps`, `nvToolsExt64_1`, `libiompstubs5md` and `torch.dll` were never needed. - The #199894 mechanism reproduces: a broken stray `zz_broken_test.dll` in `torch/lib` aborts `import torch` with the glob (WinError 193) and is ignored without it. Found on the way, independent of this PR: the stock cu132 Windows nightly does not import on a clean machine. `nvidia-cuda-cupti` 13.2.86 ships `cupti64_2026.1.2.dll`, which cuda-pathfinder 1.8.4 does not know; the pathfinder loop in `torch/__init__.py` is one `try` around all eleven libraries, so the CUPTI miss also skips cuDNN, `nvidia\cudnn\bin` is never registered, and `cudnn64_9.dll` (a static import of `torch_python.dll` and `torch_cuda.dll`) cannot be found. CUPTI itself still resolves, because a later library in the loop registers the shared `nvidia\cu13\bin` directory. CI does not see this: the Windows CUDA wheel smoke test runs on a T4 with the CUDA toolkit and cuDNN installed under Program Files, and `torch/__init__.py` adds that directory to the search path. A per-library `try` fixes the import with a warning; a pathfinder release that knows the name fixes it silently. CI on this PR: the full CPU suite on the 12 `win-vs2022-cpu-py3` shards, the `win-vs2022-cuda13.2-py3` build, and the `binaries_wheel` smoke tests for every Python version (CUDA wheels on a T4: import, CUDA tensor, magma, cuDNN, RNN and CNN smoke; XPU wheels import on CPU runners). Not covered: the full CUDA test suite on Windows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #202206 Approved by: https://github.com/atalman
## Linked issue or supporting maintainer Part of pytorch#199894. Supersedes pytorch#200856 and pytorch#199925: without the preload there is no list of test-only DLLs to maintain. ## BC-breaking? No for the supported configurations. `import torch` no longer preloads every DLL in `torch/lib`; libraries that are loaded on demand are now loaded only on demand, and the `PATH` fallback for systems without `AddDllDirectory` (pre Windows 8 without KB2533623) is gone. ## Summary (human written only) On Windows we are preloading all libraries in torch/lib. This is somewhat costly and leads to occasional problems. Furthermore, it is likely no longer necessary because the loading code has become smarter and is now able to load dependencies on demand. This PR is here to test that hypothesis in CI. ## Agent details (if applicable) Analysis and change prepared with Claude Code, reviewed by me. The commit message carries the full reasoning. Agent notes: The Windows loader has preloaded every DLL in `torch/lib` since pytorch#35362, because `caffe2_nvrtc.dll` was loaded by name from `CUDAHooks.cpp` and plain `LoadLibraryW` did not search directories registered with `AddDllDirectory`. Two later changes made that moot: pytorch#45674 (2020-10) switched CUDA builds to the in-tree LazyNVRTC, so `caffe2_nvrtc.dll` is only loaded by name on ROCm, and pytorch#49781 (2021-01) moved `at::DynamicLibrary` to `LoadLibraryExW` with `LOAD_LIBRARY_SEARCH_DEFAULT_DIRS`, which searches what `os.add_dll_directory` registers. Meanwhile the preload keeps turning on-demand libraries into import-time failures (pytorch#199894, pytorch#179024, pytorch#182123). The glob only ever preloaded torch's own DLLs with the default search flags; the NVIDIA wheel directories come from the cuda-pathfinder loop (and, on CI, from the toolkit bin dir fallback), which this PR does not touch. Tested on hardware, since trunk has had no Windows CUDA test shards since pytorch#139336: Windows 11 VM with an RTX 2060 (driver 610.88), 2026-10-26 cu132 nightly wheel, `torch/__init__.py` replaced by this PR's version (hash-checked against the base commit). Results: - With the stock cuda-pathfinder 1.8.4 the import fails on a clean machine with and without this change, for a reason outside this PR (below). The failure point moves from a `WinError 126` on `shm.dll` in the glob to "DLL load failed while importing _C". - With a per-library `try` in the pathfinder loop (not part of this PR), import, `torch.cuda.is_available()`, cuDNN conv2d, cuBLAS matmul, cuFFT, cuRAND, cuSOLVER and a jiterator kernel (NVRTC) all pass with the glob removed. 8 of 13 `torch/lib` DLLs are resident afterwards; `caffe2_nvrtc`, `torch_global_deps`, `nvToolsExt64_1`, `libiompstubs5md` and `torch.dll` were never needed. - The pytorch#199894 mechanism reproduces: a broken stray `zz_broken_test.dll` in `torch/lib` aborts `import torch` with the glob (WinError 193) and is ignored without it. Found on the way, independent of this PR: the stock cu132 Windows nightly does not import on a clean machine. `nvidia-cuda-cupti` 13.2.86 ships `cupti64_2026.1.2.dll`, which cuda-pathfinder 1.8.4 does not know; the pathfinder loop in `torch/__init__.py` is one `try` around all eleven libraries, so the CUPTI miss also skips cuDNN, `nvidia\cudnn\bin` is never registered, and `cudnn64_9.dll` (a static import of `torch_python.dll` and `torch_cuda.dll`) cannot be found. CUPTI itself still resolves, because a later library in the loop registers the shared `nvidia\cu13\bin` directory. CI does not see this: the Windows CUDA wheel smoke test runs on a T4 with the CUDA toolkit and cuDNN installed under Program Files, and `torch/__init__.py` adds that directory to the search path. A per-library `try` fixes the import with a warning; a pathfinder release that knows the name fixes it silently. CI on this PR: the full CPU suite on the 12 `win-vs2022-cpu-py3` shards, the `win-vs2022-cuda13.2-py3` build, and the `binaries_wheel` smoke tests for every Python version (CUDA wheels on a T4: import, CUDA tensor, magma, cuDNN, RNN and CNN smoke; XPU wheels import on CPU runners). Not covered: the full CUDA test suite on Windows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: pytorch#202206 Approved by: https://github.com/atalman
## Linked issue or supporting maintainer Part of pytorch#199894. Supersedes pytorch#200856 and pytorch#199925: without the preload there is no list of test-only DLLs to maintain. ## BC-breaking? No for the supported configurations. `import torch` no longer preloads every DLL in `torch/lib`; libraries that are loaded on demand are now loaded only on demand, and the `PATH` fallback for systems without `AddDllDirectory` (pre Windows 8 without KB2533623) is gone. ## Summary (human written only) On Windows we are preloading all libraries in torch/lib. This is somewhat costly and leads to occasional problems. Furthermore, it is likely no longer necessary because the loading code has become smarter and is now able to load dependencies on demand. This PR is here to test that hypothesis in CI. ## Agent details (if applicable) Analysis and change prepared with Claude Code, reviewed by me. The commit message carries the full reasoning. Agent notes: The Windows loader has preloaded every DLL in `torch/lib` since pytorch#35362, because `caffe2_nvrtc.dll` was loaded by name from `CUDAHooks.cpp` and plain `LoadLibraryW` did not search directories registered with `AddDllDirectory`. Two later changes made that moot: pytorch#45674 (2020-10) switched CUDA builds to the in-tree LazyNVRTC, so `caffe2_nvrtc.dll` is only loaded by name on ROCm, and pytorch#49781 (2021-01) moved `at::DynamicLibrary` to `LoadLibraryExW` with `LOAD_LIBRARY_SEARCH_DEFAULT_DIRS`, which searches what `os.add_dll_directory` registers. Meanwhile the preload keeps turning on-demand libraries into import-time failures (pytorch#199894, pytorch#179024, pytorch#182123). The glob only ever preloaded torch's own DLLs with the default search flags; the NVIDIA wheel directories come from the cuda-pathfinder loop (and, on CI, from the toolkit bin dir fallback), which this PR does not touch. Tested on hardware, since trunk has had no Windows CUDA test shards since pytorch#139336: Windows 11 VM with an RTX 2060 (driver 610.88), 2026-10-26 cu132 nightly wheel, `torch/__init__.py` replaced by this PR's version (hash-checked against the base commit). Results: - With the stock cuda-pathfinder 1.8.4 the import fails on a clean machine with and without this change, for a reason outside this PR (below). The failure point moves from a `WinError 126` on `shm.dll` in the glob to "DLL load failed while importing _C". - With a per-library `try` in the pathfinder loop (not part of this PR), import, `torch.cuda.is_available()`, cuDNN conv2d, cuBLAS matmul, cuFFT, cuRAND, cuSOLVER and a jiterator kernel (NVRTC) all pass with the glob removed. 8 of 13 `torch/lib` DLLs are resident afterwards; `caffe2_nvrtc`, `torch_global_deps`, `nvToolsExt64_1`, `libiompstubs5md` and `torch.dll` were never needed. - The pytorch#199894 mechanism reproduces: a broken stray `zz_broken_test.dll` in `torch/lib` aborts `import torch` with the glob (WinError 193) and is ignored without it. Found on the way, independent of this PR: the stock cu132 Windows nightly does not import on a clean machine. `nvidia-cuda-cupti` 13.2.86 ships `cupti64_2026.1.2.dll`, which cuda-pathfinder 1.8.4 does not know; the pathfinder loop in `torch/__init__.py` is one `try` around all eleven libraries, so the CUPTI miss also skips cuDNN, `nvidia\cudnn\bin` is never registered, and `cudnn64_9.dll` (a static import of `torch_python.dll` and `torch_cuda.dll`) cannot be found. CUPTI itself still resolves, because a later library in the loop registers the shared `nvidia\cu13\bin` directory. CI does not see this: the Windows CUDA wheel smoke test runs on a T4 with the CUDA toolkit and cuDNN installed under Program Files, and `torch/__init__.py` adds that directory to the search path. A per-library `try` fixes the import with a warning; a pathfinder release that knows the name fixes it silently. CI on this PR: the full CPU suite on the 12 `win-vs2022-cpu-py3` shards, the `win-vs2022-cuda13.2-py3` build, and the `binaries_wheel` smoke tests for every Python version (CUDA wheels on a T4: import, CUDA tensor, magma, cuDNN, RNN and CNN smoke; XPU wheels import on CPU runners). Not covered: the full CUDA test suite on Windows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: pytorch#202206 Approved by: https://github.com/atalman
See #47422