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

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