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