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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. private readonly Encoding _encoding;
  25. private readonly SafeLLamaContextHandle _ctx;
  26. /// <summary>
  27. /// Total number of tokens in vocabulary of this model
  28. /// </summary>
  29. public int VocabCount => _ctx.VocabCount;
  30. /// <summary>
  31. /// Total number of tokens in the context
  32. /// </summary>
  33. public int ContextSize => _ctx.ContextSize;
  34. /// <summary>
  35. /// Dimension of embedding vectors
  36. /// </summary>
  37. public int EmbeddingSize => _ctx.EmbeddingSize;
  38. /// <summary>
  39. /// Get the number of tokens in the KV Cache for this context
  40. /// </summary>
  41. public int KVCacheTokenCount => _ctx.KVCacheTokenCount;
  42. /// <summary>
  43. /// The model params set for this model.
  44. /// </summary>
  45. public IModelParams Params { get; set; }
  46. /// <summary>
  47. /// The native handle, which is used to be passed to the native APIs
  48. /// </summary>
  49. /// <remarks>Be careful how you use this!</remarks>
  50. public SafeLLamaContextHandle NativeHandle => _ctx;
  51. /// <summary>
  52. /// The encoding set for this model to deal with text input.
  53. /// </summary>
  54. public Encoding Encoding => _encoding;
  55. /// <summary>
  56. ///
  57. /// </summary>
  58. /// <param name="params">Model params.</param>
  59. /// <param name="logger">The logger.</param>
  60. [Obsolete("Use the LLamaWeights.CreateContext instead")]
  61. public LLamaContext(IModelParams @params, ILogger? logger = null)
  62. {
  63. Params = @params;
  64. _logger = logger;
  65. _encoding = @params.Encoding;
  66. _logger?.LogInformation($"[LLamaContext] Initializing LLama model with params: {this.Params}");
  67. _ctx = Utils.InitLLamaContextFromModelParams(Params);
  68. }
  69. internal LLamaContext(SafeLLamaContextHandle nativeContext, IModelParams @params, ILogger? logger = null)
  70. {
  71. Params = @params;
  72. _logger = logger;
  73. _encoding = @params.Encoding;
  74. _ctx = nativeContext;
  75. }
  76. /// <summary>
  77. /// Create a new LLamaContext for the given LLamaWeights
  78. /// </summary>
  79. /// <param name="model"></param>
  80. /// <param name="params"></param>
  81. /// <param name="logger"></param>
  82. /// <exception cref="ObjectDisposedException"></exception>
  83. public LLamaContext(LLamaWeights model, IModelParams @params, ILogger? logger = null)
  84. {
  85. if (model.NativeHandle.IsClosed)
  86. throw new ObjectDisposedException("Cannot create context, model weights have been disposed");
  87. Params = @params;
  88. _logger = logger;
  89. _encoding = @params.Encoding;
  90. @params.ToLlamaContextParams(out var lparams);
  91. _ctx = SafeLLamaContextHandle.Create(model.NativeHandle, lparams);
  92. }
  93. /// <summary>
  94. /// Create a copy of the current state of this context
  95. /// </summary>
  96. /// <returns></returns>
  97. public LLamaContext Clone()
  98. {
  99. Params.ToLlamaContextParams(out var lparams);
  100. var clone = _ctx.Clone(lparams);
  101. return new LLamaContext(clone, Params);
  102. }
  103. /// <summary>
  104. /// Tokenize a string.
  105. /// </summary>
  106. /// <param name="text"></param>
  107. /// <param name="addBos">Whether to add a bos to the text.</param>
  108. /// <returns></returns>
  109. public llama_token[] Tokenize(string text, bool addBos = true)
  110. {
  111. return _ctx.Tokenize(text, addBos, _encoding);
  112. }
  113. /// <summary>
  114. /// Detokenize the tokens to text.
  115. /// </summary>
  116. /// <param name="tokens"></param>
  117. /// <returns></returns>
  118. public string DeTokenize(IEnumerable<llama_token> tokens)
  119. {
  120. var sb = new StringBuilder();
  121. foreach (var token in tokens)
  122. _ctx.TokenToString(token, _encoding, sb);
  123. return sb.ToString();
  124. }
  125. /// <summary>
  126. /// Save the state to specified path.
  127. /// </summary>
  128. /// <param name="filename"></param>
  129. public void SaveState(string filename)
  130. {
  131. // Delete that file before overwriting it
  132. if (File.Exists(filename))
  133. File.Delete(filename);
  134. // Estimate size of state to write to disk, this is always equal to or greater than the actual size
  135. var estimatedStateSize = (long)NativeApi.llama_get_state_size(_ctx);
  136. // Map the file and write the bytes directly to it. This saves copying the bytes into a C# array
  137. long writtenBytes;
  138. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Create, null, estimatedStateSize))
  139. using (var view = file.CreateViewAccessor(0, estimatedStateSize))
  140. {
  141. unsafe
  142. {
  143. byte* ptr = null;
  144. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  145. writtenBytes = (long)NativeApi.llama_copy_state_data(_ctx, ptr);
  146. view.SafeMemoryMappedViewHandle.ReleasePointer();
  147. }
  148. }
  149. // Truncate the file to the actual size of data that was written
  150. using (var fileStream = new FileStream(filename, FileMode.Open))
  151. fileStream.SetLength(writtenBytes);
  152. }
  153. /// <summary>
  154. /// Get the state data as an opaque handle
  155. /// </summary>
  156. /// <returns></returns>
  157. public State GetState()
  158. {
  159. var stateSize = _ctx.GetStateSize();
  160. // Allocate a chunk of memory large enough to hold the entire state
  161. var memory = Marshal.AllocHGlobal((nint)stateSize);
  162. try
  163. {
  164. // Copy the state data into memory, discover the actual size required
  165. var actualSize = _ctx.GetState(memory, stateSize);
  166. // Shrink to size
  167. memory = Marshal.ReAllocHGlobal(memory, (nint)actualSize);
  168. // Wrap memory in a "state"
  169. var state = new State(memory);
  170. // Set memory to zero, to prevent it being freed in finally block
  171. memory = IntPtr.Zero;
  172. return state;
  173. }
  174. finally
  175. {
  176. if (memory != IntPtr.Zero)
  177. Marshal.FreeHGlobal(memory);
  178. }
  179. }
  180. /// <summary>
  181. /// Load the state from specified path.
  182. /// </summary>
  183. /// <param name="filename"></param>
  184. /// <exception cref="RuntimeError"></exception>
  185. public void LoadState(string filename)
  186. {
  187. // Map state file into memory and pass that pointer directly to `llama_set_state_data` to load from
  188. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Open, null))
  189. using (var view = file.CreateViewAccessor())
  190. {
  191. unsafe
  192. {
  193. byte* ptr = null;
  194. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  195. NativeApi.llama_set_state_data(_ctx, ptr);
  196. view.SafeMemoryMappedViewHandle.ReleasePointer();
  197. }
  198. }
  199. }
  200. /// <summary>
  201. /// Load the state from memory.
  202. /// </summary>
  203. /// <param name="state"></param>
  204. /// <exception cref="RuntimeError"></exception>
  205. public void LoadState(State state)
  206. {
  207. unsafe
  208. {
  209. _ctx.SetState((byte*)state.DangerousGetHandle().ToPointer());
  210. }
  211. }
  212. /// <summary>
  213. /// Perform the sampling. Please don't use it unless you fully know what it does.
  214. /// </summary>
  215. /// <param name="candidates"></param>
  216. /// <param name="mirostat_mu"></param>
  217. /// <param name="temperature"></param>
  218. /// <param name="mirostat"></param>
  219. /// <param name="mirostatTau"></param>
  220. /// <param name="mirostatEta"></param>
  221. /// <param name="topK"></param>
  222. /// <param name="topP"></param>
  223. /// <param name="tfsZ"></param>
  224. /// <param name="typicalP"></param>
  225. /// <param name="grammar"></param>
  226. /// <returns></returns>
  227. public llama_token Sample(LLamaTokenDataArray candidates, ref float? mirostat_mu, float temperature = 0.8f, MirostatType mirostat = MirostatType.Disable,
  228. float mirostatTau = 5.0f, float mirostatEta = 0.1f, int topK = 40, float topP = 0.95f, float tfsZ = 1.0f, float typicalP = 1.0f,
  229. SafeLLamaGrammarHandle? grammar = null)
  230. {
  231. llama_token id;
  232. if (grammar != null)
  233. {
  234. SamplingApi.llama_sample_grammar(_ctx, candidates, grammar);
  235. }
  236. if (temperature <= 0)
  237. {
  238. // Greedy sampling
  239. id = SamplingApi.llama_sample_token_greedy(_ctx, candidates);
  240. }
  241. else
  242. {
  243. var mu = mirostat_mu ?? (2 * mirostatTau);
  244. {
  245. if (mirostat == MirostatType.Mirostat)
  246. {
  247. const int mirostat_m = 100;
  248. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  249. id = SamplingApi.llama_sample_token_mirostat(_ctx, candidates, mirostatTau, mirostatEta, mirostat_m, ref mu);
  250. }
  251. else if (mirostat == MirostatType.Mirostat2)
  252. {
  253. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  254. id = SamplingApi.llama_sample_token_mirostat_v2(_ctx, candidates, mirostatTau, mirostatEta, ref mu);
  255. }
  256. else
  257. {
  258. // Temperature sampling
  259. SamplingApi.llama_sample_top_k(_ctx, candidates, topK, 1);
  260. SamplingApi.llama_sample_tail_free(_ctx, candidates, tfsZ, 1);
  261. SamplingApi.llama_sample_typical(_ctx, candidates, typicalP, 1);
  262. SamplingApi.llama_sample_top_p(_ctx, candidates, topP, 1);
  263. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  264. id = SamplingApi.llama_sample_token(_ctx, candidates);
  265. }
  266. }
  267. mirostat_mu = mu;
  268. }
  269. if (grammar != null)
  270. {
  271. NativeApi.llama_grammar_accept_token(_ctx, grammar, id);
  272. }
  273. return id;
  274. }
  275. /// <summary>
  276. /// Apply the penalty for the tokens. Please don't use it unless you fully know what it does.
  277. /// </summary>
  278. /// <param name="lastTokens"></param>
  279. /// <param name="logitBias"></param>
  280. /// <param name="repeatLastTokensCount"></param>
  281. /// <param name="repeatPenalty"></param>
  282. /// <param name="alphaFrequency"></param>
  283. /// <param name="alphaPresence"></param>
  284. /// <param name="penalizeNL"></param>
  285. /// <returns></returns>
  286. public LLamaTokenDataArray ApplyPenalty(IEnumerable<llama_token> lastTokens, Dictionary<llama_token, float>? logitBias = null,
  287. int repeatLastTokensCount = 64, float repeatPenalty = 1.1f, float alphaFrequency = .0f, float alphaPresence = .0f,
  288. bool penalizeNL = true)
  289. {
  290. var logits = _ctx.GetLogits();
  291. // Apply params.logit_bias map
  292. if (logitBias is not null)
  293. {
  294. foreach (var (key, value) in logitBias)
  295. logits[key] += value;
  296. }
  297. // Save the newline logit value
  298. var nl_token = NativeApi.llama_token_nl(_ctx);
  299. var nl_logit = logits[nl_token];
  300. // Convert logits into token candidates
  301. var candidates_p = LLamaTokenDataArray.Create(logits);
  302. // Extract most recently returned tokens
  303. var last_n_repeat = Math.Min(ContextSize, repeatLastTokensCount);
  304. var last_n_array = lastTokens.TakeLast(last_n_repeat).ToArray();
  305. // Apply penalties to candidates
  306. SamplingApi.llama_sample_repetition_penalty(_ctx, candidates_p, last_n_array, repeatPenalty);
  307. SamplingApi.llama_sample_frequency_and_presence_penalties(_ctx, candidates_p, last_n_array, alphaFrequency, alphaPresence);
  308. // Restore newline token logit value if necessary
  309. if (!penalizeNL)
  310. {
  311. var candidatesSpan = candidates_p.data.Span;
  312. for (var i = 0; i < candidates_p.data.Length; i++)
  313. {
  314. ref var item = ref candidatesSpan[i];
  315. if (item.id == nl_token)
  316. item.logit = nl_logit;
  317. }
  318. candidates_p.sorted = false;
  319. }
  320. return candidates_p;
  321. }
  322. #region eval overloads
  323. /// <summary>
  324. ///
  325. /// </summary>
  326. /// <param name="tokens"></param>
  327. /// <param name="pastTokensCount"></param>
  328. /// <returns>The updated `pastTokensCount`.</returns>
  329. /// <exception cref="RuntimeError"></exception>
  330. public int Eval(llama_token[] tokens, llama_token pastTokensCount)
  331. {
  332. return Eval(tokens.AsSpan(), pastTokensCount);
  333. }
  334. /// <summary>
  335. ///
  336. /// </summary>
  337. /// <param name="tokens"></param>
  338. /// <param name="pastTokensCount"></param>
  339. /// <returns>The updated `pastTokensCount`.</returns>
  340. /// <exception cref="RuntimeError"></exception>
  341. public int Eval(List<llama_token> tokens, llama_token pastTokensCount)
  342. {
  343. #if NET5_0_OR_GREATER
  344. var span = CollectionsMarshal.AsSpan(tokens);
  345. return Eval(span, pastTokensCount);
  346. #else
  347. // on netstandard2.0 we can't use CollectionsMarshal to get directly at the internal memory of
  348. // the list. Instead rent an array and copy the data into it. This avoids an allocation, but can't
  349. // avoid the copying.
  350. var rented = System.Buffers.ArrayPool<llama_token>.Shared.Rent(tokens.Count);
  351. try
  352. {
  353. tokens.CopyTo(rented, 0);
  354. return Eval(rented, pastTokensCount);
  355. }
  356. finally
  357. {
  358. System.Buffers.ArrayPool<llama_token>.Shared.Return(rented);
  359. }
  360. #endif
  361. }
  362. /// <summary>
  363. ///
  364. /// </summary>
  365. /// <param name="tokens"></param>
  366. /// <param name="pastTokensCount"></param>
  367. /// <returns>The updated `pastTokensCount`.</returns>
  368. /// <exception cref="RuntimeError"></exception>
  369. public int Eval(ReadOnlyMemory<llama_token> tokens, llama_token pastTokensCount)
  370. {
  371. return Eval(tokens.Span, pastTokensCount);
  372. }
  373. /// <summary>
  374. ///
  375. /// </summary>
  376. /// <param name="tokens"></param>
  377. /// <param name="pastTokensCount"></param>
  378. /// <returns>The updated `pastTokensCount`.</returns>
  379. /// <exception cref="RuntimeError"></exception>
  380. public int Eval(ReadOnlySpan<llama_token> tokens, llama_token pastTokensCount)
  381. {
  382. var total = tokens.Length;
  383. for(var i = 0; i < total; i += (int)Params.BatchSize)
  384. {
  385. var n_eval = total - i;
  386. if (n_eval > Params.BatchSize)
  387. {
  388. n_eval = (int)Params.BatchSize;
  389. }
  390. if (!_ctx.Eval(tokens.Slice(i, n_eval), pastTokensCount))
  391. {
  392. _logger?.LogError($"[LLamaContext] Failed to eval.");
  393. throw new RuntimeError("Failed to eval.");
  394. }
  395. pastTokensCount += n_eval;
  396. }
  397. return pastTokensCount;
  398. }
  399. #endregion
  400. /// <summary>
  401. /// Convert a token into a string
  402. /// </summary>
  403. /// <param name="token"></param>
  404. /// <returns></returns>
  405. public string TokenToString(llama_token token)
  406. {
  407. return NativeHandle.TokenToString(token, Encoding);
  408. }
  409. /// <summary>
  410. /// Append a single token to a string builder
  411. /// </summary>
  412. /// <param name="token">Token to decode</param>
  413. /// <param name="dest">string builder to append the result to</param>
  414. public void TokenToString(llama_token token, StringBuilder dest)
  415. {
  416. NativeHandle.TokenToString(token, Encoding, dest);
  417. }
  418. /// <inheritdoc />
  419. public void Dispose()
  420. {
  421. _ctx.Dispose();
  422. }
  423. /// <summary>
  424. /// The state of this model, which can be reloaded later
  425. /// </summary>
  426. public class State
  427. : SafeLLamaHandleBase
  428. {
  429. internal State(IntPtr memory)
  430. : base(memory)
  431. {
  432. }
  433. /// <inheritdoc />
  434. protected override bool ReleaseHandle()
  435. {
  436. Marshal.FreeHGlobal(handle);
  437. return true;
  438. }
  439. }
  440. }
  441. }