|
| 1 | +using Microsoft.Extensions.Logging; |
| 2 | +using Microsoft.ML.OnnxRuntime.Tensors; |
| 3 | +using OnnxStack.Core; |
| 4 | +using OnnxStack.Core.Config; |
| 5 | +using OnnxStack.Core.Model; |
| 6 | +using OnnxStack.Core.Services; |
| 7 | +using OnnxStack.StableDiffusion.Common; |
| 8 | +using OnnxStack.StableDiffusion.Config; |
| 9 | +using OnnxStack.StableDiffusion.Enums; |
| 10 | +using OnnxStack.StableDiffusion.Helpers; |
| 11 | +using OnnxStack.StableDiffusion.Schedulers.InstaFlow; |
| 12 | +using System; |
| 13 | +using System.Diagnostics; |
| 14 | +using System.Linq; |
| 15 | +using System.Threading; |
| 16 | +using System.Threading.Tasks; |
| 17 | + |
| 18 | +namespace OnnxStack.StableDiffusion.Diffusers.InstaFlow |
| 19 | +{ |
| 20 | + public abstract class InstaFlowDiffuser : DiffuserBase, IDiffuser |
| 21 | + { |
| 22 | + /// <summary> |
| 23 | + /// Initializes a new instance of the <see cref="InstaFlowDiffuser"/> class. |
| 24 | + /// </summary> |
| 25 | + /// <param name="configuration">The configuration.</param> |
| 26 | + /// <param name="onnxModelService">The onnx model service.</param> |
| 27 | + public InstaFlowDiffuser(IOnnxModelService onnxModelService, IPromptService promptService, ILogger<InstaFlowDiffuser> logger) |
| 28 | + : base(onnxModelService, promptService, logger) { } |
| 29 | + |
| 30 | + |
| 31 | + /// <summary> |
| 32 | + /// Gets the type of the pipeline. |
| 33 | + /// </summary> |
| 34 | + public override DiffuserPipelineType PipelineType => DiffuserPipelineType.InstaFlow; |
| 35 | + |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Runs the scheduler steps. |
| 39 | + /// </summary> |
| 40 | + /// <param name="modelOptions">The model options.</param> |
| 41 | + /// <param name="promptOptions">The prompt options.</param> |
| 42 | + /// <param name="schedulerOptions">The scheduler options.</param> |
| 43 | + /// <param name="promptEmbeddings">The prompt embeddings.</param> |
| 44 | + /// <param name="performGuidance">if set to <c>true</c> [perform guidance].</param> |
| 45 | + /// <param name="progressCallback">The progress callback.</param> |
| 46 | + /// <param name="cancellationToken">The cancellation token.</param> |
| 47 | + /// <returns></returns> |
| 48 | + protected override async Task<DenseTensor<float>> SchedulerStepAsync(IModelOptions modelOptions, PromptOptions promptOptions, SchedulerOptions schedulerOptions, DenseTensor<float> promptEmbeddings, bool performGuidance, Action<int, int> progressCallback = null, CancellationToken cancellationToken = default) |
| 49 | + { |
| 50 | + // Get Scheduler |
| 51 | + using (var scheduler = GetScheduler(schedulerOptions)) |
| 52 | + { |
| 53 | + // Get timesteps |
| 54 | + var timesteps = GetTimesteps(schedulerOptions, scheduler); |
| 55 | + |
| 56 | + // Create latent sample |
| 57 | + var latents = await PrepareLatentsAsync(modelOptions, promptOptions, schedulerOptions, scheduler, timesteps); |
| 58 | + |
| 59 | + // Get Model metadata |
| 60 | + var metadata = _onnxModelService.GetModelMetadata(modelOptions, OnnxModelType.Unet); |
| 61 | + |
| 62 | + // Get the distilled Timestep |
| 63 | + var distilledTimestep = 1.0f / timesteps.Count; |
| 64 | + |
| 65 | + // Loop though the timesteps |
| 66 | + var step = 0; |
| 67 | + foreach (var timestep in timesteps) |
| 68 | + { |
| 69 | + step++; |
| 70 | + var stepTime = Stopwatch.GetTimestamp(); |
| 71 | + cancellationToken.ThrowIfCancellationRequested(); |
| 72 | + |
| 73 | + // Create input tensor. |
| 74 | + var inputLatent = performGuidance ? latents.Repeat(2) : latents; |
| 75 | + var inputTensor = scheduler.ScaleInput(inputLatent, timestep); |
| 76 | + var timestepTensor = CreateTimestepTensor(inputLatent, timestep); |
| 77 | + |
| 78 | + var outputChannels = performGuidance ? 2 : 1; |
| 79 | + var outputDimension = schedulerOptions.GetScaledDimension(outputChannels); |
| 80 | + using (var inferenceParameters = new OnnxInferenceParameters(metadata)) |
| 81 | + { |
| 82 | + inferenceParameters.AddInputTensor(inputTensor); |
| 83 | + inferenceParameters.AddInputTensor(timestepTensor); |
| 84 | + inferenceParameters.AddInputTensor(promptEmbeddings); |
| 85 | + inferenceParameters.AddOutputBuffer(outputDimension); |
| 86 | + |
| 87 | + var results = await _onnxModelService.RunInferenceAsync(modelOptions, OnnxModelType.Unet, inferenceParameters); |
| 88 | + using (var result = results.First()) |
| 89 | + { |
| 90 | + var noisePred = result.ToDenseTensor(); |
| 91 | + |
| 92 | + // Perform guidance |
| 93 | + if (performGuidance) |
| 94 | + noisePred = PerformGuidance(noisePred, schedulerOptions.GuidanceScale); |
| 95 | + |
| 96 | + // Scheduler Step |
| 97 | + latents = scheduler.Step(noisePred, timestep, latents).Result; |
| 98 | + |
| 99 | + latents = noisePred |
| 100 | + .MultiplyTensorByFloat(distilledTimestep) |
| 101 | + .AddTensors(latents); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + progressCallback?.Invoke(step, timesteps.Count); |
| 106 | + _logger?.LogEnd($"Step {step}/{timesteps.Count}", stepTime); |
| 107 | + } |
| 108 | + |
| 109 | + // Decode Latents |
| 110 | + return await DecodeLatentsAsync(modelOptions, promptOptions, schedulerOptions, latents); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + |
| 115 | + /// <summary> |
| 116 | + /// Creates the timestep tensor. |
| 117 | + /// </summary> |
| 118 | + /// <param name="latents">The latents.</param> |
| 119 | + /// <param name="timestep">The timestep.</param> |
| 120 | + /// <returns></returns> |
| 121 | + private DenseTensor<float> CreateTimestepTensor(DenseTensor<float> latents, int timestep) |
| 122 | + { |
| 123 | + var timestepTensor = new DenseTensor<float>(new[] { latents.Dimensions[0] }); |
| 124 | + timestepTensor.Fill(timestep); |
| 125 | + return timestepTensor; |
| 126 | + } |
| 127 | + |
| 128 | + |
| 129 | + /// <summary> |
| 130 | + /// Gets the scheduler. |
| 131 | + /// </summary> |
| 132 | + /// <param name="options">The options.</param> |
| 133 | + /// <param name="schedulerConfig">The scheduler configuration.</param> |
| 134 | + /// <returns></returns> |
| 135 | + protected override IScheduler GetScheduler(SchedulerOptions options) |
| 136 | + { |
| 137 | + return options.SchedulerType switch |
| 138 | + { |
| 139 | + SchedulerType.InstaFlow => new InstaFlowScheduler(options), |
| 140 | + _ => default |
| 141 | + }; |
| 142 | + } |
| 143 | + } |
| 144 | +} |
0 commit comments