[inductor] fix open temp file failed on Windows. (#159342)

Fix open temp file failed on Windows. Error message:
<img width="1181" height="239" alt="image" src="https://github.com/user-attachments/assets/e4a6f438-cb06-44c6-959b-0a6a49d2f44f" />

Here two option to fix this issue: https://stackoverflow.com/questions/66744497/python-tempfile-namedtemporaryfile-cant-use-generated-tempfile
1. `tempfile.NamedTemporaryFile` must setup `delete=False` on Windows
2. Use `WritableTempFile` to handle this case on Windows.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/159342
Approved by: https://github.com/jansel
This commit is contained in:
Xu Han
2025-07-31 04:58:02 +00:00
committed by PyTorch MergeBot
parent c44efc3755
commit d5c719ec3c

View File

@ -1621,6 +1621,36 @@ class CudaKernelParamCache:
return cls.cache.keys()
class WritableTempFile:
"""
Avoid "Permission denied error" on Windows:
with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file:
# Not writable on Windows:
# https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile
Example:
with WritableTempFile("w", suffix=".gv") as temp_file:
tree.to_dotfile(temp_file.name)
"""
def __init__(
self, mode: str = "w", *, encoding: Any = None, suffix: Any = None
) -> None:
self.mode = mode
self.encoding = encoding
self.suffix = suffix
def __enter__(self) -> Any:
self.temp_file = tempfile.NamedTemporaryFile(
self.mode, encoding=self.encoding, suffix=self.suffix, delete=False
)
return self.temp_file
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.temp_file.close()
os.unlink(self.temp_file.name)
class AotCodeCompiler:
"""
Compile AOT Inductor generated code.
@ -1735,7 +1765,17 @@ class AotCodeCompiler:
)
# Log the AOTInductor wrapper and kernel code, if needed.
with tempfile.NamedTemporaryFile("w+") as t:
with WritableTempFile("w+") as t:
"""
Avoid "Permission denied error" on Windows:
with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file:
# Not writable on Windows:
# https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile
Example:
with WritableTempFile("w", suffix=".gv") as temp_file:
tree.to_dotfile(temp_file.name)
"""
t.writelines((wrapper_code, "\n", kernel_code, "\n"))
t.flush()
V.debug.output_code(t.name, extension="cpp")