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

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