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.

LLamaBatch.cs 9.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. namespace LLama.Native;
  5. /// <summary>
  6. /// A batch allows submitting multiple tokens to multiple sequences simultaneously
  7. /// </summary>
  8. public class LLamaBatch
  9. {
  10. private byte[] _logits;
  11. private LLamaToken[] _tokens;
  12. private LLamaPos[] _positions;
  13. private int[] _sequenceIdCount;
  14. private LLamaSeqId[][] _sequenceIds;
  15. private IntPtr[] _sequenceIdsPtrs;
  16. /// <summary>
  17. /// Keep track of the index of existing token/position combos in the batch
  18. /// </summary>
  19. private readonly Dictionary<(LLamaToken, LLamaPos), int> _index = new();
  20. /// <summary>
  21. /// The number of tokens in this batch
  22. /// </summary>
  23. public int TokenCount { get; private set; }
  24. /// <summary>
  25. /// Maximum number of tokens that can be added to this batch (automatically grows if exceeded)
  26. /// </summary>
  27. private int TokenCapacity { get; set; }
  28. /// <summary>
  29. /// Maximum number of sequences a token can be assigned to (automatically grows if exceeded)
  30. /// </summary>
  31. public int SequenceCapacity { get; private set; }
  32. /// <summary>
  33. /// Create a new batch for submitting inputs to llama.cpp
  34. /// </summary>
  35. public LLamaBatch()
  36. {
  37. // These can both be grown later, start off with reasonable numbers.
  38. const int n_tokens = 128;
  39. const int n_seq_max = 1;
  40. SequenceCapacity = n_seq_max;
  41. TokenCapacity = n_tokens;
  42. _logits = new byte[n_tokens];
  43. _tokens = new LLamaToken[n_tokens];
  44. _positions = new LLamaPos[n_tokens];
  45. _sequenceIdCount = new int[n_tokens];
  46. _sequenceIdsPtrs = new IntPtr[_sequenceIdCount.Length];
  47. _sequenceIds = new LLamaSeqId[n_tokens][];
  48. for (var i = 0; i < _sequenceIds.Length; i++)
  49. _sequenceIds[i] = new LLamaSeqId[SequenceCapacity];
  50. }
  51. #region grow
  52. private void GrowTokenCapacity()
  53. {
  54. var n_tokens = TokenCount * 2;
  55. TokenCapacity = n_tokens;
  56. Array.Resize(ref _logits, n_tokens);
  57. Array.Resize(ref _tokens, n_tokens);
  58. Array.Resize(ref _positions, n_tokens);
  59. Array.Resize(ref _sequenceIdCount, n_tokens);
  60. Array.Resize(ref _sequenceIdsPtrs, n_tokens);
  61. Array.Resize(ref _sequenceIds, n_tokens);
  62. for (int i = 0; i < _sequenceIds.Length; i++)
  63. {
  64. // Growing the array filled elements with null, temporarily violating the nullability contract!
  65. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  66. if (_sequenceIds[i] == null)
  67. _sequenceIds[i] = new LLamaSeqId[SequenceCapacity];
  68. }
  69. }
  70. private void GrowMaxSequences(int atLeast)
  71. {
  72. var n_seq = Math.Max(SequenceCapacity * 2, atLeast);
  73. SequenceCapacity = n_seq;
  74. for (var i = 0; i < _sequenceIds.Length; i++)
  75. Array.Resize(ref _sequenceIds[i], SequenceCapacity);
  76. }
  77. #endregion
  78. internal GroupDisposable ToNativeBatch(out LLamaNativeBatch batch)
  79. {
  80. // This group holds all of the memory pins
  81. var group = new GroupDisposable();
  82. unsafe
  83. {
  84. batch = new LLamaNativeBatch
  85. {
  86. n_tokens = TokenCount,
  87. logits = (byte*)group.Add(_logits.AsMemory().Pin()).Pointer,
  88. n_seq_id = (int*)group.Add(_sequenceIdCount.AsMemory().Pin()).Pointer,
  89. pos = (LLamaPos*)group.Add(_positions.AsMemory().Pin()).Pointer,
  90. seq_id = (LLamaSeqId**)group.Add(_sequenceIdsPtrs.AsMemory().Pin()).Pointer,
  91. // embd is not currently supported, so this is always null!
  92. embd = null,
  93. // Note that if embd is **not null** then this will be null!
  94. tokens = (LLamaToken*)group.Add(_tokens.AsMemory().Pin()).Pointer,
  95. };
  96. // Create pointers to each of the arrays in turns
  97. for (var i = 0; i < _sequenceIdsPtrs.Length; i++)
  98. _sequenceIdsPtrs[i] = (IntPtr)group.Add(_sequenceIds[i].AsMemory().Pin()).Pointer;
  99. }
  100. return group;
  101. }
  102. #region add
  103. /// <summary>
  104. /// Add a single token to the batch at the same position in several sequences
  105. /// </summary>
  106. /// <remarks>https://github.com/ggerganov/llama.cpp/blob/ad939626577cd25b462e8026cc543efb71528472/common/common.cpp#L829C2-L829C2</remarks>
  107. /// <param name="token">The token to add</param>
  108. /// <param name="pos">The position to add it att</param>
  109. /// <param name="sequences">The set of sequences to add this token to</param>
  110. /// <param name="logits"></param>
  111. /// <returns>The index that the token was added at. Use this for GetLogitsIth</returns>
  112. public int Add(LLamaToken token, LLamaPos pos, ReadOnlySpan<LLamaSeqId> sequences, bool logits)
  113. {
  114. // Try to find this (token, position) combo somewhere in the batch to re-use it
  115. if (_index.TryGetValue((token, pos), out var existingIndex))
  116. {
  117. if (_sequenceIdCount[existingIndex] + sequences.Length > SequenceCapacity)
  118. GrowMaxSequences(_sequenceIdCount[existingIndex] + sequences.Length);
  119. foreach (var sequence in sequences)
  120. {
  121. _sequenceIds[existingIndex][_sequenceIdCount[existingIndex]] = sequence;
  122. _sequenceIdCount[existingIndex]++;
  123. }
  124. return existingIndex;
  125. }
  126. // Couldn't find this it in the batch, add a new item
  127. // Frow capacity as necessary
  128. if (TokenCount == TokenCapacity)
  129. GrowTokenCapacity();
  130. if (sequences.Length > SequenceCapacity)
  131. GrowMaxSequences(sequences.Length);
  132. // Store the position in the index, so it can be found later
  133. _index.Add((token, pos), TokenCount);
  134. // Add the items to the arrays
  135. _tokens[TokenCount] = token;
  136. _positions[TokenCount] = pos;
  137. _sequenceIdCount[TokenCount] = sequences.Length;
  138. for (var i = 0; i < sequences.Length; i++)
  139. _sequenceIds[TokenCount][i] = sequences[i];
  140. _logits[TokenCount] = Convert.ToByte(logits);
  141. return TokenCount++;
  142. }
  143. /// <summary>
  144. /// Add a single token to the batch at the same position in several sequences
  145. /// </summary>
  146. /// <remarks>https://github.com/ggerganov/llama.cpp/blob/ad939626577cd25b462e8026cc543efb71528472/common/common.cpp#L829C2-L829C2</remarks>
  147. /// <param name="token">The token to add</param>
  148. /// <param name="pos">The position to add it att</param>
  149. /// <param name="sequences">The set of sequences to add this token to</param>
  150. /// <param name="logits"></param>
  151. /// <returns>The index that the token was added at. Use this for GetLogitsIth</returns>
  152. public int Add(LLamaToken token, LLamaPos pos, List<LLamaSeqId> sequences, bool logits)
  153. {
  154. #if NET5_0_OR_GREATER
  155. var seqSpan = CollectionsMarshal.AsSpan(sequences);
  156. return Add(token, pos, seqSpan, logits);
  157. #else
  158. // on netstandard2.0 we can't use CollectionsMarshal to get directly at the internal memory of
  159. // the list. Instead rent an array and copy the data into it. This avoids an allocation, but can't
  160. // avoid the copying.
  161. var rented = System.Buffers.ArrayPool<LLamaSeqId>.Shared.Rent(sequences.Count);
  162. try
  163. {
  164. sequences.CopyTo(rented, 0);
  165. return Add(token, pos, rented.AsSpan(0, sequences.Count), logits);
  166. }
  167. finally
  168. {
  169. System.Buffers.ArrayPool<LLamaSeqId>.Shared.Return(rented);
  170. }
  171. #endif
  172. }
  173. /// <summary>
  174. /// Add a single token to the batch at a certain position for a single sequences
  175. /// </summary>
  176. /// <remarks>https://github.com/ggerganov/llama.cpp/blob/ad939626577cd25b462e8026cc543efb71528472/common/common.cpp#L829C2-L829C2</remarks>
  177. /// <param name="token">The token to add</param>
  178. /// <param name="pos">The position to add it att</param>
  179. /// <param name="sequence">The sequence to add this token to</param>
  180. /// <param name="logits"></param>
  181. /// <returns>The index that the token was added at. Use this for GetLogitsIth</returns>
  182. public int Add(LLamaToken token, LLamaPos pos, LLamaSeqId sequence, bool logits)
  183. {
  184. // Create a temporary span to contain 1 item without allocating
  185. Span<LLamaSeqId> sequences = stackalloc LLamaSeqId[1];
  186. sequences[0] = sequence;
  187. // Add it
  188. return Add(token, pos, sequences, logits);
  189. }
  190. /// <summary>
  191. /// Add a range of tokens to a single sequence, start at the given position.
  192. /// </summary>
  193. /// <param name="tokens">The tokens to add</param>
  194. /// <param name="start">The starting position to add tokens at</param>
  195. /// <param name="sequence">The sequence to add this token to</param>
  196. /// <param name="logitsLast">Whether the final token should generate logits</param>
  197. /// <returns>The index that the final token was added at. Use this for GetLogitsIth</returns>
  198. public int AddRange(ReadOnlySpan<LLamaToken> tokens, LLamaPos start, LLamaSeqId sequence, bool logitsLast)
  199. {
  200. var last = -1;
  201. for (var i = 0; i < tokens.Length; i++)
  202. {
  203. var logits = (i == tokens.Length - 1) & logitsLast;
  204. last = Add(tokens[i], start.Value + i, sequence, logits);
  205. }
  206. return last;
  207. }
  208. #endregion
  209. /// <summary>
  210. /// Set TokenCount to zero for this batch
  211. /// </summary>
  212. public void Clear()
  213. {
  214. TokenCount = 0;
  215. _index.Clear();
  216. }
  217. }