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, cast
18
19import torch as _torch_module
20
21from ...pathlib import MultiStoragePath
22from ...shortcuts import open as msc_open
23from ...types import StreamingWriterOptions
24
25_torch = cast(Any, _torch_module)
26
27
[docs] 28def load(f: str | os.PathLike[str] | IO[bytes], *args: Any, **kwargs: Any) -> Any: 29 """ 30 Adapt ``torch.load``. 31 """ 32 if isinstance(f, str): 33 with msc_open(f, "rb", prefetch_file=True) as fp: 34 return _torch.load(fp, *args, **kwargs) 35 elif isinstance(f, MultiStoragePath): 36 with f.open("rb") as fp: 37 return _torch.load(fp, *args, **kwargs) 38 else: 39 return _torch.load(f, *args, **kwargs)
40 41
[docs] 42def save( 43 obj: object, 44 f: str | os.PathLike[str] | IO[bytes], 45 *args: Any, 46 writer_options: StreamingWriterOptions | None = None, 47 **kwargs: Any, 48) -> Any: 49 """ 50 Adapt ``torch.save``. 51 52 :param writer_options: Stream the object through a bounded multipart upload. Only valid when ``f`` is a path. 53 """ 54 attributes_dict = {} 55 if "attributes" in kwargs: 56 attributes_dict = kwargs.pop("attributes") 57 if isinstance(f, str): 58 with msc_open(f, "wb", attributes=attributes_dict, writer_options=writer_options) as fp: 59 return _torch.save(obj, fp, *args, **kwargs) 60 elif isinstance(f, MultiStoragePath): 61 with f.open("wb", attributes=attributes_dict, writer_options=writer_options) as fp: 62 return _torch.save(obj, fp, *args, **kwargs) 63 else: 64 if writer_options is not None: 65 raise ValueError(f"writer_options needs f to be a str or MultiStoragePath, got {type(f).__name__}.") 66 return _torch.save(obj, f, *args, **kwargs)