MSDN Community

PyTorch .NET Interop

Posted by JaneDoe • 3 days ago • 27 replies

I'm experimenting with integrating PyTorch models directly into a .NET Core application. I found TorchSharp but I'm curious about other ways to achieve efficient interop, especially for GPU tensors. Any suggestions or best practices?

Sample Code

using TorchSharp;
using static TorchSharp.torch;

var model = torch.jit.load("model.pt");
var input = torch.randn(new long[] { 1, 3, 224, 224 }, device: device);
var output = model.forward(input);
Console.WriteLine(output.shape);
pytorch dotnet interop gpu

Discussion

MikeR 2 days ago

You can also try ONNX Runtime which has a .NET API and supports exporting PyTorch models to ONNX.

SaraK 1 day ago

I used TorchSharp with CUDA and got ~30% speedup compared to CPU. Make sure to set the device correctly.

Related Topics