Search code examples
pythonpytorch

Pytorch Torch.save FileNotFoundError


When I try to call torch.save to save my model in a "tmp_file", it raises a FileNotFoundError. The traceback is as follows:

Traceback (most recent call last):
File "C:/.../python/simulations/hdr.py", line 234, in 
test_hdr_continuous()
File "C:/.../python/simulations/hdr.py", line 195, in test_hdr_continuous
model = fit_mdn(X[:split], y[:split], nepochs=20)
File "C:\...\python\simulations\continuous.py", line 192, in fit_mdn
torch.save(model, tmp_file)
File "C:\...\python\venv\lib\site-packages\torch\serialization.py", line 161, in save
return _with_file_like(f, "wb", lambda f: _save(obj, f, pickle_module, pickle_protocol))
File "C:\...\python\venv\lib\site-packages\torch\serialization.py", line 116, in _with_file_like
f = open(f, mode)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmp_file_4358f298-a1d9-4c81-9e44-db4d8f1b4319'

It is weird that everything works perfectly on my mac, but I got this error on my Windows desktop.


Solution

  • As shmee observed, you are trying to write to /tmp/[...] on a Windows machine. Therefore you get FileNotFoundError.
    To make your code OS agnostic, you may find python's tempfile package useful, especially NamedTemporaryFile: this function creates a temporary file and returns its name, so you can access/use it in your program.