Onnxify.Safetensors 0.3.11

dotnet add package Onnxify.Safetensors --version 0.3.11
                    
NuGet\Install-Package Onnxify.Safetensors -Version 0.3.11
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Onnxify.Safetensors" Version="0.3.11" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Onnxify.Safetensors" Version="0.3.11" />
                    
Directory.Packages.props
<PackageReference Include="Onnxify.Safetensors" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Onnxify.Safetensors --version 0.3.11
                    
#r "nuget: Onnxify.Safetensors, 0.3.11"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Onnxify.Safetensors@0.3.11
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Onnxify.Safetensors&version=0.3.11
                    
Install as a Cake Addin
#tool nuget:?package=Onnxify.Safetensors&version=0.3.11
                    
Install as a Cake Tool

Onnxify.Safetensors

Onnxify.Safetensors is the safetensors-focused package in this repository for reading metadata, indexing tensors, and working with safetensors-backed storage from .NET.

Install

dotnet add package Onnxify.Safetensors

Why This Package Exists

Modern ML workflows often keep model weights in .safetensors because the format is deterministic, self-describing, and easier to validate than ad-hoc binary blobs. The problem on the .NET side is usually not "how do I read bytes from a file", but:

  • how to safely parse safetensors headers and validate offsets;
  • how to inspect tensor names, dtypes, and shapes without inventing a custom parser;
  • how to work with tensor payloads as structured views instead of manual byte slicing;
  • how to produce valid .safetensors archives from .NET code for model export and tooling scenarios.

Onnxify.Safetensors exists to give .NET a dedicated safetensors surface for those tasks. It lets you read metadata, deserialize archives into zero-copy tensor views, slice tensor payloads, and serialize new safetensors files in a format-compatible way.

What It Provides

  • Read safetensors metadata and tensor layout information.
  • Work with tensor slices and tensor-backed storage abstractions.
  • Support safetensors-related flows that integrate with the broader Onnxify toolchain.

Code Examples

Create and Round-Trip a Safetensors File

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Onnxify.Safetensors;

var values = new float[] { 1.0f, 2.0f, 3.5f, 4.5f };
var bytes = new byte[values.Length * sizeof(float)];
Buffer.BlockCopy(values, 0, bytes, 0, bytes.Length);

var tensor = new TensorView(
    dtype: DataType.F32,
    shape: new ulong[] { 2, 2 },
    data: bytes
);

SafeTensors.SerializeToFile(
    data:
    [
        new KeyValuePair<string, TensorView>("weights", tensor),
    ],
    metadata: new Dictionary<string, string>
    {
        ["framework"] = "onnxify",
        ["purpose"] = "roundtrip-demo",
    },
    path: "weights.safetensors"
);

var archive = SafeTensors.Deserialize(File.ReadAllBytes("weights.safetensors"));
var loaded = archive.Tensor("weights");
var loadedValues = MemoryMarshal.Cast<byte, float>(loaded.Data.Span).ToArray();

Console.WriteLine(string.Join(", ", archive.Names()));
Console.WriteLine($"Shape: [{string.Join(", ", loaded.Shape)}]");
Console.WriteLine(string.Join(", ", loadedValues.Select(x => x.ToString(CultureInfo.InvariantCulture))));

Read Only Metadata Before Touching Tensor Payloads

This example assumes weights.safetensors already exists, for example from the previous example or from your own export pipeline.

using System;
using System.IO;
using Onnxify.Safetensors;

var buffer = File.ReadAllBytes("weights.safetensors");
var metadata = SafeTensors.ReadMetadata(buffer).Metadata;

foreach (var name in metadata.OffsetKeys())
{
    var info = metadata.Info(name)!;
    Console.WriteLine($"{name}: {info.DataType} [{string.Join(", ", info.Shape)}]");
}

if (metadata.MetadataEntries is not null)
{
    foreach (var pair in metadata.MetadataEntries)
    {
        Console.WriteLine($"{pair.Key} = {pair.Value}");
    }
}

Slice a Tensor View Without Rebuilding the Whole Archive

This example also assumes weights.safetensors already exists and contains a tensor named weights.

using System;
using System.IO;
using Onnxify.Safetensors;

var archive = SafeTensors.Deserialize(File.ReadAllBytes("weights.safetensors"));
var tensor = archive.Tensor("weights");

var rowSlice = tensor.Slice(
    new NarrowTensorIndexer(TensorBounds.Included(0), TensorBounds.Excluded(1)),
    new NarrowTensorIndexer(TensorBounds.Unbounded(), TensorBounds.Unbounded())
);

foreach (var chunk in rowSlice)
{
    Console.WriteLine($"Chunk bytes: {chunk.Length}");
}

Recommendations

  • Use Onnxify.Safetensors when your source of truth is a .safetensors file and you need a low-level, format-aware .NET API instead of a framework-specific wrapper.
  • Prefer SafeTensors.ReadMetadata(...) when you only need names, shapes, dtypes, or archive metadata. It keeps the workflow explicit and is a good fit for validation, indexing, and diagnostics.
  • Prefer SafeTensors.Deserialize(...) plus TensorView when you need to inspect or slice payload bytes without copying the whole archive into new tensor objects.
  • Use SerializeToFile(...) when you are generating weights from .NET tooling and want deterministic safetensors output rather than hand-building headers and offsets.
  • If your real task is saving or loading TorchSharp module state, reach for the higher-level Onnxify.TorchSharp extensions such as SaveStateAsSafetensors(...) and LoadStateFromSafetensors(...), which build on top of this package.
  • Keep this package as the safetensors boundary and do dtype conversion at the edge of your app. In practice, that usually means storing bytes in TensorView and materializing float[], Half[], or other typed values only where they are actually needed.

Status

This package is still evolving, but it is the dedicated safetensors surface in the repo.

Repository

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Onnxify.Safetensors:

Package Downloads
Onnxify.TorchSharp

TorchSharp-to-ONNX export layer for translating TorchSharp modules and model structure into explicit Onnxify graph operations.

DeepSharp.Import.PyTorch

Reads a network PyTorch trained into the same network written with DeepSharp: new SafetensorsFile(network, loss).Read(stream) for a safetensors file, new TorchSaveFile(network, loss).Read(stream) for the .pt or .pth file torch.save(model.state_dict(), file) writes. Every number goes into the slot its name names — in a network of steps, the step called as the module is called — a linear layer's weights turned round, a convolution's kernel, along one, two or three axes, laid out channels last, a recurrent layer's weights and multi-head attention's projections turned round with their gates and their blocks in PyTorch's order, the rows a flatten makes of series, images or volumes read place by place where PyTorch reads them channel by channel — and the network and its loss come back, to serve, to measure or to train further. A safetensors file is read by a port of safetensors' own reader, so a file it refuses is refused here in its words. The pickle torch.save writes is a program, so it is read by an interpreter that carries out only what PyTorch's own weights-only reader carries out and builds nothing a file names but what a state dictionary is made of: any other name is refused where the file names it, before anything is looked up, built or run. Every fault among the tensors is named at once by the tensor's name, and a network takes all of a file's numbers or none of them.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.11 752 9/5/2026
0.3.10 185 8/6/2026
0.3.9 177 7/8/2026
0.3.8 164 6/30/2026
0.3.7 169 6/27/2026
0.3.6 160 6/26/2026
0.3.5 161 6/23/2026
0.3.4 169 6/19/2026
0.3.3 165 6/15/2026
0.3.2 171 6/14/2026
0.3.1 148 6/12/2026
0.3.0 157 6/11/2026
0.2.0 166 6/8/2026
0.1.4 166 6/2/2026
0.1.3 165 6/1/2026
0.1.2 156 5/28/2026
0.1.1 155 5/20/2026
0.1.0 170 5/18/2026
0.0.0.15 151 5/18/2026
0.0.0.14 160 5/17/2026
Loading failed

## 0.3.11

- Updated the package version for the coordinated Onnxify 0.3.11 release.

## 0.3.9

- Aligned the package version with the 0.3.9 Onnxify package family release.

## 0.3.6

- Aligned the package version with the 0.3.6 Onnxify package family release.

## 0.3.5

- Aligned the package version with the 0.3.5 Onnxify package family release.

## 0.3.3

- Kept the safetensors package aligned with the TorchSharp integration changes that allow safetensors state helpers to work with any `torch.nn.Module` subclass.

## 0.3.2

- Aligned the package version with the 0.3.2 Onnxify package family release.

## 0.3.0

- Aligned the package version with the 0.3.0 Onnxify package family release.

## 0.2.0

- Aligned the package version with the 0.2.0 Onnxify package family release.

## 0.1.2

- Added a generic `SafeTensors` value API with `Set<T>(...)`, `Get<T>(...)`, and `Remove(...)` so callers can store supported CLR arrays without manually marshaling bytes into `TensorView`.
- Added async file helpers with `LoadFromFileAsync(...)`, `SerializeToFileAsync(...)`, and `SaveToFileAsync(...)`.
- Added round-trip coverage for all supported generic value element types.

## 0.1.1

- Aligned the package version with the 0.1.1 Onnxify package family release.

## 0.0.0.1

- Initial release