tf.keras.models.load_model can't handle UNC paths
Hi, @early-stopper!
This issue generally arises because UNC paths are not supported by the underlying TensorFlow library. TensorFlow uses a local file system to store and load models, and UNC paths are not considered to be local files.
As you said you can use different saving formats as a workaround for now. 
We are already tracking this issue #62319  here, so please move this issue to closed status?
Thank you! Just to be clear: using a different saving format is a workaround for #62319 only. This issue here still occurs, despite me switching to the `.keras` format. The only workaround left is to replace the UNC path with a drive letter path to the same file with the drawback that every machine has to adapt this naming convention. However, this would still be the same path and still not be a local file, but works nevertheless, so I really see no reason why the original UNC path shouldn't work as well.

Handling UNC paths already worked in an earlier TensorFlow version. If you regard this not a supported feature, hence not a bug, feel free to close the issue. In that case, please consider this a feature request. You may also close this issue, if you consider it a duplicate to #62319. My reasoning here was that the 2 issues, though related, result in different errors and therefore are worth separate tickets. @early-stopper Thanks for the clarification here.
@SuryanarayanaY Could you please have a look at this?
Thank you! Hi @early-stopper ,

As per [documentation](https://www.tensorflow.org/api_docs/python/tf/keras/saving/load_model#:~:text=Args-,filepath,or%20pathlib.Path%20object%2C%20path%20to%20the%20saved%20model%20file.,-custom_objects) the argument `filepath` should be `str` or `pathlib.Path` object.

I have changed the path from `pathlib.WindowsPath(path)` to `pathlib.Path(path)` and its working fine. Attached [gist](https://colab.sandbox.google.com/gist/SuryanarayanaY/0283b8880b76c39791eb91766e4b9d5a/62337.ipynb) for same.

Could you please just try with `pathlib.Path(path) `and let us know if it works on WIndows too or not. Thanks! Hi @SuryanarayanaY,
first off, since `pathlib.WindowsPath` is a subclass of `pathlib.Path`, you would expect it to work as well in the sence of duck-typing. In fact, by the [documentation](https://docs.python.org/3/library/pathlib.html#pathlib.Path), executing `pathlib.Path(...)` will always create either a `pathlib.WindowsPath` (Windows) or a `pathlib.PosixPath` (Unix) anyway, depending on the underlying OS: on Windows, I get
```python
>> import pathlib
>> pathlib.Path('C:')
WindowsPath('C:')
```
In other words, replacing `pathlib.WindowsPath` with `pathlib.Path` really should not make a difference on a Windows system.  And in fact it doesn't, the resulting error will still be the same.

The reason why you can't reproduce the error, I suspect, is that Google Colab is running with an underlying Unix system, where `pathlib.Path` will produce an instance of `pathlib.PosixPath`. Try running `print(type(path))` in the notebook to confirm this. It seems that the problem only affects Windows systems. 
 > The reason why you can't reproduce the error, I suspect, is that Google Colab is running with an underlying Unix system, where `pathlib.Path` will produce an instance of `pathlib.PosixPath`. Try running `print(type(path))` in the notebook to confirm this. It seems that the problem only affects Windows systems.

Yeah,Because of environment limitations I requested to cross check with Windows OS. Thanks for confirmation. Could you confirm whether older TF versions works fine with this path earlier.Just to check whether it is a regression problem and when it was introduced if so.

Thanks! Also just want to know whether it works with keras-nightly (i.e keras3.0.dev). Could you able to check it if have bandwidth.

Thanks! I know that both this issue and #62319 did not occur when running the same code in TensorFlow 2.11 (and Python 3.10) and I first noted these problems with TensorFlow 2.12 (and Python 3.11). > Also just want to know whether it works with keras-nightly (i.e keras3.0.dev). Could you able to check it if have bandwidth.

I am a bit confused here, do you mean I should install [this](https://pypi.org/project/keras-nightly/) package in addition to tensorflow? I thought you now were supposed to use `tf.keras` as part of the TensorFlow package rather than `keras` as a standalone package. Or do you mean the [tf-nightly](https://pypi.org/project/tf-nightly/) build? How would I need to adjust the code above to test this? > I am a bit confused here, do you mean I should install [this](https://pypi.org/project/keras-nightly/) package in addition to tensorflow? I thought you now were supposed to use `tf.keras` as part of the TensorFlow package rather than `keras` as a standalone package. Or do you mean the [tf-nightly](https://pypi.org/project/tf-nightly/) build? How would I need to adjust the code above to test this?

Actually current `keras-nightly(Keras 3.0.Dev)` is supporting multi backend now as you may be aware.If your code don't have any TF code then you can test it with `Keras3`. The compatible keras package for tf-nightly is tf-keras-nightly which can be installed from [here](https://pypi.org/project/tf-keras-nightly/) and then import tf-keras and replace tf.keras with tf-keras.

With **Keras3** your code can be like below.

```
pip install keras-nightly
import keras
path = "\\\\localhost\\d$"
path = pathlib.WindowsPath(path)
path = path/'test'

path.mkdir(exist_ok=True, parents=True)

# Set up and save a dummy model
model = keras.Sequential()
model.add(keras.Input(shape=(16,)))
model.add(keras.layers.Dense(8))
model.save(path/'model.keras', save_format='keras')

model = keras.models.load_model(path/'model.keras')
```

With **tf-keras** your code can be like this.

```
pip install tf-keras-nightly
import tf_keras as tfk

path = "\\\\localhost\\d$"
path = pathlib.WindowsPath(path)
path = path/'test'

path.mkdir(exist_ok=True, parents=True)

# Set up and save a dummy model
model = tfk.Sequential()
model.add(keras.Input(shape=(16,)))
model.add(keras.layers.Dense(8))
model.save(path/'model.keras', save_format='keras')

model = keras.models.load_model(path/'model.keras')
```

 Please also refer to #62332 I tested both variants and can confirm that the issue does not occur when using `keras-nightly`, but still occurs with `tf-nightly` + `tf_keras_nightly`. Hi @early-stopper ,

To ensure tensorflow uses Keras2 you need to set the environment variable using `os.environ["TF_USE_LEGACY_KERAS"]="1"`.  Please setup and try again.

Thanks!

 Since some months have passed, it may be worth double checking that we still are on the same page. I set up a new project and used `pip install tensorflow`. This installed `tensorflow==2.15.0` and `keras==2.15.0`. The following code uses a UNC path to first save a model and then load it again:
```python
import pathlib

import tensorflow as tf

def main():
    path = "\\\\localhost\\c$"
    path = pathlib.Path(path)
    path = path/'test'

    path.mkdir(exist_ok=True, parents=True)

    model = tf.keras.Sequential()
    model.add(tf.keras.Input(shape=(16,)))
    model.add(tf.keras.layers.Dense(8))

    model.save(path/'model.keras')

    model = tf.keras.models.load_model(path/'model.keras')

if __name__ == "__main__":
    main()
```
Saving the model with the `keras` format works fine, but loading the model raises the error
```python
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 89: invalid start byte
```
This error is seemingly related to the use of a UNC path, because replacing `path = "\\\\localhost\\c$"` with its named equivalent `path = "C:"` resolves the error.

When modifying the snippet as suggested by adding `os.environ["TF_USE_LEGACY_KERAS"]="1"`, I arrive at
```python
import os
import pathlib

os.environ["TF_USE_LEGACY_KERAS"]="1"
import tensorflow as tf

def main():
    path = "\\\\localhost\\c$"
    path = pathlib.Path(path)
    path = path/'test'

    path.mkdir(exist_ok=True, parents=True)

    model = tf.keras.Sequential()
    model.add(tf.keras.Input(shape=(16,)))
    model.add(tf.keras.layers.Dense(8))

    model.save(path/'model.keras')

    model = tf.keras.models.load_model(path/'model.keras')

if __name__ == "__main__":
    main()
```
and now get the error
```python
ImportError: Keras cannot be imported. Check that it is installed.
```
This error can be handled by additionally running `pip install tf-keras`. But then, the original error pops up again.
### Issue type

Bug

### Have you reproduced the bug with TensorFlow Nightly?

No

### Source

binary

### TensorFlow version

tf 2.14.0

### Custom code

Yes

### OS platform and distribution

Windows 10

### Mobile device

_No response_

### Python version

3.11.6

### Bazel version

_No response_

### GCC/compiler version

_No response_

### CUDA/cuDNN version

_No response_

### GPU model and memory

_No response_

### Current behavior?

I recently issued a bug when saving tf.keras.Models in the `SavedModel` format using a UNC path like
`model.save("\\\\ComputerName\\path\\to\\folder"),`
see #62319. A workaround for the time being is to use the `.keras` save_format instead, so the following works:
`model.save("\\\\ComputerName\\path\\to\\folder\\model.keras", save_format='keras').`
However, loading that model, again using the same UNC path, still is broken: running
`tf.keras.models.load_model("\\\\ComputerName\\path\\to\\folder\\model.keras")`
raises the error shown below.

The problem once again seems to be with the UNC path, because replacing it with a path using the drive's name letter resolves the problem: if `J:` is set as an alias for `\\ComputerName`, then
`tf.keras.models.load_model("J:\\path\\to\\folder\\model.keras")`
works as expected. But doing this is not really a solution for me, because then I would have to rely on others to use the same letter J for the network drive in order to run my code.

### Standalone code to reproduce the issue

```shell
# The issue can be reproduced using, for instance, the path to the root of the D: drive, expressed as UNC path
path = "\\\\localhost\\d$"
path = pathlib.WindowsPath(path)
path = path/'test'

# If we uncomment the following line and replace the path string with one that includes the drive's letter, no error occurs.
#path = pathlib.WindowsPath("D:\\test")

path.mkdir(exist_ok=True, parents=True)

# Set up and save a dummy model
model = tf.keras.Sequential()
model.add(tf.keras.Input(shape=(16,)))
model.add(tf.keras.layers.Dense(8))
model.save(path/'model.keras', save_format='keras')

# Loading the model using the same UNC path raises a UnicodeDecodeError
model = tf.keras.models.load_model(path/'model.keras')
```


### Relevant log output

```shell
Traceback (most recent call last):
  File "D:\keras_load_error.py", line 26, in <module>
    main()
  File "D:\keras_load_error.py", line 23, in main
    model = tf.keras.models.load_model(path/'model.keras')
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\.venv\Lib\site-packages\keras\src\saving\saving_api.py", line 254, in load_model
    return saving_lib.load_model(
           ^^^^^^^^^^^^^^^^^^^^^^
  File "D:\.venv\Lib\site-packages\keras\src\saving\saving_lib.py", line 281, in load_model
    raise e
  File "D:\.venv\Lib\site-packages\keras\src\saving\saving_lib.py", line 234, in load_model
    ) as gfile_handle, zipfile.ZipFile(gfile_handle, "r") as zf:
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\zipfile.py", line 1302, in __init__
    self._RealGetContents()
  File "C:\Program Files\Python311\Lib\zipfile.py", line 1365, in _RealGetContents
    endrec = _EndRecData(fp)
             ^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\zipfile.py", line 292, in _EndRecData
    fpin.seek(0, 2)
  File "D:\.venv\Lib\site-packages\tensorflow\python\util\deprecation.py", line 588, in new_func
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "D:\.venv\Lib\site-packages\tensorflow\python\lib\io\file_io.py", line 139, in seek
    self._preread_check()
  File "D:\.venv\Lib\site-packages\tensorflow\python\lib\io\file_io.py", line 77, in _preread_check
    self._read_buf = _pywrap_file_io.BufferedInputStream(
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 89: invalid start byte
```
