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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. using System.Diagnostics;
  2. using System.Text;
  3. using LLama.Abstractions;
  4. using LLama.Common;
  5. using LLama.Native;
  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. private const int top_k = 80;
  16. private const float top_p = 0.8f;
  17. private const float temp = 0.75f;
  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.BatchSize = (uint)Math.Max(n_len, n_parallel);
  35. using var context = model.CreateContext(parameters);
  36. var n_ctx = context.ContextSize;
  37. // make sure the KV cache is big enough to hold all the prompt and generated tokens
  38. if (n_kv_req > n_ctx)
  39. {
  40. await Console.Error.WriteLineAsync($"error: n_kv_req ({n_kv_req}) > n_ctx, the required KV cache size is not big enough\n");
  41. await Console.Error.WriteLineAsync(" either reduce n_parallel or increase n_ctx\n");
  42. return;
  43. }
  44. using var batch = LLamaBatchSafeHandle.Create(Math.Max(prompt_tokens.Length, n_parallel), 0, 1);
  45. // evaluate the initial prompt
  46. for (var i = 0; i < prompt_tokens.Length; i++)
  47. batch.LLamaBatchAdd(prompt_tokens[i], i, new[] { (LLamaSeqId)0 }, false);
  48. Debug.Assert(batch.NativeBatch.n_tokens == prompt_tokens.Length);
  49. // llama_decode will output logits only for the last token of the prompt
  50. unsafe
  51. {
  52. batch.NativeBatch.logits[batch.NativeBatch.n_tokens - 1] = 1;
  53. }
  54. if (context.NativeHandle.Decode(batch) != 0)
  55. {
  56. await Console.Error.WriteLineAsync("llama_decode failed");
  57. return;
  58. }
  59. // assign the system KV cache to all parallel sequences
  60. // this way, the parallel sequences will "reuse" the prompt tokens without having to copy them
  61. for (var i = 1; i < n_parallel; ++i)
  62. {
  63. NativeApi.llama_kv_cache_seq_cp(context.NativeHandle, (LLamaSeqId)0, (LLamaSeqId)i, 0, batch.NativeBatch.n_tokens);
  64. }
  65. if (n_parallel > 1)
  66. {
  67. Console.WriteLine();
  68. Console.WriteLine($"generating {n_parallel} sequences...");
  69. }
  70. // remember the batch index of the last token for each parallel sequence
  71. // we need this to determine which logits to sample from
  72. List<int> i_batch = new();
  73. for (var i = 0; i < n_parallel; i++)
  74. i_batch.Add(batch.NativeBatch.n_tokens - 1);
  75. var n_cur = batch.NativeBatch.n_tokens;
  76. var n_decode = 0;
  77. var streams = new List<int>[n_parallel];
  78. for (var i = 0; i < n_parallel; i++)
  79. streams[i] = new();
  80. var eos = model.EndOfSentenceToken;
  81. var nl = model.NewlineToken;
  82. var timer = new Stopwatch();
  83. timer.Start();
  84. while (n_cur <= n_len)
  85. {
  86. batch.LLamaBatchClear();
  87. for (var i = 0; i < n_parallel; i++)
  88. {
  89. // Skip completed streams
  90. if (i_batch[i] < 0)
  91. continue;
  92. var n_vocab = model.VocabCount;
  93. LLamaTokenDataArray candidates;
  94. unsafe
  95. {
  96. candidates = LLamaTokenDataArray.Create(new Span<float>(NativeApi.llama_get_logits_ith(context.NativeHandle, i_batch[i]), n_vocab));
  97. }
  98. candidates.TopK(context.NativeHandle, top_k);
  99. candidates.TopP(context.NativeHandle, top_p);
  100. candidates.Temperature(context.NativeHandle, temp);
  101. var new_token_id = candidates.SampleToken(context.NativeHandle);
  102. if (new_token_id == eos || new_token_id == nl)
  103. {
  104. i_batch[i] = -1;
  105. Console.WriteLine($"Completed Stream {i} early");
  106. continue;
  107. }
  108. streams[i].Add(new_token_id);
  109. i_batch[i] = batch.NativeBatch.n_tokens;
  110. // push this new token for next evaluation
  111. batch.LLamaBatchAdd(new_token_id, n_cur, new[] { (LLamaSeqId)i }, true);
  112. n_decode++;
  113. }
  114. // all streams are finished
  115. if (batch.NativeBatch.n_tokens == 0)
  116. {
  117. break;
  118. }
  119. n_cur++;
  120. // evaluate the current batch with the transformer model
  121. if (context.NativeHandle.Decode(batch) != 0)
  122. {
  123. await Console.Error.WriteLineAsync("failed to eval");
  124. return;
  125. }
  126. }
  127. timer.Stop();
  128. Console.ForegroundColor = ConsoleColor.Yellow;
  129. Console.WriteLine();
  130. Console.WriteLine($"Decoded {n_decode} tokens in {timer.ElapsedMilliseconds}ms");
  131. Console.WriteLine($"Rate: {n_decode / timer.Elapsed.TotalSeconds:##.000} tokens/second");
  132. var index = 0;
  133. foreach (var stream in streams)
  134. {
  135. var text = context.DeTokenize(stream);
  136. Console.ForegroundColor = ConsoleColor.Green;
  137. Console.Write($"{index++}. {prompt}");
  138. Console.ForegroundColor = ConsoleColor.Red;
  139. Console.WriteLine(text);
  140. }
  141. Console.WriteLine("Press any key to exit demo");
  142. Console.ReadKey(true);
  143. }
  144. }