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.

LLamaContext.cs 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. using LLama.Exceptions;
  2. using LLama.Native;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.IO;
  8. using System.IO.MemoryMappedFiles;
  9. using LLama.Common;
  10. using System.Runtime.InteropServices;
  11. using LLama.Extensions;
  12. using LLama.Abstractions;
  13. using Microsoft.Extensions.Logging;
  14. namespace LLama
  15. {
  16. using llama_token = Int32;
  17. /// <summary>
  18. /// A llama_context, which holds all the context required to interact with a model
  19. /// </summary>
  20. public sealed class LLamaContext
  21. : IDisposable
  22. {
  23. private readonly ILogger? _logger;
  24. /// <summary>
  25. /// Total number of tokens in vocabulary of this model
  26. /// </summary>
  27. public int VocabCount => NativeHandle.VocabCount;
  28. /// <summary>
  29. /// Total number of tokens in the context
  30. /// </summary>
  31. public int ContextSize => NativeHandle.ContextSize;
  32. /// <summary>
  33. /// Dimension of embedding vectors
  34. /// </summary>
  35. public int EmbeddingSize => NativeHandle.EmbeddingSize;
  36. /// <summary>
  37. /// The context params set for this context
  38. /// </summary>
  39. public IContextParams Params { get; set; }
  40. /// <summary>
  41. /// The native handle, which is used to be passed to the native APIs
  42. /// </summary>
  43. /// <remarks>Be careful how you use this!</remarks>
  44. public SafeLLamaContextHandle NativeHandle { get; }
  45. /// <summary>
  46. /// The encoding set for this model to deal with text input.
  47. /// </summary>
  48. public Encoding Encoding { get; }
  49. internal LLamaContext(SafeLLamaContextHandle nativeContext, IContextParams @params, ILogger? logger = null)
  50. {
  51. Params = @params;
  52. _logger = logger;
  53. Encoding = @params.Encoding;
  54. NativeHandle = nativeContext;
  55. }
  56. /// <summary>
  57. /// Create a new LLamaContext for the given LLamaWeights
  58. /// </summary>
  59. /// <param name="model"></param>
  60. /// <param name="params"></param>
  61. /// <param name="logger"></param>
  62. /// <exception cref="ObjectDisposedException"></exception>
  63. public LLamaContext(LLamaWeights model, IContextParams @params, ILogger? logger = null)
  64. {
  65. if (model.NativeHandle.IsClosed)
  66. throw new ObjectDisposedException("Cannot create context, model weights have been disposed");
  67. Params = @params;
  68. _logger = logger;
  69. Encoding = @params.Encoding;
  70. @params.ToLlamaContextParams(out var lparams);
  71. NativeHandle = SafeLLamaContextHandle.Create(model.NativeHandle, lparams);
  72. }
  73. /// <summary>
  74. /// Tokenize a string.
  75. /// </summary>
  76. /// <param name="text"></param>
  77. /// <param name="addBos">Whether to add a bos to the text.</param>
  78. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  79. /// <returns></returns>
  80. public llama_token[] Tokenize(string text, bool addBos = true, bool special = false)
  81. {
  82. return NativeHandle.Tokenize(text, addBos, special, Encoding);
  83. }
  84. /// <summary>
  85. /// Detokenize the tokens to text.
  86. /// </summary>
  87. /// <param name="tokens"></param>
  88. /// <returns></returns>
  89. public string DeTokenize(IEnumerable<llama_token> tokens)
  90. {
  91. var sb = new StringBuilder();
  92. foreach (var token in tokens)
  93. NativeHandle.TokenToString(token, Encoding, sb);
  94. return sb.ToString();
  95. }
  96. /// <summary>
  97. /// Save the state to specified path.
  98. /// </summary>
  99. /// <param name="filename"></param>
  100. public void SaveState(string filename)
  101. {
  102. // Delete that file before overwriting it
  103. if (File.Exists(filename))
  104. File.Delete(filename);
  105. // Estimate size of state to write to disk, this is always equal to or greater than the actual size
  106. var estimatedStateSize = (long)NativeApi.llama_get_state_size(NativeHandle);
  107. // Map the file and write the bytes directly to it. This saves copying the bytes into a C# array
  108. long writtenBytes;
  109. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Create, null, estimatedStateSize))
  110. using (var view = file.CreateViewAccessor(0, estimatedStateSize))
  111. {
  112. unsafe
  113. {
  114. byte* ptr = null;
  115. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  116. writtenBytes = (long)NativeApi.llama_copy_state_data(NativeHandle, ptr);
  117. view.SafeMemoryMappedViewHandle.ReleasePointer();
  118. }
  119. }
  120. // Truncate the file to the actual size of data that was written
  121. using (var fileStream = new FileStream(filename, FileMode.Open))
  122. fileStream.SetLength(writtenBytes);
  123. }
  124. /// <summary>
  125. /// Get the state data as an opaque handle
  126. /// </summary>
  127. /// <returns></returns>
  128. public State GetState()
  129. {
  130. var stateSize = NativeHandle.GetStateSize();
  131. // Allocate a chunk of memory large enough to hold the entire state
  132. var memory = Marshal.AllocHGlobal((nint)stateSize);
  133. try
  134. {
  135. // Copy the state data into memory, discover the actual size required
  136. var actualSize = NativeHandle.GetState(memory, stateSize);
  137. // Shrink to size
  138. memory = Marshal.ReAllocHGlobal(memory, (nint)actualSize);
  139. // Wrap memory in a "state"
  140. var state = new State(memory);
  141. // Set memory to zero, to prevent it being freed in finally block
  142. memory = IntPtr.Zero;
  143. return state;
  144. }
  145. finally
  146. {
  147. if (memory != IntPtr.Zero)
  148. Marshal.FreeHGlobal(memory);
  149. }
  150. }
  151. /// <summary>
  152. /// Load the state from specified path.
  153. /// </summary>
  154. /// <param name="filename"></param>
  155. /// <exception cref="RuntimeError"></exception>
  156. public void LoadState(string filename)
  157. {
  158. // Map state file into memory and pass that pointer directly to `llama_set_state_data` to load from
  159. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Open, null))
  160. using (var view = file.CreateViewAccessor())
  161. {
  162. unsafe
  163. {
  164. byte* ptr = null;
  165. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  166. NativeApi.llama_set_state_data(NativeHandle, ptr);
  167. view.SafeMemoryMappedViewHandle.ReleasePointer();
  168. }
  169. }
  170. }
  171. /// <summary>
  172. /// Load the state from memory.
  173. /// </summary>
  174. /// <param name="state"></param>
  175. /// <exception cref="RuntimeError"></exception>
  176. public void LoadState(State state)
  177. {
  178. unsafe
  179. {
  180. NativeHandle.SetState((byte*)state.DangerousGetHandle().ToPointer());
  181. }
  182. }
  183. /// <summary>
  184. /// Perform the sampling. Please don't use it unless you fully know what it does.
  185. /// </summary>
  186. /// <param name="candidates"></param>
  187. /// <param name="mirostat_mu"></param>
  188. /// <param name="temperature"></param>
  189. /// <param name="mirostat"></param>
  190. /// <param name="mirostatTau"></param>
  191. /// <param name="mirostatEta"></param>
  192. /// <param name="topK"></param>
  193. /// <param name="topP"></param>
  194. /// <param name="tfsZ"></param>
  195. /// <param name="typicalP"></param>
  196. /// <param name="grammar"></param>
  197. /// <returns></returns>
  198. public llama_token Sample(LLamaTokenDataArray candidates, ref float? mirostat_mu, float temperature = 0.8f, MirostatType mirostat = MirostatType.Disable,
  199. float mirostatTau = 5.0f, float mirostatEta = 0.1f, int topK = 40, float topP = 0.95f, float tfsZ = 1.0f, float typicalP = 1.0f,
  200. SafeLLamaGrammarHandle? grammar = null)
  201. {
  202. llama_token id;
  203. if (grammar != null)
  204. {
  205. SamplingApi.llama_sample_grammar(NativeHandle, candidates, grammar);
  206. }
  207. if (temperature <= 0)
  208. {
  209. // Greedy sampling
  210. id = SamplingApi.llama_sample_token_greedy(NativeHandle, candidates);
  211. }
  212. else
  213. {
  214. var mu = mirostat_mu ?? (2 * mirostatTau);
  215. {
  216. if (mirostat == MirostatType.Mirostat)
  217. {
  218. const int mirostat_m = 100;
  219. SamplingApi.llama_sample_temperature(NativeHandle, candidates, temperature);
  220. id = SamplingApi.llama_sample_token_mirostat(NativeHandle, candidates, mirostatTau, mirostatEta, mirostat_m, ref mu);
  221. }
  222. else if (mirostat == MirostatType.Mirostat2)
  223. {
  224. SamplingApi.llama_sample_temperature(NativeHandle, candidates, temperature);
  225. id = SamplingApi.llama_sample_token_mirostat_v2(NativeHandle, candidates, mirostatTau, mirostatEta, ref mu);
  226. }
  227. else
  228. {
  229. // Temperature sampling
  230. SamplingApi.llama_sample_top_k(NativeHandle, candidates, topK, 1);
  231. SamplingApi.llama_sample_tail_free(NativeHandle, candidates, tfsZ, 1);
  232. SamplingApi.llama_sample_typical(NativeHandle, candidates, typicalP, 1);
  233. SamplingApi.llama_sample_top_p(NativeHandle, candidates, topP, 1);
  234. SamplingApi.llama_sample_temperature(NativeHandle, candidates, temperature);
  235. id = SamplingApi.llama_sample_token(NativeHandle, candidates);
  236. }
  237. }
  238. mirostat_mu = mu;
  239. }
  240. if (grammar != null)
  241. {
  242. NativeApi.llama_grammar_accept_token(NativeHandle, grammar, id);
  243. }
  244. return id;
  245. }
  246. /// <summary>
  247. /// Apply the penalty for the tokens. Please don't use it unless you fully know what it does.
  248. /// </summary>
  249. /// <param name="lastTokens"></param>
  250. /// <param name="logitBias"></param>
  251. /// <param name="repeatLastTokensCount"></param>
  252. /// <param name="repeatPenalty"></param>
  253. /// <param name="alphaFrequency"></param>
  254. /// <param name="alphaPresence"></param>
  255. /// <param name="penalizeNL"></param>
  256. /// <returns></returns>
  257. public LLamaTokenDataArray ApplyPenalty(IEnumerable<llama_token> lastTokens, Dictionary<llama_token, float>? logitBias = null,
  258. int repeatLastTokensCount = 64, float repeatPenalty = 1.1f, float alphaFrequency = .0f, float alphaPresence = .0f,
  259. bool penalizeNL = true)
  260. {
  261. var logits = NativeHandle.GetLogits();
  262. // Apply params.logit_bias map
  263. if (logitBias is not null)
  264. {
  265. foreach (var (key, value) in logitBias)
  266. logits[key] += value;
  267. }
  268. // Save the newline logit value
  269. var nl_token = NativeApi.llama_token_nl(NativeHandle);
  270. var nl_logit = logits[nl_token];
  271. // Convert logits into token candidates
  272. var candidates_p = LLamaTokenDataArray.Create(logits);
  273. // Extract most recently returned tokens
  274. var last_n_repeat = Math.Min(ContextSize, repeatLastTokensCount);
  275. var last_n_array = lastTokens.TakeLast(last_n_repeat).ToArray();
  276. // Apply penalties to candidates
  277. SamplingApi.llama_sample_repetition_penalty(NativeHandle, candidates_p, last_n_array, repeatPenalty);
  278. SamplingApi.llama_sample_frequency_and_presence_penalties(NativeHandle, candidates_p, last_n_array, alphaFrequency, alphaPresence);
  279. // Restore newline token logit value if necessary
  280. if (!penalizeNL)
  281. {
  282. var candidatesSpan = candidates_p.data.Span;
  283. for (var i = 0; i < candidates_p.data.Length; i++)
  284. {
  285. ref var item = ref candidatesSpan[i];
  286. if (item.id == nl_token)
  287. item.logit = nl_logit;
  288. }
  289. candidates_p.sorted = false;
  290. }
  291. return candidates_p;
  292. }
  293. #region eval overloads
  294. /// <summary>
  295. ///
  296. /// </summary>
  297. /// <param name="tokens"></param>
  298. /// <param name="pastTokensCount"></param>
  299. /// <returns>The updated `pastTokensCount`.</returns>
  300. /// <exception cref="RuntimeError"></exception>
  301. public int Eval(llama_token[] tokens, int pastTokensCount)
  302. {
  303. return Eval(tokens.AsSpan(), pastTokensCount);
  304. }
  305. /// <summary>
  306. ///
  307. /// </summary>
  308. /// <param name="tokens"></param>
  309. /// <param name="pastTokensCount"></param>
  310. /// <returns>The updated `pastTokensCount`.</returns>
  311. /// <exception cref="RuntimeError"></exception>
  312. public int Eval(List<llama_token> tokens, int pastTokensCount)
  313. {
  314. #if NET5_0_OR_GREATER
  315. var span = CollectionsMarshal.AsSpan(tokens);
  316. return Eval(span, pastTokensCount);
  317. #else
  318. // on netstandard2.0 we can't use CollectionsMarshal to get directly at the internal memory of
  319. // the list. Instead rent an array and copy the data into it. This avoids an allocation, but can't
  320. // avoid the copying.
  321. var rented = System.Buffers.ArrayPool<llama_token>.Shared.Rent(tokens.Count);
  322. try
  323. {
  324. tokens.CopyTo(rented, 0);
  325. return Eval(rented, pastTokensCount);
  326. }
  327. finally
  328. {
  329. System.Buffers.ArrayPool<llama_token>.Shared.Return(rented);
  330. }
  331. #endif
  332. }
  333. /// <summary>
  334. ///
  335. /// </summary>
  336. /// <param name="tokens"></param>
  337. /// <param name="pastTokensCount"></param>
  338. /// <returns>The updated `pastTokensCount`.</returns>
  339. /// <exception cref="RuntimeError"></exception>
  340. public int Eval(ReadOnlyMemory<llama_token> tokens, int pastTokensCount)
  341. {
  342. return Eval(tokens.Span, pastTokensCount);
  343. }
  344. /// <summary>
  345. ///
  346. /// </summary>
  347. /// <param name="tokens"></param>
  348. /// <param name="pastTokensCount"></param>
  349. /// <returns>The updated `pastTokensCount`.</returns>
  350. /// <exception cref="RuntimeError"></exception>
  351. public int Eval(ReadOnlySpan<llama_token> tokens, int pastTokensCount)
  352. {
  353. var total = tokens.Length;
  354. for(var i = 0; i < total; i += (int)Params.BatchSize)
  355. {
  356. var n_eval = total - i;
  357. if (n_eval > Params.BatchSize)
  358. {
  359. n_eval = (int)Params.BatchSize;
  360. }
  361. if (!NativeHandle.Eval(tokens.Slice(i, n_eval), pastTokensCount))
  362. {
  363. _logger?.LogError("[LLamaContext] Failed to eval.");
  364. throw new RuntimeError("Failed to eval.");
  365. }
  366. pastTokensCount += n_eval;
  367. }
  368. return pastTokensCount;
  369. }
  370. #endregion
  371. /// <summary>
  372. /// Convert a token into a string
  373. /// </summary>
  374. /// <param name="token"></param>
  375. /// <returns></returns>
  376. public string TokenToString(llama_token token)
  377. {
  378. return NativeHandle.TokenToString(token, Encoding);
  379. }
  380. /// <summary>
  381. /// Append a single token to a string builder
  382. /// </summary>
  383. /// <param name="token">Token to decode</param>
  384. /// <param name="dest">string builder to append the result to</param>
  385. public void TokenToString(llama_token token, StringBuilder dest)
  386. {
  387. NativeHandle.TokenToString(token, Encoding, dest);
  388. }
  389. /// <inheritdoc />
  390. public void Dispose()
  391. {
  392. NativeHandle.Dispose();
  393. }
  394. /// <summary>
  395. /// The state of this model, which can be reloaded later
  396. /// </summary>
  397. public class State
  398. : SafeLLamaHandleBase
  399. {
  400. internal State(IntPtr memory)
  401. : base(memory)
  402. {
  403. }
  404. /// <inheritdoc />
  405. protected override bool ReleaseHandle()
  406. {
  407. Marshal.FreeHGlobal(handle);
  408. return true;
  409. }
  410. }
  411. }
  412. }