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

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