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 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, which can be loaded later using <see cref="LoadState(State)"/>
  131. /// </summary>
  132. /// <remarks>Use <see cref="SaveState"/> if you intend to save this state to disk.</remarks>
  133. /// <returns></returns>
  134. public State GetState()
  135. {
  136. var stateSize = NativeHandle.GetStateSize();
  137. // Allocate a chunk of memory large enough to hold the entire state
  138. var memory = Marshal.AllocHGlobal((nint)stateSize);
  139. try
  140. {
  141. // Copy the state data into memory, discover the actual size required
  142. var actualSize = NativeHandle.GetState(memory, stateSize);
  143. // Shrink to size
  144. memory = Marshal.ReAllocHGlobal(memory, (nint)actualSize);
  145. // Wrap memory in a "state"
  146. var state = new State(memory);
  147. // Set memory to zero, to prevent it being freed in finally block
  148. memory = IntPtr.Zero;
  149. return state;
  150. }
  151. finally
  152. {
  153. if (memory != IntPtr.Zero)
  154. Marshal.FreeHGlobal(memory);
  155. }
  156. }
  157. /// <summary>
  158. /// Load the state from specified path.
  159. /// </summary>
  160. /// <param name="filename"></param>
  161. /// <exception cref="RuntimeError"></exception>
  162. public void LoadState(string filename)
  163. {
  164. // Map state file into memory and pass that pointer directly to `llama_set_state_data` to load from
  165. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Open, null))
  166. using (var view = file.CreateViewAccessor())
  167. {
  168. unsafe
  169. {
  170. byte* ptr = null;
  171. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  172. NativeApi.llama_set_state_data(NativeHandle, ptr);
  173. view.SafeMemoryMappedViewHandle.ReleasePointer();
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// Load the state from memory.
  179. /// </summary>
  180. /// <param name="state"></param>
  181. /// <exception cref="RuntimeError"></exception>
  182. public void LoadState(State state)
  183. {
  184. unsafe
  185. {
  186. NativeHandle.SetState((byte*)state.DangerousGetHandle().ToPointer());
  187. }
  188. }
  189. /// <summary>
  190. /// Sample a single token from this context, using the given sampling pipeline
  191. /// </summary>
  192. /// <param name="pipeline">The pipeline to use to process the logits and to select a token</param>
  193. /// <param name="lastTokens">The tokens recently returned from the model</param>
  194. /// <returns>The selected token</returns>
  195. public LLamaToken Sample(ISamplingPipeline pipeline, ReadOnlySpan<LLamaToken> lastTokens)
  196. {
  197. var token = pipeline.Sample(NativeHandle, NativeHandle.GetLogits(), lastTokens);
  198. pipeline.Accept(NativeHandle, token);
  199. return token;
  200. }
  201. /// <summary>
  202. /// Perform the sampling. Please don't use it unless you fully know what it does.
  203. /// </summary>
  204. /// <param name="candidates"></param>
  205. /// <param name="mirostat_mu"></param>
  206. /// <param name="temperature"></param>
  207. /// <param name="mirostat"></param>
  208. /// <param name="mirostatTau"></param>
  209. /// <param name="mirostatEta"></param>
  210. /// <param name="topK"></param>
  211. /// <param name="topP"></param>
  212. /// <param name="tfsZ"></param>
  213. /// <param name="typicalP"></param>
  214. /// <param name="grammar"></param>
  215. /// <param name="minP"></param>
  216. /// <returns></returns>
  217. public LLamaToken Sample(LLamaTokenDataArray candidates, ref float? mirostat_mu, float temperature, MirostatType mirostat,
  218. float mirostatTau, float mirostatEta, int topK, float topP, float tfsZ, float typicalP,
  219. SafeLLamaGrammarHandle? grammar, float minP)
  220. {
  221. LLamaToken id;
  222. if (grammar != null)
  223. {
  224. candidates.ApplyGrammar(NativeHandle, grammar);
  225. }
  226. if (temperature <= 0)
  227. {
  228. // Greedy sampling
  229. id = candidates.SampleTokenGreedy(NativeHandle);
  230. }
  231. else
  232. {
  233. var mu = mirostat_mu ?? (2 * mirostatTau);
  234. {
  235. if (mirostat == MirostatType.Mirostat)
  236. {
  237. const int mirostat_m = 100;
  238. candidates.Temperature(NativeHandle, temperature);
  239. id = candidates.SampleTokenMirostat(NativeHandle, mirostatTau, mirostatEta, mirostat_m, ref mu);
  240. }
  241. else if (mirostat == MirostatType.Mirostat2)
  242. {
  243. candidates.Temperature(NativeHandle, temperature);
  244. id = candidates.SampleTokenMirostat2(NativeHandle, mirostatTau, mirostatEta, ref mu);
  245. }
  246. else
  247. {
  248. candidates.TopK(NativeHandle, topK);
  249. candidates.TailFree(NativeHandle, tfsZ);
  250. candidates.LocallyTypical(NativeHandle, typicalP);
  251. candidates.TopP(NativeHandle, topP);
  252. candidates.MinP(NativeHandle, minP);
  253. candidates.Temperature(NativeHandle, temperature);
  254. id = candidates.SampleToken(NativeHandle);
  255. }
  256. }
  257. mirostat_mu = mu;
  258. }
  259. grammar?.AcceptToken(NativeHandle, id);
  260. return id;
  261. }
  262. /// <summary>
  263. /// Apply the penalty for the tokens. Please don't use it unless you fully know what it does.
  264. /// </summary>
  265. /// <param name="logits_i"></param>
  266. /// <param name="lastTokens"></param>
  267. /// <param name="logitBias"></param>
  268. /// <param name="repeatLastTokensCount"></param>
  269. /// <param name="repeatPenalty"></param>
  270. /// <param name="alphaFrequency"></param>
  271. /// <param name="alphaPresence"></param>
  272. /// <param name="penalizeNL"></param>
  273. /// <returns></returns>
  274. public LLamaTokenDataArray ApplyPenalty(int logits_i, IEnumerable<LLamaToken> lastTokens, Dictionary<LLamaToken, float>? logitBias = null,
  275. int repeatLastTokensCount = 64, float repeatPenalty = 1.1f, float alphaFrequency = .0f, float alphaPresence = .0f,
  276. bool penalizeNL = true)
  277. {
  278. var logits = NativeHandle.GetLogitsIth(logits_i);
  279. // Apply params.logit_bias map
  280. if (logitBias is not null)
  281. {
  282. foreach (var (key, value) in logitBias)
  283. logits[(int)key] += value;
  284. }
  285. // Save the newline logit value
  286. var nl_token = NativeApi.llama_token_nl(NativeHandle.ModelHandle);
  287. var nl_logit = logits[(int)nl_token];
  288. // Convert logits into token candidates
  289. var candidates_p = LLamaTokenDataArray.Create(logits);
  290. // Extract most recently returned tokens
  291. var last_n_repeat = Math.Min((int)ContextSize, repeatLastTokensCount);
  292. var last_n_array = lastTokens.TakeLast(last_n_repeat).ToArray();
  293. // Apply penalties to candidates
  294. candidates_p.RepetitionPenalty(NativeHandle, last_n_array, repeatPenalty, alphaFrequency, alphaPresence);
  295. // Restore newline token logit value if necessary
  296. if (!penalizeNL)
  297. {
  298. var candidatesSpan = candidates_p.data.Span;
  299. for (var i = 0; i < candidates_p.data.Length; i++)
  300. {
  301. ref var item = ref candidatesSpan[i];
  302. if (item.id == nl_token)
  303. item.logit = nl_logit;
  304. }
  305. candidates_p.sorted = false;
  306. }
  307. return candidates_p;
  308. }
  309. #region eval overloads
  310. /// <summary>
  311. /// </summary>
  312. /// <param name="batch"></param>
  313. public DecodeResult Decode(LLamaBatch batch)
  314. {
  315. if (batch.TokenCount == 0)
  316. return 0;
  317. if (batch.TokenCount > Params.BatchSize)
  318. throw new ArgumentException("Input contains more tokens than configured batch size", nameof(batch));
  319. return (DecodeResult)NativeHandle.Decode(batch);
  320. }
  321. /// <summary>
  322. /// </summary>
  323. /// <param name="batch"></param>
  324. /// <param name="cancellationToken"></param>
  325. public Task<DecodeResult> DecodeAsync(LLamaBatch batch, CancellationToken cancellationToken = default)
  326. {
  327. return Task.Run(() => Decode(batch), cancellationToken);
  328. }
  329. /// <summary>
  330. ///
  331. /// </summary>
  332. /// <param name="tokens"></param>
  333. /// <param name="pastTokensCount"></param>
  334. /// <returns>The updated `pastTokensCount`.</returns>
  335. /// <exception cref="RuntimeError"></exception>
  336. [Obsolete("use Decode() instead")]
  337. public int Eval(List<LLamaToken> tokens, int pastTokensCount)
  338. {
  339. #if NET5_0_OR_GREATER
  340. var span = CollectionsMarshal.AsSpan(tokens);
  341. return Eval(span, pastTokensCount);
  342. #else
  343. // on netstandard2.0 we can't use CollectionsMarshal to get directly at the internal memory of
  344. // the list. Instead rent an array and copy the data into it. This avoids an allocation, but can't
  345. // avoid the copying.
  346. var rented = System.Buffers.ArrayPool<LLamaToken>.Shared.Rent(tokens.Count);
  347. try
  348. {
  349. tokens.CopyTo(rented, 0);
  350. return Eval(rented.AsSpan(0, tokens.Count), pastTokensCount);
  351. }
  352. finally
  353. {
  354. System.Buffers.ArrayPool<LLamaToken>.Shared.Return(rented);
  355. }
  356. #endif
  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 Decode() instead")]
  366. public int Eval(ReadOnlySpan<LLamaToken> 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, true)
  399. {
  400. }
  401. /// <inheritdoc />
  402. protected override bool ReleaseHandle()
  403. {
  404. Marshal.FreeHGlobal(handle);
  405. return true;
  406. }
  407. }
  408. }
  409. }