You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

BatchedDecoding.cs 5.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. using System.Diagnostics;
  2. using System.Text;
  3. using LLama.Common;
  4. using LLama.Native;
  5. using LLama.Sampling;
  6. namespace LLama.Examples.Examples;
  7. /// <summary>
  8. /// This demonstrates generating multiple replies to the same prompt, with a shared cache
  9. /// </summary>
  10. /// <remarks>Note that this is currently using the low level API directly, future work will provide a safer C# wrapper over this!</remarks>
  11. public class BatchedDecoding
  12. {
  13. private const int n_parallel = 8;
  14. private const int n_len = 32;
  15. public static async Task Run()
  16. {
  17. Console.Write("Please input your model path: ");
  18. var modelPath = Console.ReadLine();
  19. Console.WriteLine("Prompt (leave blank to select automatically):");
  20. var prompt = Console.ReadLine();
  21. if (string.IsNullOrWhiteSpace(prompt))
  22. prompt = "Not many people know that";
  23. // Load model
  24. var parameters = new ModelParams(modelPath);
  25. using var model = LLamaWeights.LoadFromFile(parameters);
  26. // Tokenize prompt
  27. var prompt_tokens = model.Tokenize(prompt, true, false, Encoding.UTF8);
  28. var n_kv_req = prompt_tokens.Length + (n_len - prompt_tokens.Length) * n_parallel;
  29. // Create a context
  30. parameters.ContextSize = (uint)model.ContextSize;
  31. parameters.BatchSize = (uint)Math.Max(n_len, n_parallel);
  32. using var context = model.CreateContext(parameters);
  33. var n_ctx = context.ContextSize;
  34. // make sure the KV cache is big enough to hold all the prompt and generated tokens
  35. if (n_kv_req > n_ctx)
  36. {
  37. await Console.Error.WriteLineAsync($"error: n_kv_req ({n_kv_req}) > n_ctx, the required KV cache size is not big enough\n");
  38. await Console.Error.WriteLineAsync(" either reduce n_parallel or increase n_ctx\n");
  39. return;
  40. }
  41. var batch = new LLamaBatch();
  42. // evaluate the initial prompt
  43. batch.AddRange(prompt_tokens, 0, LLamaSeqId.Zero, true);
  44. if (await context.DecodeAsync(batch) != DecodeResult.Ok)
  45. {
  46. await Console.Error.WriteLineAsync("llama_decode failed");
  47. return;
  48. }
  49. // assign the system KV cache to all parallel sequences
  50. // this way, the parallel sequences will "reuse" the prompt tokens without having to copy them
  51. for (var i = 1; i < n_parallel; ++i)
  52. {
  53. context.NativeHandle.KvCacheSequenceCopy((LLamaSeqId)0, (LLamaSeqId)i, 0, batch.TokenCount);
  54. }
  55. if (n_parallel > 1)
  56. {
  57. Console.WriteLine();
  58. Console.WriteLine($"generating {n_parallel} sequences...");
  59. }
  60. // remember the batch index of the last token for each parallel sequence
  61. // we need this to determine which logits to sample from
  62. List<int> i_batch = new();
  63. for (var i = 0; i < n_parallel; i++)
  64. i_batch.Add(batch.TokenCount - 1);
  65. // Create per-stream decoder and sampler
  66. var decoders = new StreamingTokenDecoder[n_parallel];
  67. var samplers = new ISamplingPipeline[n_parallel];
  68. for (var i = 0; i < n_parallel; i++)
  69. {
  70. decoders[i] = new StreamingTokenDecoder(context);
  71. samplers[i] = new DefaultSamplingPipeline
  72. {
  73. Temperature = 0.1f + (float)i / n_parallel,
  74. MinP = 0.25f,
  75. };
  76. }
  77. var n_cur = batch.TokenCount;
  78. var n_decode = 0;
  79. var timer = new Stopwatch();
  80. timer.Start();
  81. while (n_cur <= n_len)
  82. {
  83. batch.Clear();
  84. for (var i = 0; i < n_parallel; i++)
  85. {
  86. // Skip completed streams
  87. if (i_batch[i] < 0)
  88. continue;
  89. // Use the sampling pipeline to select a token
  90. var new_token_id = samplers[i].Sample(
  91. context.NativeHandle,
  92. context.NativeHandle.GetLogitsIth(i_batch[i]),
  93. Array.Empty<LLamaToken>()
  94. );
  95. // Finish this stream early if necessary
  96. if (new_token_id == model.EndOfSentenceToken || new_token_id == model.NewlineToken)
  97. {
  98. i_batch[i] = -1;
  99. Console.WriteLine($"Completed Stream {i} early");
  100. continue;
  101. }
  102. // Add this token to the decoder, so it will be turned into text
  103. decoders[i].Add(new_token_id);
  104. i_batch[i] = batch.TokenCount;
  105. // push this new token for next evaluation
  106. batch.Add(new_token_id, n_cur, (LLamaSeqId)i, true);
  107. n_decode++;
  108. }
  109. // Check if all streams are finished
  110. if (batch.TokenCount == 0)
  111. {
  112. break;
  113. }
  114. n_cur++;
  115. // evaluate the current batch with the transformer model
  116. if (await context.DecodeAsync(batch) != 0)
  117. {
  118. await Console.Error.WriteLineAsync("failed to eval");
  119. return;
  120. }
  121. }
  122. timer.Stop();
  123. Console.ForegroundColor = ConsoleColor.Yellow;
  124. Console.WriteLine();
  125. Console.WriteLine($"Decoded {n_decode} tokens in {timer.ElapsedMilliseconds}ms");
  126. Console.WriteLine($"Rate: {n_decode / timer.Elapsed.TotalSeconds:##.000} tokens/second");
  127. var index = 0;
  128. foreach (var stream in decoders)
  129. {
  130. var text = stream.Read();
  131. Console.ForegroundColor = ConsoleColor.Green;
  132. Console.Write($"{index++}. {prompt}");
  133. Console.ForegroundColor = ConsoleColor.Red;
  134. Console.WriteLine(text);
  135. }
  136. Console.WriteLine("Press any key to exit demo");
  137. Console.ReadKey(true);
  138. }
  139. }