< Summary

Information
Class: InferenceEngine.Core.BaseStreamingInferenceEngine<T1, T2, T3>
Assembly: InferenceEngine.Core
File(s): /home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Core/BaseStreamingInferenceEngine.cs
Line coverage
98%
Covered lines: 145
Uncovered lines: 2
Coverable lines: 147
Total lines: 406
Line coverage: 98.6%
Branch coverage
96%
Covered branches: 98
Total branches: 102
Branch coverage: 96%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_CurrentOptions()100%11100%
get_DefaultStreamingOptions()100%11100%
PredictAsync()100%22100%
PredictStreamingAsync()100%1414100%
SampleNextToken(...)96.42%565698.33%
Argmax(...)100%44100%
NthLargest(...)100%1414100%
.ctor(...)100%11100%
Compare(...)100%11100%
RunStep(...)50%22100%
CloneAsPastKeyValue(...)100%22100%
.ctor(...)100%22100%
get_Values()100%11100%
Dispose()100%22100%
DisposeNamedOnnxValues(...)75%4475%
PreProcessWithContext(...)100%11100%
PostProcessWithContext(...)100%11100%

File(s)

/home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Core/BaseStreamingInferenceEngine.cs

#LineLine coverage
 1using System;
 2using System.Buffers;
 3using System.Collections.Generic;
 4using System.Runtime.CompilerServices;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using Microsoft.Extensions.Logging;
 8using Microsoft.ML.OnnxRuntime;
 9using Microsoft.ML.OnnxRuntime.Tensors;
 10
 11namespace InferenceEngine.Core;
 12
 13/// <summary>
 14/// Reuses <see cref="BaseInferenceEngine{TInput, TOutput}"/> for session/acceleration/warmup/
 15/// model-download/diagnostics, and adds an autoregressive decode loop driven by engine-supplied
 16/// hooks. One-shot consumers see no change: <see cref="PredictAsync"/> is routed through the
 17/// streaming loop and reduced via <see cref="BuildFinalOutput"/>.
 18/// </summary>
 19/// <typeparam name="TInput">Raw engine input (e.g. a prompt).</typeparam>
 20/// <typeparam name="TOutput">Fully-reduced one-shot result.</typeparam>
 21/// <typeparam name="TStep">One streamed model-level step.</typeparam>
 22public abstract class BaseStreamingInferenceEngine<TInput, TOutput, TStep>
 23    : BaseInferenceEngine<TInput, TOutput>, IStreamingInferenceEngine<TInput, TOutput, TStep>
 24{
 25    // Single-in-flight-stream guard (§6.9): KV-cache state is per-run; a second concurrent
 26    // stream on the same instance must be rejected.
 27    private int _activeStreams;
 28
 29    /// <summary>Creates the streaming engine, forwarding options + logger to the base.</summary>
 30    protected BaseStreamingInferenceEngine(InferenceEngineOptions options, ILogger? logger = null)
 4631        : base(options, logger)
 32    {
 4633    }
 34
 35    /// <summary>
 36    /// The <see cref="StreamingOptions"/> for the stream currently in progress, or <see langword="null"/>
 37    /// outside a stream. Hooks (<see cref="BuildStepInputs"/>/<see cref="ProcessStepOutputs"/>) read this
 38    /// to honor <see cref="StreamingOptions.IncludePrefillInStream"/>, <see cref="StreamingOptions.EosTokenIds"/>, etc.
 39    /// </summary>
 36240    protected StreamingOptions? CurrentOptions { get; private set; }
 41
 42    /// <summary>Default streaming options used when a caller passes <see langword="null"/>.</summary>
 1843    protected virtual StreamingOptions DefaultStreamingOptions => new();
 44
 45    /// <summary>One-shot behavior is preserved: run the stream to completion and reduce it.</summary>
 46    public override async Task<TOutput> PredictAsync(TInput input)
 47    {
 248        var steps = new List<TStep>();
 2249        await foreach (var step in PredictStreamingAsync(input).ConfigureAwait(false))
 950            steps.Add(step);
 251        return BuildFinalOutput(steps);
 252    }
 53
 54    /// <inheritdoc/>
 55    public async IAsyncEnumerable<TStep> PredictStreamingAsync(
 56        TInput input,
 57        StreamingOptions? options = null,
 58        [EnumeratorCancellation] CancellationToken cancellationToken = default)
 59    {
 2860        await LoadAsync().ConfigureAwait(false);
 61
 2862        if (Interlocked.CompareExchange(ref _activeStreams, 1, 0) != 0)
 163            throw new InvalidOperationException(
 164                "Only one in-flight stream is supported per engine instance (§6.9).");
 65
 2766        var opts = options ?? DefaultStreamingOptions;
 2767        CurrentOptions = opts;
 2768        object? state = null;
 69
 70        try
 71        {
 38672            for (int step = 0; step < opts.MaxSteps; step++)
 73            {
 19174                cancellationToken.ThrowIfCancellationRequested();
 75
 18876                var (inputs, buildContext) = BuildStepInputs(input, state, step);
 77
 78                IDisposableReadOnlyCollection<DisposableNamedOnnxValue> outputs;
 79                try
 80                {
 18881                    outputs = RunStep(inputs);
 18882                }
 83                finally
 84                {
 18885                    DisposeNamedOnnxValues(inputs);
 86                }
 87
 88                TStep yielded;
 89                object? nextState;
 90                bool isEos;
 91                try
 92                {
 18893                    (yielded, nextState, isEos) = ProcessStepOutputs(outputs, buildContext);
 18794                }
 95                finally
 96                {
 18897                    outputs.Dispose();
 98                }
 99
 100                // Guard against an engine that reuses (mutates in place) the same state object
 101                // across steps: disposing the prior reference would also dispose the live state.
 187102                if (state is IDisposable priorState && !ReferenceEquals(state, nextState))
 6103                    priorState.Dispose();
 187104                state = nextState;
 187105                yield return yielded;
 106
 204107                if (isEos) yield break;
 108            }
 2109        }
 110        finally
 111        {
 112            // Reset per-run state and release the in-flight guard on every exit path
 113            // (success, EOS, MaxSteps, exception, and cancellation).
 27114            if (state is IDisposable finalState)
 6115                finalState.Dispose();
 27116            state = null;
 27117            CurrentOptions = null;
 27118            Interlocked.Exchange(ref _activeStreams, 0);
 119        }
 23120    }
 121
 122    // ---- Model-aware hooks: the engine knows its own I/O contract. ----------------
 123
 124    /// <summary>
 125    /// Build the ONNX inputs for a given step and return the carry-forward context.
 126    /// <paramref name="step"/> == 0 means prefill (full prompt); step &gt; 0 means decode
 127    /// (feed the previous step's <c>present_key_values</c> back as <c>past_key_values</c>).
 128    /// </summary>
 129    protected abstract (List<NamedOnnxValue> Inputs, object? BuildContext) BuildStepInputs(
 130        TInput input, object? state, int step);
 131
 132    /// <summary>
 133    /// Parse one forward pass's outputs into a streamed step, the next carry-forward state, and an
 134    /// end-of-sequence signal. The engine is responsible for token-level EOS detection against
 135    /// <see cref="StreamingOptions.EosTokenIds"/> (it holds the sampled token); the base enforces
 136    /// the returned <c>IsEos</c> flag and <see cref="StreamingOptions.MaxSteps"/>.
 137    /// </summary>
 138    protected abstract (TStep Step, object? NextState, bool IsEos) ProcessStepOutputs(
 139        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> outputs, object? buildContext);
 140
 141    /// <summary>Reduce the accumulated steps into the final one-shot <typeparamref name="TOutput"/>.</summary>
 142    protected abstract TOutput BuildFinalOutput(IReadOnlyList<TStep> steps);
 143
 144    /// <summary>
 145    /// Samples one token id from a vocab-length logit row. Greedy argmax when
 146    /// <see cref="StreamingOptions.Sampling"/>'s temperature is disabled (0); otherwise
 147    /// temperature-scaled softmax sampling with optional top-k / top-p filtering.
 148    /// Engines call this from <see cref="ProcessStepOutputs"/> when they want the default sampler.
 149    /// </summary>
 150    protected virtual int SampleNextToken(ReadOnlySpan<float> logits)
 151    {
 143152        if (logits.IsEmpty) return -1;
 153
 141154        var sampling = CurrentOptions?.Sampling;
 141155        if (sampling is null || sampling.Temperature <= 0f)
 20156            return Argmax(logits);
 157
 158        // Temperature scaling.
 121159        float temperature = sampling.Temperature;
 121160        int vocab = logits.Length;
 161
 162        // Rent vocab-sized buffers instead of allocating them on every step. For a typical
 163        // vocabulary (e.g. Phi-3's 32,006) a fresh double[32006] would land on the Large Object Heap
 164        // each token, causing severe GC pressure during generation. Rented arrays may be larger than
 165        // `vocab`, so every loop below is bounded by `vocab` and helpers take a vocab-length span.
 166        // Declare the rented arrays as nullable outside the try so a rent that throws cannot leak an
 167        // already-rented buffer; the finally block returns whichever buffers were successfully rented.
 121168        float[]? scaled = null;
 121169        double[]? probs = null;
 121170        int[]? order = null;
 171        try
 172        {
 121173            scaled = ArrayPool<float>.Shared.Rent(vocab);
 121174            probs = ArrayPool<double>.Shared.Rent(vocab);
 175
 968176            for (int i = 0; i < vocab; i++)
 363177                scaled[i] = logits[i] / temperature;
 178
 179            // Top-k filtering: keep only the k highest logits, mask the rest to -inf.
 121180            int topK = sampling.TopK;
 121181            if (topK > 0 && topK < vocab)
 182            {
 31183                float cutoff = NthLargest(scaled.AsSpan(0, vocab), topK);
 248184                for (int i = 0; i < vocab; i++)
 93185                    if (scaled[i] < cutoff)
 60186                        scaled[i] = float.NegativeInfinity;
 187            }
 188
 189            // Softmax (numerically stable: subtract max of finite values).
 121190            float max = float.NegativeInfinity;
 968191            for (int i = 0; i < vocab; i++)
 513192                if (scaled[i] > max) max = scaled[i];
 121193            if (float.IsNegativeInfinity(max))
 1194                return Argmax(logits); // everything masked; fall back to greedy
 195
 120196            double sum = 0d;
 960197            for (int i = 0; i < vocab; i++)
 198            {
 360199                double p = Math.Exp(scaled[i] - max);
 360200                probs[i] = p;
 360201                sum += p;
 202            }
 203
 204            // Top-p (nucleus) filtering: keep the smallest set of highest-prob tokens whose
 205            // cumulative probability reaches p, sorted descending.
 120206            float topP = sampling.TopP;
 120207            if (topP > 0f && topP < 1f)
 208            {
 30209                order = ArrayPool<int>.Shared.Rent(vocab);
 330210                for (int i = 0; i < vocab; i++) order[i] = i;
 211                // Sort token indices by descending probability without per-step allocation: a struct
 212                // comparer is specialized by MemoryExtensions.Sort and never boxes, unlike
 213                // Comparer<int>.Create(lambda), which allocates a Comparer + delegate every token.
 30214                order.AsSpan(0, vocab).Sort(new DescendingProbabilityIndexComparer(probs));
 30215                double cum = 0d;
 30216                bool reached = false;
 240217                for (int i = 0; i < vocab; i++)
 218                {
 90219                    if (reached)
 220                    {
 60221                        probs[order[i]] = 0d;
 222                    }
 223                    else
 224                    {
 30225                        cum += probs[order[i]] / sum;
 60226                        if (cum >= topP) reached = true;
 227                    }
 228                }
 229                // Renormalize the kept set.
 30230                double keptSum = 0d;
 330231                for (int i = 0; i < vocab; i++) keptSum += probs[i];
 30232                if (keptSum <= 0d) return Argmax(logits);
 330233                for (int i = 0; i < vocab; i++) probs[i] /= keptSum;
 234            }
 235            else
 236            {
 990237                for (int i = 0; i < vocab; i++) probs[i] /= sum;
 238            }
 239
 240            // Sample from the resulting distribution.
 120241            double r = Random.Shared.NextDouble();
 120242            double acc = 0d;
 480243            for (int i = 0; i < vocab; i++)
 244            {
 240245                acc += probs[i];
 360246                if (r < acc) return i;
 247            }
 0248            return vocab - 1;
 249        }
 250        finally
 251        {
 121252            if (scaled is not null)
 121253                ArrayPool<float>.Shared.Return(scaled);
 121254            if (probs is not null)
 121255                ArrayPool<double>.Shared.Return(probs);
 121256            if (order is not null)
 30257                ArrayPool<int>.Shared.Return(order);
 121258        }
 121259    }
 260
 261    private static int Argmax(ReadOnlySpan<float> logits)
 262    {
 21263        int best = 0;
 21264        float max = logits[0];
 192334265        for (int i = 1; i < logits.Length; i++)
 266        {
 96146267            if (logits[i] > max)
 268            {
 14269                max = logits[i];
 14270                best = i;
 271            }
 272        }
 21273        return best;
 274    }
 275
 276    /// <summary>Returns the cutoff value of the k-th largest element (allocation-free partial sort).
 277    /// Maintains a sorted span of the k largest values seen; its minimum is the k-th largest.
 278    /// Operates on a vocab-length slice of a (possibly larger) rented array. Allocation-free (uses
 279    /// stackalloc for small k, an ArrayPool rental otherwise) so the hot sampling path never hits the
 280    /// managed heap — the previous PriorityQueue approach allocated on every token-generation step.</summary>
 281    internal static float NthLargest(ReadOnlySpan<float> values, int k)
 282    {
 35283        float[]? rented = null;
 284        // Slice the rented array to exactly k: ArrayPool.Rent may hand back a larger buffer (e.g.
 285        // 512 for k=300), and operating on the full buffer would track more than k elements and
 286        // yield the wrong (k+slack)-th-largest cutoff.
 35287        Span<float> temp = k <= 256 ? stackalloc float[k] : (rented = ArrayPool<float>.Shared.Rent(k)).AsSpan(0, k);
 288        try
 289        {
 35290            temp.Fill(float.NegativeInfinity);
 2656291            for (int i = 0; i < values.Length; i++)
 292            {
 1293293                float v = values[i];
 1293294                if (v <= temp[0]) continue;
 295
 296                // Insert v into the ascending-sorted top-k window, evicting the current minimum
 297                // (temp[0]). BinarySearch gives the insertion point; shift the sub-slice left by one
 298                // to drop the old minimum and place v at the now-vacated slot.
 1263299                int index = temp.BinarySearch(v);
 2526300                if (index < 0) index = ~index;
 1263301                if (index > 1)
 900302                    temp.Slice(1, index - 1).CopyTo(temp.Slice(0, index - 1));
 1263303                if (index > 0)
 1260304                    temp[index - 1] = v;
 305            }
 35306            return temp[0];
 307        }
 308        finally
 309        {
 35310            if (rented is not null)
 2311                ArrayPool<float>.Shared.Return(rented);
 35312        }
 35313    }
 314
 315    /// <summary>
 316    /// Compares two array indices by the value they reference in descending order. A struct so that
 317    /// the span sort helper can specialize it without boxing or any heap allocation (a delegate-based
 318    /// comparer would allocate on every token-generation step).
 319    /// </summary>
 320    private readonly struct DescendingProbabilityIndexComparer : IComparer<int>
 321    {
 322        private readonly double[] _values;
 323
 30324        public DescendingProbabilityIndexComparer(double[] values) => _values = values;
 325
 90326        public int Compare(int a, int b) => _values[b].CompareTo(_values[a]);
 327    }
 328
 329    /// <summary>
 330    /// Run one forward pass. Virtual so tests can substitute a fake session without a real model.
 331    /// </summary>
 332    protected virtual IDisposableReadOnlyCollection<DisposableNamedOnnxValue> RunStep(
 333        IReadOnlyCollection<NamedOnnxValue> inputs)
 334    {
 8335        var session = _session ?? throw new InvalidOperationException("Engine is not loaded.");
 8336        return session.Run(inputs, session.OutputNames, _runOptions);
 337    }
 338
 339    /// <summary>
 340    /// Clone a <see cref="DenseTensor{T}"/> of <see cref="float"/> carried in a model output so it
 341    /// survives disposal of the output collection, renaming it from a <c>present_*</c> name to the
 342    /// matching <c>past_*</c> name for the next step. Engines call this from
 343    /// <see cref="ProcessStepOutputs"/> to carry the KV cache forward. Other dtypes require extension.
 344    /// </summary>
 345    protected static NamedOnnxValue? CloneAsPastKeyValue(DisposableNamedOnnxValue output, string pastName)
 346    {
 9347        if (output.Value is not DenseTensor<float> src) return null;
 7348        var copy = new DenseTensor<float>(src.Dimensions);
 7349        src.Buffer.Span.CopyTo(copy.Buffer.Span);
 7350        return NamedOnnxValue.CreateFromTensor(pastName, copy);
 351    }
 352
 353    /// <summary>
 354    /// Convenience <see cref="IDisposable"/> holder for a list of carry-forward KV-cache tensors.
 355    /// Engines that use <see cref="CloneAsPastKeyValue"/> should wrap the cloned values in an
 356    /// instance of this type (or any other <see cref="IDisposable"/>) and return it from
 357    /// <see cref="ProcessStepOutputs"/> as the next state. The base loop disposes the previous
 358    /// state on step rollover and the final state on stream end, releasing the cloned tensors.
 359    /// </summary>
 360    protected sealed class KeyValueCacheState : IDisposable
 361    {
 362        private readonly List<NamedOnnxValue> _values;
 363        private bool _disposed;
 364
 3365        public KeyValueCacheState(List<NamedOnnxValue> values)
 366        {
 3367            _values = values ?? throw new ArgumentNullException(nameof(values));
 2368        }
 369
 370        /// <summary>The carry-forward KV-cache tensors.</summary>
 1371        public IReadOnlyList<NamedOnnxValue> Values => _values;
 372
 373        public void Dispose()
 374        {
 4375            if (_disposed) return;
 2376            _disposed = true;
 2377            DisposeNamedOnnxValues(_values);
 2378        }
 379    }
 380
 381    /// <summary>Dispose any <see cref="NamedOnnxValue"/> items in <paramref name="values"/> that are disposable.</summa
 382    protected static void DisposeNamedOnnxValues(IReadOnlyCollection<NamedOnnxValue> values)
 383    {
 494384        foreach (var t in values)
 385        {
 48386            if (t is IDisposable disposable)
 0387                disposable.Dispose();
 388        }
 199389    }
 390
 391    // ---- One-shot pre/post hooks are unused on streaming engines (PredictAsync is
 392    //      overridden to route through the stream). Provide stubs so concrete streaming
 393    //      engines are not forced to implement dead methods.
 394    /// <summary>Not used by streaming engines; one-shot <see cref="PredictAsync"/> is routed through the stream.</summa
 395    protected sealed override (List<NamedOnnxValue> InputTensors, object? Context) PreProcessWithContext(TInput input) =
 1396        throw new NotSupportedException(
 1397            "Streaming engines route one-shot PredictAsync through PredictStreamingAsync; " +
 1398            "PreProcessWithContext is not used. Override BuildStepInputs instead.");
 399
 400    /// <summary>Not used by streaming engines.</summary>
 401    protected sealed override TOutput PostProcessWithContext(
 402        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> output, object? context) =>
 1403        throw new NotSupportedException(
 1404            "Streaming engines route one-shot PredictAsync through PredictStreamingAsync; " +
 1405            "PostProcessWithContext is not used. Override ProcessStepOutputs instead.");
 406}