TorchSharp.PyBridge is an extension library for TorchSharp, providing seamless interoperability between .NET and Python for model serialization. It simplifies the process of saving and loading PyTorch models in a .NET environment, enabling developers to easily develop models in both .NET and Python and transfer models easily.
-
load_py Method: Easily load PyTorch models saved in the standard Python format (using
torch.save) directly into TorchSharp.This only works for when the
state_dictwas saved and not the whole model, see example below. -
save_py Method: Save TorchSharp models in a format that can be directly loaded in PyTorch (using
torch.load), offering cross-platform model compatibility.
As of version 1.1.0, there is now support for loading and saving the optim.state_dict in the PyTorch format as well.
TorchSharp.PyBridge is available on NuGet. You can install it using the following command:
dotnet add package TorchSharp.PyBridgeInstall-Package TorchSharp.PyBridge- .NET SDK
- TorchSharp library
Saving the model in Python:
import torch
model = ...
torch.save(model.state_dict(), 'path_to_your_model.pth')Loading it in C#:
using TorchSharp.PyBridge;
var model = ...;
model.load_py("path_to_your_model.pth");To save a model in a format compatible with PyTorch:
using TorchSharp.PyBridge;
var model = ...;
model.save_py("path_to_save_model.pth");And loading it in in Python:
import torch
model = ...
model.load_state_dict(torch.load('path_to_save_model.pth'))Contributions to TorchSharp.PyBridge are welcome.
This project makes use of the pickle library, a Java and .NET implementation of Python's pickle serialization protocol, developed by Irmen de Jong. The pickle library plays a vital role in enabling the serialization features within TorchSharp.PyBridge. We extend our thanks to the developer for their significant contributions to the open-source community. For more details about the pickle library, please visit their GitHub repository.
For support, questions, or feedback, please open an issue in the GitHub repository.