< Summary

Information
Class: InferenceEngine.Core.Text.TextGenerationEngine
Assembly: InferenceEngine.Core
File(s): /home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Core/Text/TextGenerationEngine.cs
Line coverage
97%
Covered lines: 115
Uncovered lines: 3
Coverable lines: 118
Total lines: 356
Line coverage: 97.4%
Branch coverage
88%
Covered branches: 67
Total branches: 76
Branch coverage: 88.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_TestTokenizer()100%11100%
set_TestTokenizer(...)100%11100%
.ctor(...)100%11100%
LoadAsync()100%22100%
get_ModelName()100%11100%
get_ModelDownloadUrls()100%11100%
get_DefaultStreamingOptions()100%11100%
BuildStepInputs(...)75%88100%
ProcessStepOutputs(...)95%2020100%
BuildFinalOutput(...)100%11100%
BuildFullRecomputeInputs(...)88.88%1818100%
GetLastPositionLogitRow(...)62.5%9875%
CreateIntTensor(...)87.5%88100%
AdvanceDecodeState(...)100%88100%
CommonPrefixLength(...)100%44100%
get_Ids()100%11100%
get_PrevFull()100%11100%
get_EmittedLen()100%11100%
.ctor(...)100%11100%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading;
 5using System.Threading.Tasks;
 6using Microsoft.Extensions.Logging;
 7using Microsoft.ML.OnnxRuntime;
 8using Microsoft.ML.OnnxRuntime.Tensors;
 9using Microsoft.ML.Tokenizers;
 10
 11namespace InferenceEngine.Core.Text;
 12
 13/// <summary>
 14/// Streaming text-generation engine for the Phi-3-mini-4k-instruct ONNX export. Owns SentencePiece
 15/// tokenization end-to-end: callers pass a prompt string and receive streamed text chunks
 16/// (<c>string in -> string out</c>).
 17/// </summary>
 18/// <remarks>
 19/// <para>
 20/// <b>Decode strategy: full-recompute per step.</b> Each step re-feeds the entire growing token-id
 21/// sequence (plus <c>attention_mask</c> and <c>position_ids</c>) and runs a fresh forward pass. This
 22/// is model-agnostic and robust across ONNX export variants (which differ in their KV-cache I/O
 23/// names/shapes), at the cost of O(n²) compute. A KV-cache optimization is a follow-up.
 24/// </para>
 25/// <para>
 26/// <b>Phi-3 external-data note.</b> The cpu-int4 export is split across a graph file (<c>.onnx</c>)
 27/// and an external-data file (<c>.onnx.data</c>). <see cref="ModelDownloadUrls"/> references the
 28/// <c>.onnx</c> only; a session created from that single file will fail to initialize without its
 29/// sibling <c>.onnx.data</c>. For real runs, point <see cref="InferenceEngineOptions.ModelPath"/> at
 30/// a complete local bundle (both files co-located).
 31/// </para>
 32/// </remarks>
 33public class TextGenerationEngine : BaseStreamingInferenceEngine<string, string, string>
 34{
 35    /// <summary>Phi-3-mini-4k-instruct (cpu-int4) graph download URL.</summary>
 36    internal const string Phi3ModelUrl =
 37        "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/resolve/main/cpu_and_mobile/cpu-int4-rtn-block-32/
 38
 39    private Tokenizer? _tokenizer;
 40
 41    /// <summary>
 42    /// Test seam (used by <c>InferenceEngine.Tests</c>): injects a pre-built tokenizer without
 43    /// network access. Phi-3's <c>tokenizer.model</c> is a binary SentencePiece protobuf that tests
 44    /// cannot fabricate, so hermetic streaming tests inject a locally-constructed tokenizer instead.
 45    /// Null (default) = the tokenizer is resolved lazily during <see cref="LoadAsync"/>.
 46    /// </summary>
 47    internal Tokenizer? TestTokenizer
 48    {
 249        get => _tokenizer;
 1550        set => _tokenizer = value;
 51    }
 52
 53    /// <summary>
 54    /// Creates the engine. The ONNX model and tokenizer are resolved lazily during
 55    /// <see cref="LoadAsync"/>.
 56    /// </summary>
 57    /// <param name="options">Engine options. GPU acceleration defaults on; pass <c>UseGpuAcceleration = false</c> for C
 58    /// <param name="logger">Optional typed logger.</param>
 59    public TextGenerationEngine(InferenceEngineOptions options, ILogger<TextGenerationEngine>? logger = null)
 1760        : base(options, logger)
 61    {
 1762    }
 63
 64    /// <summary>
 65    /// Loads the Phi-3 SentencePiece tokenizer (best-effort) and then initializes the ONNX session.
 66    /// A tokenizer load failure is logged as a warning and does not abort the session load; the
 67    /// first generation call will surface a clear error if a tokenizer is genuinely required.
 68    /// </summary>
 69    public override async Task LoadAsync()
 70    {
 571        if (_tokenizer == null)
 72        {
 73            try
 74            {
 275                _tokenizer = await TokenizerAssets.LoadPhi3TokenizerAsync(_options, _logger, CancellationToken.None)
 276                    .ConfigureAwait(false);
 177            }
 178            catch (Exception ex)
 79            {
 180                _logger.LogWarning(ex, "Could not load the Phi-3 tokenizer during LoadAsync.");
 181                _tokenizer = null;
 182            }
 83        }
 84
 585        await base.LoadAsync().ConfigureAwait(false);
 486    }
 87
 88    /// <summary>The model file name used for cache keys and registry lookups.</summary>
 289    protected override string ModelName => "phi-3-mini-4k-instruct.onnx";
 90
 91    /// <summary>
 92    /// Download URL for the Phi-3 graph file. See the class remarks: this references the
 93    /// <c>.onnx</c> only; the co-located <c>.onnx.data</c> external-data file is required for a
 94    /// successful session but is not fetched here.
 95    /// </summary>
 196    protected override string[]? ModelDownloadUrls => new[] { Phi3ModelUrl };
 97
 98    /// <summary>
 99    /// Default streaming options: greedy, capped at 256 steps, terminating on the Phi-3
 100    /// <c>&lt;|endoftext|&gt;</c> (32000) and <c>&lt;|im_end|&gt;</c> (32002) tokens.
 101    /// </summary>
 1102    protected override StreamingOptions DefaultStreamingOptions => new()
 1103    {
 1104        MaxSteps = 256,
 1105        EosTokenIds = new[] { 32000, 32002 },
 1106    };
 107
 108    /// <summary>
 109    /// Step 0 tokenizes the prompt and seeds a <see cref="GenerationState"/>. Steps &gt; 0 receive a
 110    /// state whose id list already includes the previously-sampled token; the full id list is rebuilt
 111    /// into <c>input_ids</c>, <c>attention_mask</c> (all-ones), and <c>position_ids</c>
 112    /// (0..n-1) — only for inputs the model actually declares.
 113    /// </summary>
 114    protected override (List<NamedOnnxValue> Inputs, object? BuildContext) BuildStepInputs(
 115        string input, object? state, int step)
 116    {
 16117        var tokenizer = _tokenizer ?? throw new InvalidOperationException(
 16118            "Tokenizer is not loaded. Ensure network access so the Phi-3 tokenizer.model can be fetched.");
 119
 120        GenerationState gen;
 15121        if (step == 0)
 122        {
 7123            var ids = tokenizer.EncodeToIds(input ?? string.Empty);
 7124            if (ids.Count == 0) ids = new[] { 0 };
 7125            gen = new GenerationState(ids);
 126        }
 127        else
 128        {
 8129            gen = (GenerationState)state!;
 130        }
 131
 15132        var inputs = BuildFullRecomputeInputs(gen.Ids);
 15133        return (inputs, gen);
 134    }
 135
 136    /// <summary>
 137    /// Reads the logits output, greedy-samples the last position, appends the sampled id to the
 138    /// state, detokenizes the full id list, and yields only the new text suffix since the last
 139    /// yield (correctly handling SentencePiece subword merges).
 140    /// </summary>
 141    protected override (string Step, object? NextState, bool IsEos) ProcessStepOutputs(
 142        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> outputs, object? buildContext)
 143    {
 16144        var gen = (GenerationState)buildContext!;
 16145        var tokenizer = _tokenizer ?? throw new InvalidOperationException("Tokenizer is not loaded.");
 146
 15147        DenseTensor<float>? logits = null;
 48148        foreach (var item in outputs)
 149        {
 15150            if (item.Value is not DenseTensor<float> f) continue;
 14151            string n = item.Name ?? string.Empty;
 14152            if (n.Contains("logits", StringComparison.OrdinalIgnoreCase))
 153            {
 12154                logits = f;
 12155                break;
 156            }
 157
 2158            logits ??= f;
 159        }
 160
 15161        if (logits is null)
 162        {
 2163            throw new InvalidOperationException("No logits output was produced by the generation model.");
 164        }
 165
 13166        ReadOnlySpan<float> lastRow = GetLastPositionLogitRow(logits);
 12167        int sampled = SampleNextToken(lastRow);
 168
 12169        bool isEos = CurrentOptions?.EosTokenIds is { Count: > 0 } eos && eos.Contains(sampled);
 170
 171        // One-step-delayed delta decode: only emit text that is confirmed stable (the longest
 172        // common prefix of the previous full decode and the current full decode). This is robust
 173        // to SentencePiece byte-fallback, where appending one id can mutate a previously-emitted
 174        // replacement char (U+FFFD) — a plain substring-by-length slice would emit wrong/lost
 175        // chunks. On EOS the remaining (final) tail is flushed so string.Concat(stream) == Decode(all).
 12176        string delta = AdvanceDecodeState(
 24177            gen, sampled, isEos, ids => tokenizer.Decode(ids));
 178
 12179        return (delta, gen, isEos);
 180    }
 181
 182    /// <summary>Reduces the streamed chunks into the final one-shot text.</summary>
 1183    protected override string BuildFinalOutput(IReadOnlyList<string> steps) => string.Concat(steps);
 184
 185    /// <summary>
 186    /// Builds the integer inputs for a full-recompute forward pass from the current id list, typed
 187    /// to match each input's declared element type (int64 or int32).
 188    /// </summary>
 189    private List<NamedOnnxValue> BuildFullRecomputeInputs(IReadOnlyList<int> ids)
 190    {
 15191        var metadata = InputMetadata ?? throw new InvalidOperationException("Engine is not loaded (no input metadata).")
 15192        int seqLen = ids.Count;
 15193        var inputs = new List<NamedOnnxValue>();
 194
 134195        foreach (var (name, nodeMeta) in metadata)
 196        {
 155197            var shape = nodeMeta.Dimensions.Select(d => d <= 0 ? 1 : d).ToArray();
 103198            if (shape.Length >= 2) shape[1] = seqLen;
 53199            if (shape.Length == 1) shape[0] = seqLen;
 52200            Type elementType = nodeMeta.ElementType ?? typeof(long);
 201
 202            IEnumerable<int> data;
 52203            if (name.Contains("input_ids", StringComparison.OrdinalIgnoreCase))
 204            {
 15205                data = ids;
 206            }
 37207            else if (name.Contains("attention_mask", StringComparison.OrdinalIgnoreCase))
 208            {
 13209                data = Enumerable.Repeat(1, seqLen);
 210            }
 24211            else if (name.Contains("position_ids", StringComparison.OrdinalIgnoreCase))
 212            {
 12213                data = Enumerable.Range(0, seqLen);
 214            }
 215            else
 216            {
 217                // KV-cache / unknown integer inputs are skipped under full-recompute; populating them
 218                // is unnecessary for forward-only passes and avoids mismatched past-key-value shapes.
 219                continue;
 220            }
 221
 40222            inputs.Add(CreateIntTensor(name, data, shape, elementType));
 223        }
 224
 15225        return inputs;
 226    }
 227
 228    /// <summary>
 229    /// Extracts the vocab-length logit row for the last (most recent) token position from a logits
 230    /// tensor of arbitrary rank. For [*, vocab] the final dim is the vocabulary; the last row is the
 231    /// contiguous span ending at the tensor's end.
 232    /// </summary>
 233    private static ReadOnlySpan<float> GetLastPositionLogitRow(DenseTensor<float> logits)
 234    {
 13235        var span = logits.Buffer.Span;
 13236        if (logits.Dimensions.Length == 0 || span.IsEmpty)
 237        {
 1238            throw new InvalidOperationException("Logits tensor is empty.");
 239        }
 240
 12241        int vocab = logits.Dimensions[^1];
 12242        if (vocab <= 0)
 243        {
 0244            throw new InvalidOperationException("Logits tensor has a non-positive vocabulary dimension.");
 245        }
 246
 12247        int total = (int)span.Length;
 12248        if (total < vocab)
 249        {
 0250            throw new InvalidOperationException(
 0251                $"Logits tensor length ({total}) is less than vocabulary size ({vocab}).");
 252        }
 253
 12254        int start = total - vocab;
 12255        return span.Slice(start, vocab);
 256    }
 257
 258    /// <summary>Builds an integer-valued tensor matching <paramref name="elementType"/> (long or int).</summary>
 259    private static NamedOnnxValue CreateIntTensor(string name, IEnumerable<int> values, int[] shape, Type elementType)
 260    {
 40261        var list = values as int[] ?? values.ToArray();
 40262        if (elementType == typeof(int))
 263        {
 2264            var tensor = new DenseTensor<int>(shape);
 2265            var span = tensor.Buffer.Span;
 2266            int count = Math.Min(span.Length, list.Length);
 8267            for (int i = 0; i < count; i++)
 268            {
 2269                span[i] = list[i];
 270            }
 271
 2272            return NamedOnnxValue.CreateFromTensor(name, tensor);
 273        }
 274
 38275        var longTensor = new DenseTensor<long>(shape);
 38276        var longSpan = longTensor.Buffer.Span;
 38277        int longCount = Math.Min(longSpan.Length, list.Length);
 304278        for (int i = 0; i < longCount; i++)
 279        {
 114280            longSpan[i] = list[i];
 281        }
 282
 38283        return NamedOnnxValue.CreateFromTensor(name, longTensor);
 284    }
 285
 286    /// <summary>
 287    /// Advances the decode state by one sampled token and returns the text chunk to yield this
 288    /// step. Pure except for mutating <paramref name="gen"/>; the <paramref name="decode"/>
 289    /// callback lets tests drive it with a fake tokenizer that mutates the prefix.
 290    /// </summary>
 291    internal static string AdvanceDecodeState(
 292        GenerationState gen, int sampled, bool isEos, Func<IReadOnlyList<int>, string> decode)
 293    {
 26294        gen.Ids.Add(sampled);
 295        // Defensive: a custom decode delegate could return null, which would otherwise cause a
 296        // NullReferenceException in the Length/CommonPrefixLength/Substring calls below.
 26297        string currFull = decode(gen.Ids) ?? string.Empty;
 26298        int confirmed = CommonPrefixLength(gen.PrevFull, currFull);
 299
 300        // Guard the slice start: a non-monotonic decode (subword merges / control-char stripping)
 301        // could shrink currFull below the already-emitted length. Fail with a descriptive error
 302        // instead of letting Substring throw a generic ArgumentOutOfRangeException.
 26303        if (gen.EmittedLen > currFull.Length)
 304        {
 1305            throw new InvalidOperationException(
 1306                $"Decoded text shrank below the already-emitted length " +
 1307                $"(emitted={gen.EmittedLen}, current={currFull.Length}); the tokenizer is not stable " +
 1308                $"for one-step-delayed delta decoding.");
 309        }
 310
 311        string delta;
 25312        if (isEos)
 313        {
 314            // Flush the final tail: everything not yet emitted.
 6315            delta = currFull.Substring(gen.EmittedLen);
 6316            gen.EmittedLen = currFull.Length;
 317        }
 19318        else if (confirmed > gen.EmittedLen)
 319        {
 320            // Emit the newly-confirmed stable region (common prefix with the previous full decode).
 9321            delta = currFull.Substring(gen.EmittedLen, confirmed - gen.EmittedLen);
 9322            gen.EmittedLen = confirmed;
 323        }
 324        else
 325        {
 10326            delta = string.Empty;
 327        }
 328
 25329        gen.PrevFull = currFull;
 25330        return delta;
 331    }
 332
 333    /// <summary>Length of the longest common leading character prefix of two strings.</summary>
 334    internal static int CommonPrefixLength(string a, string b)
 335    {
 30336        int max = Math.Min(a.Length, b.Length);
 30337        int i = 0;
 390338        while (i < max && a[i] == b[i]) i++;
 30339        return i;
 340    }
 341
 342    /// <summary>Carry-forward decode state for full-recompute generation.</summary>
 343    internal sealed class GenerationState
 344    {
 70345        public List<int> Ids { get; }
 346        /// <summary>Full decoded text after the previous step (Decode of ids[0..n-1]).</summary>
 75347        public string PrevFull { get; set; } = string.Empty;
 348        /// <summary>Number of leading chars of the current full decode that have been emitted.</summary>
 91349        public int EmittedLen { get; set; }
 350
 20351        public GenerationState(IReadOnlyList<int> ids)
 352        {
 20353            Ids = new List<int>(ids);
 20354        }
 355    }
 356}