OnnxStack.StableDiffusion 0.7.0

The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org. Prefix Reserved
There is a newer version of this package available.
See the version list below for details.
dotnet add package OnnxStack.StableDiffusion --version 0.7.0
NuGet\Install-Package OnnxStack.StableDiffusion -Version 0.7.0
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="OnnxStack.StableDiffusion" Version="0.7.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add OnnxStack.StableDiffusion --version 0.7.0
#r "nuget: OnnxStack.StableDiffusion, 0.7.0"
#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.
// Install OnnxStack.StableDiffusion as a Cake Addin
#addin nuget:?package=OnnxStack.StableDiffusion&version=0.7.0

// Install OnnxStack.StableDiffusion as a Cake Tool
#tool nuget:?package=OnnxStack.StableDiffusion&version=0.7.0

OnnxStack.StableDiffusion - Onnx Stable Diffusion Services for .NET Applications

OnnxStack.StableDiffusion is a library that provides higher-level Stable Diffusion services for use in .NET applications. It offers extensive support for features such as dependency injection, .NET configuration implementations, ASP.NET Core integration, and IHostedService support.

Getting Started

OnnxStack.StableDiffusion can be found via the nuget package manager, download and install it.

PM> Install-Package OnnxStack.StableDiffusion

Microsoft.ML.OnnxRuntime

Depending on the devices you have and the platform you are running on, you will want to install the Microsoft.ML.OnnxRuntime package that best suits your needs.

CPU-GPU via Microsoft Drirect ML

PM> Install-Package Microsoft.ML.OnnxRuntime.DirectML

GPU support for both NVIDIA and AMD?

PM> Install-Package Microsoft.ML.OnnxRuntime.Gpu

.NET Core Registration

You can easily integrate OnnxStack.StableDiffusion into your application services layer. This registration process sets up the necessary services and loads the appsettings.json configuration.

Example: Registering OnnxStack.StableDiffusion

builder.Services.AddOnnxStackStableDiffusion();

.NET Console Application Example

Required Nuget Packages for example

Microsoft.Extensions.Hosting
Microsoft.Extensions.Logging
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OnnxStack.StableDiffusion.Common;
using OnnxStack.StableDiffusion.Config;

internal class Program
{
   static async Task Main(string[] _)
   {
      var builder = Host.CreateApplicationBuilder();
      builder.Logging.ClearProviders();
      builder.Services.AddLogging((loggingBuilder) => loggingBuilder.SetMinimumLevel(LogLevel.Error));

      // Add OnnxStack Stable Diffusion
      builder.Services.AddOnnxStackStableDiffusion();

      // Add AppService
      builder.Services.AddHostedService<AppService>();

      // Start
      await builder.Build().RunAsync();
   }
}

internal class AppService : IHostedService
{
   private readonly string _outputDirectory;
   private readonly IStableDiffusionService _stableDiffusionService;

   public AppService(IStableDiffusionService stableDiffusionService)
   {
      _stableDiffusionService = stableDiffusionService;
      _outputDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Images");
   }

   public async Task StartAsync(CancellationToken cancellationToken)
   {
      Directory.CreateDirectory(_outputDirectory);

      while (true)
      {
            System.Console.WriteLine("Please type a prompt and press ENTER");
            var prompt = System.Console.ReadLine();

            System.Console.WriteLine("Please type a negative prompt and press ENTER (optional)");
            var negativePrompt = System.Console.ReadLine();

            System.Console.WriteLine("Please enter image filepath for Img2Img and press ENTER (optional)");
            var inputImageFile = System.Console.ReadLine();

            var promptOptions = new PromptOptions
            {
               Prompt = prompt,
               NegativePrompt = negativePrompt,
               SchedulerType = SchedulerType.LMSScheduler,
               InputImage = new InputImage
               {
                  ImagePath = inputImageFile
               }
            };

            var schedulerOptions = new SchedulerOptions
            {
               Seed = Random.Shared.Next(),
               GuidanceScale = 7.5f,
               InferenceSteps = 30,
               Height = 512,
               Width = 512,
               Strength = 0.6f // Img2Img
            };

            System.Console.WriteLine("Generating Image...");
            var outputFilename = Path.Combine(_outputDirectory, $"{schedulerOptions.Seed}_{promptOptions.SchedulerType}.png");
            var result = await _stableDiffusionService.GenerateAsImageAsync(prompt, options);
            if (result is not null)
            { 
               await result.SaveAsPngAsync(outputFilename);
               System.Console.WriteLine($"Image Created, FilePath: {outputFilename}");
            }
      }
   }

   public Task StopAsync(CancellationToken cancellationToken)
   {
      return Task.CompletedTask;
   }
}

Configuration

The appsettings.json is the easiest option for configuring model sets. Below is an example of Stable Diffusion 1.5. The example adds the necessary paths to each model file required for Stable Diffusion, as well as any model-specific configurations. Each model can be assigned to its own device, which is handy if you have only a small GPU. This way, you can offload only what you need. There are limitations depending on the version of the Microsoft.ML.OnnxRuntime package you are using, but in most cases, you can split the load between CPU and GPU.

{
   "Logging": {
      "LogLevel": {
         "Default": "Information",
         "Microsoft.AspNetCore": "Warning"
      }
   },

   "OnnxStackConfig": {
      "Name": "StableDiffusion 1.5",
      "PadTokenId": 49407,
      "BlankTokenId": 49407,
      "TokenizerLimit": 77,
      "EmbeddingsLength": 768,
      "ScaleFactor": 0.18215,
      "ModelConfigurations": [{
            "Type": "Unet",
            "DeviceId": 0,
            "ExecutionProvider": "DirectML",
            "OnnxModelPath": "D:\\Repositories\\stable-diffusion-v1-5\\unet\\model.onnx"
         },
         {
            "Type": "Tokenizer",
            "DeviceId": 0,
            "ExecutionProvider": "Cpu",
            "OnnxModelPath": "D:\\Repositories\\stable-diffusion-v1-5\\cliptokenizer.onnx"
         },
         {
            "Type": "TextEncoder",
            "DeviceId": 0,
            "ExecutionProvider": "Cpu",
            "OnnxModelPath": "D:\\Repositories\\stable-diffusion-v1-5\\text_encoder\\model.onnx"
         },
         {
            "Type": "VaeEncoder",
            "DeviceId": 0,
            "ExecutionProvider": "Cpu",
            "OnnxModelPath": "D:\\Repositories\\stable-diffusion-v1-5\\vae_encoder\\model.onnx"
         },
         {
            "Type": "VaeDecoder",
            "DeviceId": 0,
            "ExecutionProvider": "Cpu",
            "OnnxModelPath": "D:\\Repositories\\stable-diffusion-v1-5\\vae_decoder\\model.onnx"
         },
         {
            "Type": "SafetyChecker",
            "IsDisabled": true,
            "DeviceId": 0,
            "ExecutionProvider": "Cpu",
            "OnnxModelPath": "D:\\Repositories\\stable-diffusion-v1-5\\safety_checker\\model.onnx"
         }]
   }
}
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on OnnxStack.StableDiffusion:

Package Downloads
Frank.SemanticKernel.Connectors.OnnxStack.StableDiffusion

Package Description

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on OnnxStack.StableDiffusion:

Repository Stars
saddam213/OnnxStack
C# Stable Diffusion using ONNX Runtime
Version Downloads Last updated
0.31.0 129 4/25/2024
0.27.0 133 3/31/2024
0.25.0 124 3/14/2024
0.23.1 108 3/1/2024
0.23.0 83 2/29/2024
0.22.0 102 2/23/2024
0.21.0 93 2/15/2024
0.19.0 105 2/1/2024
0.17.0 148 1/19/2024
0.16.0 105 1/11/2024
0.15.0 146 1/5/2024
0.14.0 126 12/27/2023
0.13.0 95 12/22/2023
0.12.0 123 12/15/2023
0.10.0 146 11/30/2023
0.9.0 136 11/23/2023
0.8.0 185 11/16/2023
0.7.0 127 11/9/2023
0.6.0 102 11/2/2023
0.5.0 129 10/27/2023
0.4.0 131 10/19/2023
0.3.1 130 10/9/2023
0.3.0 119 10/9/2023
0.2.0 124 10/3/2023
0.1.0 133 9/25/2023