Source code for multistorageclient.contrib.torch

 1# SPDX-FileCopyrightText: Copyright (c) 2024 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
16from typing import Any
17
18import torch as _torch
19from torch.serialization import FILE_LIKE
20
21from ..shortcuts import open as msc_open
22from ..types import MSC_PROTOCOL
23
24
[docs] 25def load(f: FILE_LIKE, *args: Any, **kwargs: Any) -> Any: 26 """ 27 Adapt ``torch.load``. 28 """ 29 if isinstance(f, str) and f.startswith(MSC_PROTOCOL): 30 with msc_open(f, "rb") as fp: 31 return _torch.load(fp, *args, **kwargs) 32 else: 33 return _torch.load(f, *args, **kwargs)
34 35
[docs] 36def save(obj: object, f: FILE_LIKE, *args: Any, **kwargs: Any) -> Any: 37 """ 38 Adapt ``torch.save``. 39 """ 40 if isinstance(f, str) and f.startswith(MSC_PROTOCOL): 41 with msc_open(f, "wb") as fp: 42 return _torch.save(obj, fp, *args, **kwargs) 43 else: 44 return _torch.save(obj, f, *args, **kwargs)