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.

LLamaTokenDataArray.cs 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. using System;
  2. using System.Buffers;
  3. using System.Runtime.InteropServices;
  4. using llama_token = System.Int32;
  5. namespace LLama.Native
  6. {
  7. /// <summary>
  8. /// Contains an array of LLamaTokenData, potentially sorted.
  9. /// </summary>
  10. public struct LLamaTokenDataArray
  11. {
  12. /// <summary>
  13. /// The LLamaTokenData
  14. /// </summary>
  15. public readonly Memory<LLamaTokenData> data;
  16. /// <summary>
  17. /// Indicates if `data` is sorted by logits in descending order. If this is false the token data is in _no particular order_.
  18. /// </summary>
  19. public bool sorted;
  20. /// <summary>
  21. /// Create a new LLamaTokenDataArray
  22. /// </summary>
  23. /// <param name="tokens"></param>
  24. /// <param name="isSorted"></param>
  25. public LLamaTokenDataArray(Memory<LLamaTokenData> tokens, bool isSorted = false)
  26. {
  27. data = tokens;
  28. sorted = isSorted;
  29. }
  30. /// <summary>
  31. /// Create a new LLamaTokenDataArray, copying the data from the given logits
  32. /// </summary>
  33. /// <param name="logits"></param>
  34. /// <returns></returns>
  35. public static LLamaTokenDataArray Create(ReadOnlySpan<float> logits)
  36. {
  37. var candidates = new LLamaTokenData[logits.Length];
  38. for (var token_id = 0; token_id < logits.Length; token_id++)
  39. candidates[token_id] = new LLamaTokenData(token_id, logits[token_id], 0.0f);
  40. return new LLamaTokenDataArray(candidates);
  41. }
  42. /// <summary>
  43. /// Overwrite the logit values for all given tokens
  44. /// </summary>
  45. /// <param name="values">tuples of token and logit value to overwrite</param>
  46. public void OverwriteLogits(ReadOnlySpan<(llama_token token, float logit)> values)
  47. {
  48. if (values.Length == 0)
  49. return;
  50. var dataSpan = data.Span;
  51. foreach (var (token, value) in values)
  52. {
  53. for (var i = 0; i < data.Length; i++)
  54. {
  55. if (dataSpan[i].id == token)
  56. {
  57. dataSpan[i].logit = value;
  58. break;
  59. }
  60. }
  61. }
  62. sorted = false;
  63. }
  64. #region sampling
  65. /// <summary>
  66. /// Apply grammar rules to candidate tokens
  67. /// </summary>
  68. /// <param name="ctx"></param>
  69. /// <param name="grammar"></param>
  70. public void ApplyGrammar(SafeLLamaContextHandle ctx, SafeLLamaGrammarHandle? grammar)
  71. {
  72. if (grammar == null)
  73. return;
  74. using (LLamaTokenDataArrayNative.Create(this, out var st))
  75. {
  76. NativeApi.llama_sample_grammar(ctx, ref st, grammar);
  77. sorted = st.sorted;
  78. }
  79. }
  80. /// <summary>
  81. /// Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  82. /// </summary>
  83. /// <param name="context"></param>
  84. /// <param name="k">Number of tokens to keep</param>
  85. /// <param name="minKeep">Minimum number to keep</param>
  86. public void TopK(SafeLLamaContextHandle context, int k, ulong minKeep = 1)
  87. {
  88. using (LLamaTokenDataArrayNative.Create(this, out var st))
  89. {
  90. NativeApi.llama_sample_top_k(context, ref st, k, minKeep);
  91. sorted = st.sorted;
  92. }
  93. }
  94. /// <summary>
  95. /// Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751
  96. /// </summary>
  97. /// <param name="context"></param>
  98. /// <param name="p"></param>
  99. /// <param name="minKeep"></param>
  100. public void TopP(SafeLLamaContextHandle context, float p, ulong minKeep = 1)
  101. {
  102. using (LLamaTokenDataArrayNative.Create(this, out var st))
  103. {
  104. NativeApi.llama_sample_top_p(context, ref st, p, minKeep);
  105. sorted = st.sorted;
  106. }
  107. }
  108. /// <summary>
  109. /// Minimum P sampling as described in https://github.com/ggerganov/llama.cpp/pull/3841
  110. /// </summary>
  111. /// <param name="context"></param>
  112. /// <param name="p">All tokens with probability greater than this will be kept</param>
  113. /// <param name="minKeep"></param>
  114. public void MinP(SafeLLamaContextHandle context, float p, ulong minKeep = 1)
  115. {
  116. using (LLamaTokenDataArrayNative.Create(this, out var st))
  117. {
  118. NativeApi.llama_sample_min_p(context, ref st, p, minKeep);
  119. sorted = st.sorted;
  120. }
  121. }
  122. /// <summary>
  123. /// Tail Free Sampling described in https://www.trentonbricken.com/Tail-Free-Sampling/.
  124. /// </summary>
  125. /// <param name="context"></param>
  126. /// <param name="z"></param>
  127. /// <param name="min_keep"></param>
  128. public void TailFree(SafeLLamaContextHandle context, float z, ulong min_keep = 1)
  129. {
  130. using (LLamaTokenDataArrayNative.Create(this, out var st))
  131. {
  132. NativeApi.llama_sample_tail_free(context, ref st, z, min_keep);
  133. sorted = st.sorted;
  134. }
  135. }
  136. /// <summary>
  137. /// Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666.
  138. /// </summary>
  139. /// <param name="context"></param>
  140. /// <param name="p"></param>
  141. /// <param name="min_keep"></param>
  142. public void LocallyTypical(SafeLLamaContextHandle context, float p, ulong min_keep = 1)
  143. {
  144. using (LLamaTokenDataArrayNative.Create(this, out var st))
  145. {
  146. NativeApi.llama_sample_typical(context, ref st, p, min_keep);
  147. sorted = st.sorted;
  148. }
  149. }
  150. /// <summary>
  151. /// Repetition penalty described in CTRL academic paper https://arxiv.org/abs/1909.05858, with negative logit fix.
  152. /// Frequency and presence penalties described in OpenAI API https://platform.openai.com/docs/api-reference/parameter-details.
  153. /// </summary>
  154. /// <param name="context"></param>
  155. /// <param name="last_tokens"></param>
  156. /// <param name="penalty_repeat"></param>
  157. /// <param name="penalty_freq"></param>
  158. /// <param name="penalty_present"></param>
  159. public void RepetitionPenalty(SafeLLamaContextHandle context, ReadOnlySpan<llama_token> last_tokens, float penalty_repeat, float penalty_freq, float penalty_present)
  160. {
  161. unsafe
  162. {
  163. using (LLamaTokenDataArrayNative.Create(this, out var st))
  164. {
  165. fixed (int* last_tokens_handle = last_tokens)
  166. {
  167. NativeApi.llama_sample_repetition_penalties(context, ref st, last_tokens_handle, (ulong)last_tokens.Length, penalty_repeat, penalty_freq, penalty_present);
  168. sorted = st.sorted;
  169. }
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Sample with temperature.
  175. /// As temperature increases, the prediction becomes more diverse but also vulnerable to hallucinations -- generating tokens that are sensible but not factual
  176. /// </summary>
  177. /// <param name="context"></param>
  178. /// <param name="temp"></param>
  179. public void Temperature(SafeLLamaContextHandle context, float temp)
  180. {
  181. using (LLamaTokenDataArrayNative.Create(this, out var st))
  182. {
  183. NativeApi.llama_sample_temperature(context, ref st, temp);
  184. sorted = st.sorted;
  185. }
  186. }
  187. /// <summary>
  188. /// Sorts candidate tokens by their logits in descending order and calculate probabilities based on logits.
  189. /// </summary>
  190. /// <param name="context"></param>
  191. public void Softmax(SafeLLamaContextHandle context)
  192. {
  193. using (LLamaTokenDataArrayNative.Create(this, out var st))
  194. {
  195. NativeApi.llama_sample_softmax(context, ref st);
  196. sorted = st.sorted;
  197. }
  198. }
  199. /// <summary>
  200. /// Randomly selects a token from the candidates based on their probabilities.
  201. /// </summary>
  202. /// <param name="context"></param>
  203. /// <returns></returns>
  204. public int SampleToken(SafeLLamaContextHandle context)
  205. {
  206. using (LLamaTokenDataArrayNative.Create(this, out var st))
  207. {
  208. var token = NativeApi.llama_sample_token(context, ref st);
  209. sorted = st.sorted;
  210. return token;
  211. }
  212. }
  213. /// <summary>
  214. /// Selects the token with the highest probability.
  215. /// </summary>
  216. /// <param name="context"></param>
  217. /// <returns></returns>
  218. public int SampleTokenGreedy(SafeLLamaContextHandle context)
  219. {
  220. using (LLamaTokenDataArrayNative.Create(this, out var st))
  221. {
  222. var token = NativeApi.llama_sample_token_greedy(context, ref st);
  223. sorted = st.sorted;
  224. return token;
  225. }
  226. }
  227. /// <summary>
  228. /// Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  229. /// </summary>
  230. /// <param name="context"></param>
  231. /// <param name="tau">The target cross-entropy (or surprise) value you want to achieve for the generated text. A higher value corresponds to more surprising or less predictable text, while a lower value corresponds to less surprising or more predictable text.</param>
  232. /// <param name="eta">The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates.</param>
  233. /// <param name="m">The number of tokens considered in the estimation of `s_hat`. This is an arbitrary value that is used to calculate `s_hat`, which in turn helps to calculate the value of `k`. In the paper, they use `m = 100`, but you can experiment with different values to see how it affects the performance of the algorithm.</param>
  234. /// <param name="mu">Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal.</param>
  235. /// <returns></returns>
  236. public int SampleTokenMirostat(SafeLLamaContextHandle context, float tau, float eta, int m, ref float mu)
  237. {
  238. using (LLamaTokenDataArrayNative.Create(this, out var st))
  239. {
  240. var token = NativeApi.llama_sample_token_mirostat(context, ref st, tau, eta, m, ref mu);
  241. sorted = st.sorted;
  242. return token;
  243. }
  244. }
  245. /// <summary>
  246. /// Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words.
  247. /// </summary>
  248. /// <param name="context"></param>
  249. /// <param name="tau">The target cross-entropy (or surprise) value you want to achieve for the generated text. A higher value corresponds to more surprising or less predictable text, while a lower value corresponds to less surprising or more predictable text.</param>
  250. /// <param name="eta">The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates.</param>
  251. /// <param name="mu">Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal.</param>
  252. /// <returns></returns>
  253. public int SampleTokenMirostat2(SafeLLamaContextHandle context, float tau, float eta, ref float mu)
  254. {
  255. using (LLamaTokenDataArrayNative.Create(this, out var st))
  256. {
  257. var token = NativeApi.llama_sample_token_mirostat_v2(context, ref st, tau, eta, ref mu);
  258. sorted = st.sorted;
  259. return token;
  260. }
  261. }
  262. #endregion
  263. }
  264. /// <summary>
  265. /// Contains a pointer to an array of LLamaTokenData which is pinned in memory.
  266. /// </summary>
  267. [StructLayout(LayoutKind.Sequential)]
  268. public struct LLamaTokenDataArrayNative
  269. {
  270. /// <summary>
  271. /// A pointer to an array of LlamaTokenData
  272. /// </summary>
  273. /// <remarks>Memory must be pinned in place for all the time this LLamaTokenDataArrayNative is in use</remarks>
  274. public IntPtr data;
  275. /// <summary>
  276. /// Number of LLamaTokenData in the array
  277. /// </summary>
  278. public ulong size;
  279. /// <summary>
  280. /// Indicates if the items in the array are sorted
  281. /// </summary>
  282. public bool sorted
  283. {
  284. get => Convert.ToBoolean(_sorted);
  285. set => _sorted = Convert.ToSByte(value);
  286. }
  287. private sbyte _sorted;
  288. /// <summary>
  289. /// Create a new LLamaTokenDataArrayNative around the data in the LLamaTokenDataArray
  290. /// </summary>
  291. /// <param name="array">Data source</param>
  292. /// <param name="native">Created native array</param>
  293. /// <returns>A memory handle, pinning the data in place until disposed</returns>
  294. public static MemoryHandle Create(LLamaTokenDataArray array, out LLamaTokenDataArrayNative native)
  295. {
  296. var handle = array.data.Pin();
  297. unsafe
  298. {
  299. native = new LLamaTokenDataArrayNative
  300. {
  301. data = new IntPtr(handle.Pointer),
  302. size = (ulong)array.data.Length,
  303. sorted = array.sorted
  304. };
  305. }
  306. return handle;
  307. }
  308. }
  309. }