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

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