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 7.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. using System.Diagnostics;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using LLama.Common;
  5. using LLama.Native;
  6. namespace LLama.Examples.NewVersion;
  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. private const int top_k = 40;
  16. private const float top_p = 0.9f;
  17. private const float temp = 0.4f;
  18. public static async Task Run()
  19. {
  20. Console.Write("Please input your model path: ");
  21. var modelPath = Console.ReadLine();
  22. Console.WriteLine("Prompt (leave blank to select automatically):");
  23. var prompt = Console.ReadLine();
  24. if (string.IsNullOrWhiteSpace(prompt))
  25. prompt = "Not many people know that";
  26. // Load model
  27. var parameters = new ModelParams(modelPath);
  28. using var model = LLamaWeights.LoadFromFile(parameters);
  29. // Tokenize prompt
  30. var prompt_tokens = model.NativeHandle.Tokenize(prompt, true, false, Encoding.UTF8);
  31. var n_kv_req = prompt_tokens.Length + (n_len - prompt_tokens.Length) * n_parallel;
  32. // Create a context
  33. parameters.ContextSize = (uint)model.ContextSize;
  34. parameters.Seed = unchecked((uint)RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue));
  35. parameters.BatchSize = (uint)Math.Max(n_len, n_parallel);
  36. using var context = model.CreateContext(parameters);
  37. var n_ctx = context.ContextSize;
  38. // make sure the KV cache is big enough to hold all the prompt and generated tokens
  39. if (n_kv_req > n_ctx)
  40. {
  41. await Console.Error.WriteLineAsync($"error: n_kv_req ({n_kv_req}) > n_ctx, the required KV cache size is not big enough\n");
  42. await Console.Error.WriteLineAsync(" either reduce n_parallel or increase n_ctx\n");
  43. return;
  44. }
  45. using var batch = LLamaBatchSafeHandle.Create(Math.Max(prompt_tokens.Length, n_parallel), 0, 1);
  46. // evaluate the initial prompt
  47. for (var i = 0; i < prompt_tokens.Length; i++)
  48. llama_batch_add(batch, prompt_tokens[i], i, new() { (LLamaSeqId)0 }, false);
  49. Debug.Assert(batch.NativeBatch.n_tokens == (int)prompt_tokens.Length);
  50. // llama_decode will output logits only for the last token of the prompt
  51. unsafe
  52. {
  53. batch.NativeBatch.logits[batch.NativeBatch.n_tokens - 1] = 1;
  54. }
  55. if (NativeApi.llama_decode(context.NativeHandle, batch.NativeBatch) != 0)
  56. {
  57. await Console.Error.WriteLineAsync("llama_decode failed");
  58. return;
  59. }
  60. // assign the system KV cache to all parallel sequences
  61. // this way, the parallel sequences will "reuse" the prompt tokens without having to copy them
  62. for (var i = 1; i < n_parallel; ++i)
  63. {
  64. NativeApi.llama_kv_cache_seq_cp(context.NativeHandle, (LLamaSeqId)0, (LLamaSeqId)i, 0, batch.NativeBatch.n_tokens);
  65. }
  66. if (n_parallel > 1)
  67. {
  68. Console.WriteLine();
  69. Console.WriteLine($"generating {n_parallel} sequences...");
  70. }
  71. // remember the batch index of the last token for each parallel sequence
  72. // we need this to determine which logits to sample from
  73. List<int> i_batch = new();
  74. for (var i = 0; i < n_parallel; i++)
  75. i_batch.Add(batch.NativeBatch.n_tokens - 1);
  76. int n_cur = batch.NativeBatch.n_tokens;
  77. int n_decode = 0;
  78. var streams = new List<int>[n_parallel];
  79. for (var i = 0; i < n_parallel; i++)
  80. streams[i] = new();
  81. var eos = model.EndOfSentenceToken;
  82. var nl = model.NewlineToken;
  83. var timer = new Stopwatch();
  84. timer.Start();
  85. while (n_cur <= n_len)
  86. {
  87. llama_batch_clear(batch);
  88. for (var i = 0; i < n_parallel; i++)
  89. {
  90. // Skip completed streams
  91. if (i_batch[i] < 0)
  92. continue;
  93. var n_vocab = model.VocabCount;
  94. LLamaTokenDataArray candidates;
  95. unsafe
  96. {
  97. candidates = LLamaTokenDataArray.Create(new Span<float>(NativeApi.llama_get_logits_ith(context.NativeHandle, i_batch[i]), n_vocab));
  98. }
  99. candidates.TopK(context.NativeHandle, top_k);
  100. candidates.TopP(context.NativeHandle, top_p);
  101. candidates.Temperature(context.NativeHandle, temp);
  102. var new_token_id = candidates.SampleToken(context.NativeHandle);
  103. if (new_token_id == eos || new_token_id == nl)
  104. {
  105. i_batch[i] = -1;
  106. Console.WriteLine($"Completed Stream {i} early");
  107. continue;
  108. }
  109. streams[i].Add(new_token_id);
  110. i_batch[i] = batch.NativeBatch.n_tokens;
  111. // push this new token for next evaluation
  112. llama_batch_add(batch, new_token_id, n_cur, new() { (LLamaSeqId)i }, true);
  113. n_decode++;
  114. }
  115. // all streams are finished
  116. if (batch.NativeBatch.n_tokens == 0)
  117. {
  118. break;
  119. }
  120. n_cur++;
  121. // evaluate the current batch with the transformer model
  122. if (NativeApi.llama_decode(context.NativeHandle, batch.NativeBatch) != 0)
  123. {
  124. await Console.Error.WriteLineAsync("failed to eval");
  125. return;
  126. }
  127. }
  128. timer.Stop();
  129. Console.ForegroundColor = ConsoleColor.Yellow;
  130. Console.WriteLine();
  131. Console.WriteLine($"Decoded {n_decode} tokens in {timer.ElapsedMilliseconds}ms");
  132. Console.WriteLine($"Rate: {n_decode / timer.Elapsed.TotalSeconds:##.000} tokens/second");
  133. var index = 0;
  134. foreach (var stream in streams)
  135. {
  136. var text = context.DeTokenize(stream);
  137. Console.ForegroundColor = ConsoleColor.Green;
  138. Console.Write($"{index++}. {prompt}");
  139. Console.ForegroundColor = ConsoleColor.Red;
  140. Console.WriteLine(text);
  141. }
  142. }
  143. /// <summary>
  144. /// https://github.com/ggerganov/llama.cpp/blob/ad939626577cd25b462e8026cc543efb71528472/common/common.cpp#L829C2-L829C2
  145. /// </summary>
  146. private static void llama_batch_add(LLamaBatchSafeHandle batchHandle, int token, LLamaPos pos, List<LLamaSeqId> sequences, bool logits)
  147. {
  148. unsafe
  149. {
  150. ref var batch = ref batchHandle.NativeBatch;
  151. batch.token[batch.n_tokens] = token;
  152. batch.pos[batch.n_tokens] = pos;
  153. batch.n_seq_id[batch.n_tokens] = sequences.Count;
  154. for (var i = 0; i < sequences.Count; i++)
  155. batch.seq_id[batch.n_tokens][i] = sequences[i];
  156. batch.logits[batch.n_tokens] = Convert.ToByte(logits);
  157. batch.n_tokens++;
  158. }
  159. }
  160. /// <summary>
  161. /// https://github.com/ggerganov/llama.cpp/blob/ad939626577cd25b462e8026cc543efb71528472/common/common.cpp#L825
  162. /// </summary>
  163. /// <param name="batchHandle"></param>
  164. private static void llama_batch_clear(LLamaBatchSafeHandle batchHandle)
  165. {
  166. batchHandle.NativeBatch.n_tokens = 0;
  167. }
  168. }