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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. [Obsolete("Use a `StreamingTokenDecoder` instead")]
  90. public string DeTokenize(IReadOnlyList<llama_token> tokens)
  91. {
  92. // Do **not** use this method as an example of how to correctly use the StreamingTokenDecoder!
  93. // It should be kept around for the entire time you are decoding one stream of tokens.
  94. var decoder = new StreamingTokenDecoder(this);
  95. decoder.AddRange(tokens);
  96. return decoder.Read();
  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(NativeHandle);
  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(NativeHandle, 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 = NativeHandle.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 = NativeHandle.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(NativeHandle, 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. NativeHandle.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. candidates.ApplyGrammar(NativeHandle, grammar);
  208. }
  209. if (temperature <= 0)
  210. {
  211. // Greedy sampling
  212. id = candidates.SampleTokenGreedy(NativeHandle);
  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. candidates.Temperature(NativeHandle, temperature);
  222. id = candidates.SampleTokenMirostat(NativeHandle, mirostatTau, mirostatEta, mirostat_m, ref mu);
  223. }
  224. else if (mirostat == MirostatType.Mirostat2)
  225. {
  226. candidates.Temperature(NativeHandle, temperature);
  227. id = candidates.SampleTokenMirostat2(NativeHandle, mirostatTau, mirostatEta, ref mu);
  228. }
  229. else
  230. {
  231. candidates.TopK(NativeHandle, topK);
  232. candidates.TailFree(NativeHandle, tfsZ);
  233. candidates.LocallyTypical(NativeHandle, typicalP);
  234. candidates.TopP(NativeHandle, topP);
  235. candidates.Temperature(NativeHandle, temperature);
  236. id = candidates.SampleToken(NativeHandle);
  237. }
  238. }
  239. mirostat_mu = mu;
  240. }
  241. grammar?.AcceptToken(NativeHandle, id);
  242. return id;
  243. }
  244. /// <summary>
  245. /// Apply the penalty for the tokens. Please don't use it unless you fully know what it does.
  246. /// </summary>
  247. /// <param name="lastTokens"></param>
  248. /// <param name="logitBias"></param>
  249. /// <param name="repeatLastTokensCount"></param>
  250. /// <param name="repeatPenalty"></param>
  251. /// <param name="alphaFrequency"></param>
  252. /// <param name="alphaPresence"></param>
  253. /// <param name="penalizeNL"></param>
  254. /// <returns></returns>
  255. public LLamaTokenDataArray ApplyPenalty(IEnumerable<llama_token> lastTokens, Dictionary<llama_token, float>? logitBias = null,
  256. int repeatLastTokensCount = 64, float repeatPenalty = 1.1f, float alphaFrequency = .0f, float alphaPresence = .0f,
  257. bool penalizeNL = true)
  258. {
  259. var logits = NativeHandle.GetLogits();
  260. // Apply params.logit_bias map
  261. if (logitBias is not null)
  262. {
  263. foreach (var (key, value) in logitBias)
  264. logits[key] += value;
  265. }
  266. // Save the newline logit value
  267. var nl_token = NativeApi.llama_token_nl(NativeHandle.ModelHandle);
  268. var nl_logit = logits[nl_token];
  269. // Convert logits into token candidates
  270. var candidates_p = LLamaTokenDataArray.Create(logits);
  271. // Extract most recently returned tokens
  272. var last_n_repeat = Math.Min(ContextSize, repeatLastTokensCount);
  273. var last_n_array = lastTokens.TakeLast(last_n_repeat).ToArray();
  274. // Apply penalties to candidates
  275. candidates_p.RepetitionPenalty(NativeHandle, last_n_array, repeatPenalty, alphaFrequency, alphaPresence);
  276. // Restore newline token logit value if necessary
  277. if (!penalizeNL)
  278. {
  279. var candidatesSpan = candidates_p.data.Span;
  280. for (var i = 0; i < candidates_p.data.Length; i++)
  281. {
  282. ref var item = ref candidatesSpan[i];
  283. if (item.id == nl_token)
  284. item.logit = nl_logit;
  285. }
  286. candidates_p.sorted = false;
  287. }
  288. return candidates_p;
  289. }
  290. #region eval overloads
  291. /// <summary>
  292. ///
  293. /// </summary>
  294. /// <param name="tokens"></param>
  295. /// <param name="pastTokensCount"></param>
  296. /// <returns>The updated `pastTokensCount`.</returns>
  297. /// <exception cref="RuntimeError"></exception>
  298. public int Eval(llama_token[] tokens, int pastTokensCount)
  299. {
  300. return Eval(tokens.AsSpan(), pastTokensCount);
  301. }
  302. /// <summary>
  303. ///
  304. /// </summary>
  305. /// <param name="tokens"></param>
  306. /// <param name="pastTokensCount"></param>
  307. /// <returns>The updated `pastTokensCount`.</returns>
  308. /// <exception cref="RuntimeError"></exception>
  309. public int Eval(List<llama_token> tokens, int pastTokensCount)
  310. {
  311. #if NET5_0_OR_GREATER
  312. var span = CollectionsMarshal.AsSpan(tokens);
  313. return Eval(span, pastTokensCount);
  314. #else
  315. // on netstandard2.0 we can't use CollectionsMarshal to get directly at the internal memory of
  316. // the list. Instead rent an array and copy the data into it. This avoids an allocation, but can't
  317. // avoid the copying.
  318. var rented = System.Buffers.ArrayPool<llama_token>.Shared.Rent(tokens.Count);
  319. try
  320. {
  321. tokens.CopyTo(rented, 0);
  322. return Eval(rented, pastTokensCount);
  323. }
  324. finally
  325. {
  326. System.Buffers.ArrayPool<llama_token>.Shared.Return(rented);
  327. }
  328. #endif
  329. }
  330. /// <summary>
  331. ///
  332. /// </summary>
  333. /// <param name="tokens"></param>
  334. /// <param name="pastTokensCount"></param>
  335. /// <returns>The updated `pastTokensCount`.</returns>
  336. /// <exception cref="RuntimeError"></exception>
  337. public int Eval(ReadOnlyMemory<llama_token> tokens, int pastTokensCount)
  338. {
  339. return Eval(tokens.Span, pastTokensCount);
  340. }
  341. /// <summary>
  342. ///
  343. /// </summary>
  344. /// <param name="tokens"></param>
  345. /// <param name="pastTokensCount"></param>
  346. /// <returns>The updated `pastTokensCount`.</returns>
  347. /// <exception cref="RuntimeError"></exception>
  348. public int Eval(ReadOnlySpan<llama_token> tokens, int pastTokensCount)
  349. {
  350. var total = tokens.Length;
  351. for(var i = 0; i < total; i += (int)Params.BatchSize)
  352. {
  353. var n_eval = total - i;
  354. if (n_eval > Params.BatchSize)
  355. {
  356. n_eval = (int)Params.BatchSize;
  357. }
  358. if (!NativeHandle.Eval(tokens.Slice(i, n_eval), pastTokensCount))
  359. {
  360. _logger?.LogError("[LLamaContext] Failed to eval.");
  361. throw new RuntimeError("Failed to eval.");
  362. }
  363. pastTokensCount += n_eval;
  364. }
  365. return pastTokensCount;
  366. }
  367. #endregion
  368. /// <inheritdoc />
  369. public void Dispose()
  370. {
  371. NativeHandle.Dispose();
  372. }
  373. /// <summary>
  374. /// The state of this model, which can be reloaded later
  375. /// </summary>
  376. public class State
  377. : SafeLLamaHandleBase
  378. {
  379. internal State(IntPtr memory)
  380. : base(memory)
  381. {
  382. }
  383. /// <inheritdoc />
  384. protected override bool ReleaseHandle()
  385. {
  386. Marshal.FreeHGlobal(handle);
  387. return true;
  388. }
  389. }
  390. }
  391. }