Source code for multistorageclient.contrib.torch.core
1# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import os
17from typing import IO, Any, Union, cast
18
19import torch as _torch_module
20
21from ...pathlib import MultiStoragePath
22from ...shortcuts import open as msc_open
23
24_torch = cast(Any, _torch_module)
25
26
[docs]
27def load(f: Union[str, os.PathLike[str], IO[bytes]], *args: Any, **kwargs: Any) -> Any:
28 """
29 Adapt ``torch.load``.
30 """
31 if isinstance(f, str):
32 with msc_open(f, "rb", prefetch_file=True) as fp:
33 return _torch.load(fp, *args, **kwargs)
34 elif isinstance(f, MultiStoragePath):
35 with f.open("rb") as fp:
36 return _torch.load(fp, *args, **kwargs)
37 else:
38 return _torch.load(f, *args, **kwargs)
39
40
[docs]
41def save(obj: object, f: Union[str, os.PathLike[str], IO[bytes]], *args: Any, **kwargs: Any) -> Any:
42 """
43 Adapt ``torch.save``.
44 """
45 attributes_dict = {}
46 if "attributes" in kwargs:
47 attributes_dict = kwargs.pop("attributes")
48 if isinstance(f, str):
49 with msc_open(f, "wb", attributes=attributes_dict) as fp:
50 return _torch.save(obj, fp, *args, **kwargs)
51 elif isinstance(f, MultiStoragePath):
52 with f.open("wb", attributes=attributes_dict) as fp:
53 return _torch.save(obj, fp, *args, **kwargs)
54 else:
55 return _torch.save(obj, f, *args, **kwargs)