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

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