# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Tuple
import torch
from safetensors.torch import load, save
import nvflare.fuel.utils.fobs.dots as dots
from nvflare.fuel.f3.streaming.download_service import Downloadable
from nvflare.fuel.utils.fobs.datum import DatumManager
from nvflare.fuel.utils.fobs.decomposers.via_downloader import ViaDownloaderDecomposer
from ...fuel.f3.cellnet.cell import Cell
from .tensor_downloader import TensorDownloadable, download_tensors
[docs]
class SerializationModule(torch.nn.Module):
def __init__(self, tensor):
super().__init__()
self.register_buffer("saved_tensor", tensor)
[docs]
class TensorDecomposer(ViaDownloaderDecomposer):
def __init__(self):
ViaDownloaderDecomposer.__init__(self, 1024 * 1024 * 2, "tensor_")
[docs]
def supported_type(self):
return torch.Tensor
[docs]
def get_download_dot(self) -> int:
return dots.TENSOR_DOWNLOAD
[docs]
def to_downloadable(self, items: dict, max_chunk_size: int, fobs_ctx: dict) -> Downloadable:
return TensorDownloadable(items, max_chunk_size)
[docs]
def download(
self,
from_fqcn: str,
ref_id: str,
per_request_timeout: float,
cell: Cell,
secure=False,
optional=False,
abort_signal=None,
) -> Tuple[str, dict]:
return download_tensors(
from_fqcn,
ref_id,
per_request_timeout,
cell,
secure,
optional,
abort_signal,
)
[docs]
def native_decompose(self, target: torch.Tensor, manager: DatumManager = None) -> bytes:
# save the tensor to bytes using safetensors
dummy = {"t": target}
return save(dummy)
[docs]
def native_recompose(self, data: bytes, manager: DatumManager = None) -> torch.Tensor:
# load safetensors generated bytes
dummy = load(data)
if not isinstance(dummy, dict):
raise ValueError(f"failed to load data: should be dict but got {type(dummy)}")
return dummy.get("t")