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 18 kB

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