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

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