| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Threading; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | using Microsoft.ML.OnnxRuntime; |
| | | 8 | | using Microsoft.ML.OnnxRuntime.Tensors; |
| | | 9 | | using Microsoft.ML.Tokenizers; |
| | | 10 | | |
| | | 11 | | namespace 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> |
| | | 33 | | public 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 | | { |
| | 2 | 49 | | get => _tokenizer; |
| | 15 | 50 | | 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) |
| | 17 | 60 | | : base(options, logger) |
| | | 61 | | { |
| | 17 | 62 | | } |
| | | 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 | | { |
| | 5 | 71 | | if (_tokenizer == null) |
| | | 72 | | { |
| | | 73 | | try |
| | | 74 | | { |
| | 2 | 75 | | _tokenizer = await TokenizerAssets.LoadPhi3TokenizerAsync(_options, _logger, CancellationToken.None) |
| | 2 | 76 | | .ConfigureAwait(false); |
| | 1 | 77 | | } |
| | 1 | 78 | | catch (Exception ex) |
| | | 79 | | { |
| | 1 | 80 | | _logger.LogWarning(ex, "Could not load the Phi-3 tokenizer during LoadAsync."); |
| | 1 | 81 | | _tokenizer = null; |
| | 1 | 82 | | } |
| | | 83 | | } |
| | | 84 | | |
| | 5 | 85 | | await base.LoadAsync().ConfigureAwait(false); |
| | 4 | 86 | | } |
| | | 87 | | |
| | | 88 | | /// <summary>The model file name used for cache keys and registry lookups.</summary> |
| | 2 | 89 | | 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> |
| | 1 | 96 | | 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><|endoftext|></c> (32000) and <c><|im_end|></c> (32002) tokens. |
| | | 101 | | /// </summary> |
| | 1 | 102 | | protected override StreamingOptions DefaultStreamingOptions => new() |
| | 1 | 103 | | { |
| | 1 | 104 | | MaxSteps = 256, |
| | 1 | 105 | | EosTokenIds = new[] { 32000, 32002 }, |
| | 1 | 106 | | }; |
| | | 107 | | |
| | | 108 | | /// <summary> |
| | | 109 | | /// Step 0 tokenizes the prompt and seeds a <see cref="GenerationState"/>. Steps > 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 | | { |
| | 16 | 117 | | var tokenizer = _tokenizer ?? throw new InvalidOperationException( |
| | 16 | 118 | | "Tokenizer is not loaded. Ensure network access so the Phi-3 tokenizer.model can be fetched."); |
| | | 119 | | |
| | | 120 | | GenerationState gen; |
| | 15 | 121 | | if (step == 0) |
| | | 122 | | { |
| | 7 | 123 | | var ids = tokenizer.EncodeToIds(input ?? string.Empty); |
| | 7 | 124 | | if (ids.Count == 0) ids = new[] { 0 }; |
| | 7 | 125 | | gen = new GenerationState(ids); |
| | | 126 | | } |
| | | 127 | | else |
| | | 128 | | { |
| | 8 | 129 | | gen = (GenerationState)state!; |
| | | 130 | | } |
| | | 131 | | |
| | 15 | 132 | | var inputs = BuildFullRecomputeInputs(gen.Ids); |
| | 15 | 133 | | 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 | | { |
| | 16 | 144 | | var gen = (GenerationState)buildContext!; |
| | 16 | 145 | | var tokenizer = _tokenizer ?? throw new InvalidOperationException("Tokenizer is not loaded."); |
| | | 146 | | |
| | 15 | 147 | | DenseTensor<float>? logits = null; |
| | 48 | 148 | | foreach (var item in outputs) |
| | | 149 | | { |
| | 15 | 150 | | if (item.Value is not DenseTensor<float> f) continue; |
| | 14 | 151 | | string n = item.Name ?? string.Empty; |
| | 14 | 152 | | if (n.Contains("logits", StringComparison.OrdinalIgnoreCase)) |
| | | 153 | | { |
| | 12 | 154 | | logits = f; |
| | 12 | 155 | | break; |
| | | 156 | | } |
| | | 157 | | |
| | 2 | 158 | | logits ??= f; |
| | | 159 | | } |
| | | 160 | | |
| | 15 | 161 | | if (logits is null) |
| | | 162 | | { |
| | 2 | 163 | | throw new InvalidOperationException("No logits output was produced by the generation model."); |
| | | 164 | | } |
| | | 165 | | |
| | 13 | 166 | | ReadOnlySpan<float> lastRow = GetLastPositionLogitRow(logits); |
| | 12 | 167 | | int sampled = SampleNextToken(lastRow); |
| | | 168 | | |
| | 12 | 169 | | 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). |
| | 12 | 176 | | string delta = AdvanceDecodeState( |
| | 24 | 177 | | gen, sampled, isEos, ids => tokenizer.Decode(ids)); |
| | | 178 | | |
| | 12 | 179 | | return (delta, gen, isEos); |
| | | 180 | | } |
| | | 181 | | |
| | | 182 | | /// <summary>Reduces the streamed chunks into the final one-shot text.</summary> |
| | 1 | 183 | | 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 | | { |
| | 15 | 191 | | var metadata = InputMetadata ?? throw new InvalidOperationException("Engine is not loaded (no input metadata).") |
| | 15 | 192 | | int seqLen = ids.Count; |
| | 15 | 193 | | var inputs = new List<NamedOnnxValue>(); |
| | | 194 | | |
| | 134 | 195 | | foreach (var (name, nodeMeta) in metadata) |
| | | 196 | | { |
| | 155 | 197 | | var shape = nodeMeta.Dimensions.Select(d => d <= 0 ? 1 : d).ToArray(); |
| | 103 | 198 | | if (shape.Length >= 2) shape[1] = seqLen; |
| | 53 | 199 | | if (shape.Length == 1) shape[0] = seqLen; |
| | 52 | 200 | | Type elementType = nodeMeta.ElementType ?? typeof(long); |
| | | 201 | | |
| | | 202 | | IEnumerable<int> data; |
| | 52 | 203 | | if (name.Contains("input_ids", StringComparison.OrdinalIgnoreCase)) |
| | | 204 | | { |
| | 15 | 205 | | data = ids; |
| | | 206 | | } |
| | 37 | 207 | | else if (name.Contains("attention_mask", StringComparison.OrdinalIgnoreCase)) |
| | | 208 | | { |
| | 13 | 209 | | data = Enumerable.Repeat(1, seqLen); |
| | | 210 | | } |
| | 24 | 211 | | else if (name.Contains("position_ids", StringComparison.OrdinalIgnoreCase)) |
| | | 212 | | { |
| | 12 | 213 | | 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 | | |
| | 40 | 222 | | inputs.Add(CreateIntTensor(name, data, shape, elementType)); |
| | | 223 | | } |
| | | 224 | | |
| | 15 | 225 | | 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 | | { |
| | 13 | 235 | | var span = logits.Buffer.Span; |
| | 13 | 236 | | if (logits.Dimensions.Length == 0 || span.IsEmpty) |
| | | 237 | | { |
| | 1 | 238 | | throw new InvalidOperationException("Logits tensor is empty."); |
| | | 239 | | } |
| | | 240 | | |
| | 12 | 241 | | int vocab = logits.Dimensions[^1]; |
| | 12 | 242 | | if (vocab <= 0) |
| | | 243 | | { |
| | 0 | 244 | | throw new InvalidOperationException("Logits tensor has a non-positive vocabulary dimension."); |
| | | 245 | | } |
| | | 246 | | |
| | 12 | 247 | | int total = (int)span.Length; |
| | 12 | 248 | | if (total < vocab) |
| | | 249 | | { |
| | 0 | 250 | | throw new InvalidOperationException( |
| | 0 | 251 | | $"Logits tensor length ({total}) is less than vocabulary size ({vocab})."); |
| | | 252 | | } |
| | | 253 | | |
| | 12 | 254 | | int start = total - vocab; |
| | 12 | 255 | | 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 | | { |
| | 40 | 261 | | var list = values as int[] ?? values.ToArray(); |
| | 40 | 262 | | if (elementType == typeof(int)) |
| | | 263 | | { |
| | 2 | 264 | | var tensor = new DenseTensor<int>(shape); |
| | 2 | 265 | | var span = tensor.Buffer.Span; |
| | 2 | 266 | | int count = Math.Min(span.Length, list.Length); |
| | 8 | 267 | | for (int i = 0; i < count; i++) |
| | | 268 | | { |
| | 2 | 269 | | span[i] = list[i]; |
| | | 270 | | } |
| | | 271 | | |
| | 2 | 272 | | return NamedOnnxValue.CreateFromTensor(name, tensor); |
| | | 273 | | } |
| | | 274 | | |
| | 38 | 275 | | var longTensor = new DenseTensor<long>(shape); |
| | 38 | 276 | | var longSpan = longTensor.Buffer.Span; |
| | 38 | 277 | | int longCount = Math.Min(longSpan.Length, list.Length); |
| | 304 | 278 | | for (int i = 0; i < longCount; i++) |
| | | 279 | | { |
| | 114 | 280 | | longSpan[i] = list[i]; |
| | | 281 | | } |
| | | 282 | | |
| | 38 | 283 | | 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 | | { |
| | 26 | 294 | | 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. |
| | 26 | 297 | | string currFull = decode(gen.Ids) ?? string.Empty; |
| | 26 | 298 | | 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. |
| | 26 | 303 | | if (gen.EmittedLen > currFull.Length) |
| | | 304 | | { |
| | 1 | 305 | | throw new InvalidOperationException( |
| | 1 | 306 | | $"Decoded text shrank below the already-emitted length " + |
| | 1 | 307 | | $"(emitted={gen.EmittedLen}, current={currFull.Length}); the tokenizer is not stable " + |
| | 1 | 308 | | $"for one-step-delayed delta decoding."); |
| | | 309 | | } |
| | | 310 | | |
| | | 311 | | string delta; |
| | 25 | 312 | | if (isEos) |
| | | 313 | | { |
| | | 314 | | // Flush the final tail: everything not yet emitted. |
| | 6 | 315 | | delta = currFull.Substring(gen.EmittedLen); |
| | 6 | 316 | | gen.EmittedLen = currFull.Length; |
| | | 317 | | } |
| | 19 | 318 | | else if (confirmed > gen.EmittedLen) |
| | | 319 | | { |
| | | 320 | | // Emit the newly-confirmed stable region (common prefix with the previous full decode). |
| | 9 | 321 | | delta = currFull.Substring(gen.EmittedLen, confirmed - gen.EmittedLen); |
| | 9 | 322 | | gen.EmittedLen = confirmed; |
| | | 323 | | } |
| | | 324 | | else |
| | | 325 | | { |
| | 10 | 326 | | delta = string.Empty; |
| | | 327 | | } |
| | | 328 | | |
| | 25 | 329 | | gen.PrevFull = currFull; |
| | 25 | 330 | | 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 | | { |
| | 30 | 336 | | int max = Math.Min(a.Length, b.Length); |
| | 30 | 337 | | int i = 0; |
| | 390 | 338 | | while (i < max && a[i] == b[i]) i++; |
| | 30 | 339 | | return i; |
| | | 340 | | } |
| | | 341 | | |
| | | 342 | | /// <summary>Carry-forward decode state for full-recompute generation.</summary> |
| | | 343 | | internal sealed class GenerationState |
| | | 344 | | { |
| | 70 | 345 | | public List<int> Ids { get; } |
| | | 346 | | /// <summary>Full decoded text after the previous step (Decode of ids[0..n-1]).</summary> |
| | 75 | 347 | | public string PrevFull { get; set; } = string.Empty; |
| | | 348 | | /// <summary>Number of leading chars of the current full decode that have been emitted.</summary> |
| | 91 | 349 | | public int EmittedLen { get; set; } |
| | | 350 | | |
| | 20 | 351 | | public GenerationState(IReadOnlyList<int> ids) |
| | | 352 | | { |
| | 20 | 353 | | Ids = new List<int>(ids); |
| | 20 | 354 | | } |
| | | 355 | | } |
| | | 356 | | } |