Recursive AI

Migrate from TorchSharp to managed C# tensors

Compare CPU output, tensor lifetimes, and limits on dtype, device, and gradients.

To migrate from TorchSharp to managed C# tensors, start with CPU float32 and check who owns each tensor view.

OneModel is a free, open-source managed C# tensor and neural network library from Recursive AI, licensed MIT OR Apache-2.0. The core package has no native binaries. NuGet: RecursiveAI.OneModel · GitHub: OneModel.

OneModel 1.3.0NuGet
dotnet add package RecursiveAI.OneModel --version 1.3.0

Port the same tensor expression

Use a separate .NET 10 console project for each side. Both programs apply ReLU to an affine expression, multiply the result by the transposed input, and sum the product.

After: OneModel

Program.cs.NET 10
using RecursiveAI.OneModel.Tensors;
 
using Tensor x = Tensor.FromSpan<float>([1, 2, 3, 4], 2, 2);
using var scope = new ActivationScope();
Tensor y = Ops.Relu(x * 2f - 3f);
Tensor product = Ops.MatMul(y, x.T());
Console.WriteLine($"ReLU: {string.Join(", ", y.ToArray<float>())}");
Console.WriteLine($"Product: {string.Join(", ", product.ToArray<float>())}");
Console.WriteLine($"Sum: {Ops.Sum(product).Item<float>()}");

Before: TorchSharp

The TorchSharp install guide recommends the bundled CPU package when you want the matching LibTorch backend. This example uses TorchSharp-cpu 0.107.0.

TorchSharp-cpu 0.107.0NuGet
dotnet add package TorchSharp-cpu --version 0.107.0
Program.cs.NET 10
using TorchSharp;
 
using var scope = torch.NewDisposeScope();
var x = torch.tensor(new float[] { 1, 2, 3, 4 }, new long[] { 2, 2 });
var y = (x * 2f - 3f).relu();
var product = torch.matmul(y, x.transpose(0, 1));
Console.WriteLine($"ReLU: {string.Join(", ", y.data<float>().ToArray())}");
Console.WriteLine($"Product: {string.Join(", ", product.data<float>().ToArray())}");
Console.WriteLine($"Sum: {product.sum().item<float>()}");

Both programs printed the same values on CPU. The product is shown in row order:

Both runsOutput
ReLU: 0, 1, 3, 5
Product: 2, 4, 13, 29
Sum: 48

Map the tensor calls and ownership

The calls below are exercised in the two programs. For scope ownership, see TorchSharp’s memory guide and OneModel’s tensor ownership rules.

TorchSharpOneModel 1.3.0
torch.tensorTensor.FromSpan
Pass int dimensions, not a long[].
x.relu()Ops.Relu(x)
Keep scalar arithmetic as operators.
torch.matmul, x.transpose(0, 1)Ops.MatMul, x.T()
Transpose swaps axes; * is elementwise.
data<float>(), then ToArray()ToArray<float>()
Copy to an array. For a contiguous tensor, Data<float>() gives a span.
sum(), then item<float>()Ops.Sum, then Item<float>()
Reduce first. Item reads a one-element tensor.
torch.NewDisposeScope()ActivationScope
The scope owns operation results; dispose the input separately.

In OneModel, x.T() shares storage with x. Don’t dispose the view independently: doing so also releases the input’s storage. Read a scalar or copy the result to an array before leaving the scope. If you need the result as a tensor, use the documented scope escape with ActivationScope.Keep and give the result an owner.

What doesn’t carry over

  • Eager device and dtype: This OneModel tensor path is CPU-only and eager arithmetic uses float32. Integer tensors serve as indices or labels; the porting guide distinguishes other I/O types from supported eager arithmetic. Check dtype and device requirements before swapping packages.
  • Operator and gradient coverage: Don’t assume that changing names ports every operation. Check the autograd operator list if a caller needs gradients. Higher-order derivatives aren’t recorded, and traced graphs don’t capture dynamic control flow.
  • Model inference: If you already have an ONNX export, try the ONNX inference path instead of rewriting each tensor operation. It’s a separate API; check the operator coverage against your graph.

Before removing TorchSharp, compare shape and values at each boundary on a representative input. Include a non-square matrix to catch swapped axes, and test any result that must stay alive past the scope.