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, software11# 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 and14# limitations under the License.1516fromtypingimportAny,Dict,Union1718importnumpyas_np1920from..shortcutsimportopenasmsc_open21from..typesimportMSC_PROTOCOL2223
[docs]42defload(*args:Any,**kwargs:Any)->Union[_np.ndarray,Dict[str,_np.ndarray],_np.lib.npyio.NpzFile]:43"""44 Adapt ``numpy.load``.45 """4647file=args[0]ifargselsekwargs.get("file")48ifisinstance(file,str)andfile.startswith(MSC_PROTOCOL):49withmsc_open(file)asfp:50# For .npy with memmap mode != none, _np.load() will call format.open_memmap() underneath,51# Which require a file path string52# Refs:53# https://github.com/numpy/numpy/blob/main/numpy/lib/_npyio_impl.py#L47754# https://numpy.org/doc/stable/reference/generated/numpy.lib.format.open_memmap.html55#56# For the simplicity of the code, we always pass the file path to _np.load and let it convert the path57# to file-like object.5859# block until download is completed to ensure local path is available for the open() call within _np.load()60local_path=fp.get_local_path()61ifnotlocal_path:62raiseValueError(f"local_path={local_path} for the downloaded file[{file}] is not valid")63ifargs:64args=(local_path,)+args[1:]65else:66kwargs["file"]=local_path6768return_np.load(*args,**kwargs)# pyright: ignore [reportArgumentType, reportCallIssue]
6970
[docs]71defsave(*args:Any,**kwargs:Any)->None:72"""73 Adapt ``numpy.save``.74 """7576file=args[0]ifargselsekwargs.get("file")77ifisinstance(file,str)andfile.startswith(MSC_PROTOCOL):78# use context manager to make sure to upload the file once close() is called79withmsc_open(file,mode="wb")asfp:80ifargs:81args=(fp,)+args[1:]82else:83kwargs["file"]=fp8485_np.save(*args,**kwargs)# pyright: ignore [reportArgumentType, reportCallIssue]86else:87_np.save(*args,**kwargs)# pyright: ignore [reportArgumentType, reportCallIssue]