|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using LLama.Batched; |
| 5 | +using LLama.Common; |
| 6 | +using LLama.Exceptions; |
| 7 | +using LLama.Native; |
| 8 | +using LLama.Sampling; |
| 9 | +using Spectre.Console; |
| 10 | + |
| 11 | +namespace LLama.Examples.Examples; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// Demonstrates how to evaluate an image with MTMD helpers and continue generation by |
| 15 | +/// manually scheduling batches, similar to what the batched executor does internally. |
| 16 | +/// </summary> |
| 17 | +public class BatchedExecutorMtmd |
| 18 | +{ |
| 19 | + /// <summary> |
| 20 | + /// Number of completion tokens to generate after sending the image prompt. |
| 21 | + /// </summary> |
| 22 | + public const int TokenCount = 100; |
| 23 | + |
| 24 | + public static async Task Run() |
| 25 | + { |
| 26 | + // Load the base LLM and its clip/mtmd sidecar weights so the executor has everything it needs. |
| 27 | + var parameters = new ModelParams(UserSettings.GetModelPath()); |
| 28 | + using var model = await LLamaWeights.LoadFromFileAsync(parameters); |
| 29 | + var mtmdParams = MtmdContextParams.Default(); // reuse llama.cpp defaults for helper settings |
| 30 | + mtmdParams.UseGpu = false; |
| 31 | + var marker = mtmdParams.MediaMarker ?? NativeApi.MtmdDefaultMarker() ?? "<media>"; |
| 32 | + |
| 33 | + using var mtmd = await MtmdWeights.LoadFromFileAsync(UserSettings.GetMMProjPath(), model, mtmdParams); // multimodal helper weights |
| 34 | + |
| 35 | + using var executor = new BatchedExecutor(model, parameters, mtmd); // drives batched token + chunk evaluation |
| 36 | + |
| 37 | + // Prepend the media marker so the helper knows where to inject the encoded image tokens. |
| 38 | + var defaultPrompt = "\nUSER: Provide a full description of the image.\nASSISTANT: "; |
| 39 | + var promptSuffix = AnsiConsole.Ask("Prompt (or ENTER for default):", defaultPrompt); |
| 40 | + var promptText = string.Concat(marker, promptSuffix); |
| 41 | + |
| 42 | + var imagePath = UserSettings.GetImagePath(); |
| 43 | + AnsiConsole.Write(new CanvasImage(imagePath)); |
| 44 | + |
| 45 | + var vocab = executor.Context.NativeHandle.ModelHandle.Vocab; |
| 46 | + |
| 47 | + // Simple low-temperature sampler keeps the demo deterministic-ish. |
| 48 | + var sampler = new DefaultSamplingPipeline |
| 49 | + { |
| 50 | + Temperature = 0.1f |
| 51 | + }; |
| 52 | + |
| 53 | + // Stream decoded text to the console as soon as tokens arrive. |
| 54 | + var decoder = new StreamingTokenDecoder(executor.Context) |
| 55 | + { |
| 56 | + DecodeSpecialTokens = false |
| 57 | + }; |
| 58 | + |
| 59 | + try |
| 60 | + { |
| 61 | + // Each conversation tracks its own KV cache sequence IDs. |
| 62 | + var conversation = executor.Create(); |
| 63 | + // Load the media embed explicitly so ownership is clear. |
| 64 | + using var embed = mtmd.LoadMedia( imagePath) |
| 65 | + ?? throw new RuntimeError($"Failed to load media '{imagePath}'."); |
| 66 | + // Schedule the multimodal prompt with explicit embeds. |
| 67 | + conversation.Prompt(promptText, new[] { embed }, addBos: true); |
| 68 | + |
| 69 | + Console.ForegroundColor = ConsoleColor.Yellow; |
| 70 | + Console.WriteLine("Prompt queued with multimodal chunks. Generating response...\n"); |
| 71 | + Console.ResetColor(); |
| 72 | + |
| 73 | + var remaining = TokenCount; |
| 74 | + |
| 75 | + // Run one decode/sampling/prompt cycle – mirrors the batched executor inner loop. |
| 76 | + async Task<bool> ProcessNextAsync() |
| 77 | + { |
| 78 | + var decodeResult = await executor.Infer(); |
| 79 | + if (decodeResult == DecodeResult.NoKvSlot) // KV cache exhausted – surface to the user |
| 80 | + { |
| 81 | + Console.ForegroundColor = ConsoleColor.Red; |
| 82 | + Console.WriteLine("Insufficient KV cache space for multimodal evaluation."); |
| 83 | + Console.ResetColor(); |
| 84 | + return false; |
| 85 | + } |
| 86 | + |
| 87 | + if (decodeResult != DecodeResult.Ok) |
| 88 | + throw new RuntimeError($"Failed to evaluate batch: {decodeResult}."); |
| 89 | + |
| 90 | + if (!conversation.RequiresSampling) // another conversation may still be queued |
| 91 | + return true; |
| 92 | + |
| 93 | + var token = conversation.Sample(sampler); // pull logits (or -1 for mtmd chunk) and sample |
| 94 | + if (token.IsEndOfGeneration(vocab)) |
| 95 | + return false; |
| 96 | + |
| 97 | + decoder.Add(token); |
| 98 | + var delta = decoder.Read(); |
| 99 | + if (!string.IsNullOrEmpty(delta)) |
| 100 | + Console.Write(delta); |
| 101 | + |
| 102 | + sampler.Accept(token); // keep sampler state in sync |
| 103 | + conversation.Prompt(token); // feed the accepted token back into the batch |
| 104 | + remaining--; |
| 105 | + return remaining > 0; |
| 106 | + } |
| 107 | + |
| 108 | + while (remaining > 0 && await ProcessNextAsync()) // continue until EOS or budget is reached |
| 109 | + { |
| 110 | + } |
| 111 | + |
| 112 | + Console.WriteLine(); |
| 113 | + } |
| 114 | + catch (IOException ex) |
| 115 | + { |
| 116 | + Console.ForegroundColor = ConsoleColor.Red; |
| 117 | + Console.WriteLine($"Could not load media '{imagePath}': {ex.Message}"); |
| 118 | + Console.ResetColor(); |
| 119 | + } |
| 120 | + catch (RuntimeError ex) |
| 121 | + { |
| 122 | + Console.ForegroundColor = ConsoleColor.Red; |
| 123 | + Console.WriteLine($"MTMD processing failed: {ex.Message}"); |
| 124 | + Console.ResetColor(); |
| 125 | + } |
| 126 | + } |
| 127 | +} |
0 commit comments