はじめに PyTorchで開発をしていると、テンソルデータをバイト列に変換(シリアライズ)して保存や転送を行う必要に迫られることがあります。本記事では、一般的な3つのシリアライズ方法について、その特徴とパフォーマンスを解説します。 シリアライズの3つの方法 1. numpy().tobytes() def tensor_to_buffer_numpy(tensor: torch.Tensor) -> bytes: if tensor.device.type != "cpu": tensor = tensor.cpu() return tensor.numpy().tobytes() def buffer_to_tensor_numpy(buffer: bytes, shape: tuple[int, ...], dtype: np.dtype) -> torch.Tensor: array

