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

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