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

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