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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. using var pin = @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. using var pin = 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 a byte array.
  155. /// </summary>
  156. /// <returns></returns>
  157. [Obsolete("Use `GetState` instead, this supports larger states (over 2GB)")]
  158. public byte[] GetStateData()
  159. {
  160. var stateSize = NativeApi.llama_get_state_size(_ctx);
  161. byte[] stateMemory = new byte[stateSize];
  162. NativeApi.llama_copy_state_data(_ctx, stateMemory);
  163. return stateMemory;
  164. }
  165. /// <summary>
  166. /// Get the state data as an opaque handle
  167. /// </summary>
  168. /// <returns></returns>
  169. public State GetState()
  170. {
  171. var stateSize = _ctx.GetStateSize();
  172. unsafe
  173. {
  174. // Allocate a chunk of memory large enough to hold the entire state
  175. var memory = Marshal.AllocHGlobal((nint)stateSize);
  176. try
  177. {
  178. // Copy the state data into memory, discover the actual size required
  179. var actualSize = _ctx.GetState(memory, stateSize);
  180. // Shrink to size
  181. memory = Marshal.ReAllocHGlobal(memory, (nint)actualSize);
  182. // Wrap memory in a "state"
  183. var state = new State(memory);
  184. // Set memory to zero, to prevent it being freed in finally block
  185. memory = IntPtr.Zero;
  186. return state;
  187. }
  188. finally
  189. {
  190. if (memory != IntPtr.Zero)
  191. Marshal.FreeHGlobal(memory);
  192. }
  193. }
  194. }
  195. /// <summary>
  196. /// Load the state from specified path.
  197. /// </summary>
  198. /// <param name="filename"></param>
  199. /// <exception cref="RuntimeError"></exception>
  200. public void LoadState(string filename)
  201. {
  202. // Map state file into memory and pass that pointer directly to `llama_set_state_data` to load from
  203. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Open, null))
  204. using (var view = file.CreateViewAccessor())
  205. {
  206. unsafe
  207. {
  208. byte* ptr = null;
  209. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  210. NativeApi.llama_set_state_data(_ctx, ptr);
  211. view.SafeMemoryMappedViewHandle.ReleasePointer();
  212. }
  213. }
  214. }
  215. /// <summary>
  216. /// Load the state from memory.
  217. /// </summary>
  218. /// <param name="stateData"></param>
  219. /// <exception cref="RuntimeError"></exception>
  220. public void LoadState(byte[] stateData)
  221. {
  222. int stateSize = (int)NativeApi.llama_get_state_size(_ctx);
  223. if (stateData.Length > stateSize)
  224. {
  225. throw new RuntimeError("Failed to validate state size.");
  226. }
  227. NativeApi.llama_set_state_data(_ctx, stateData);
  228. }
  229. /// <summary>
  230. /// Load the state from memory.
  231. /// </summary>
  232. /// <param name="state"></param>
  233. /// <exception cref="RuntimeError"></exception>
  234. public void LoadState(State state)
  235. {
  236. unsafe
  237. {
  238. _ctx.SetState((byte*)state.DangerousGetHandle().ToPointer());
  239. }
  240. }
  241. /// <summary>
  242. /// Perform the sampling. Please don't use it unless you fully know what it does.
  243. /// </summary>
  244. /// <param name="candidates"></param>
  245. /// <param name="mirostat_mu"></param>
  246. /// <param name="temperature"></param>
  247. /// <param name="mirostat"></param>
  248. /// <param name="mirostatTau"></param>
  249. /// <param name="mirostatEta"></param>
  250. /// <param name="topK"></param>
  251. /// <param name="topP"></param>
  252. /// <param name="tfsZ"></param>
  253. /// <param name="typicalP"></param>
  254. /// <param name="grammar"></param>
  255. /// <returns></returns>
  256. public llama_token Sample(LLamaTokenDataArray candidates, ref float? mirostat_mu, float temperature = 0.8f, MirostatType mirostat = MirostatType.Disable,
  257. float mirostatTau = 5.0f, float mirostatEta = 0.1f, int topK = 40, float topP = 0.95f, float tfsZ = 1.0f, float typicalP = 1.0f,
  258. SafeLLamaGrammarHandle? grammar = null)
  259. {
  260. llama_token id;
  261. if (grammar != null)
  262. {
  263. SamplingApi.llama_sample_grammar(_ctx, candidates, grammar);
  264. }
  265. if (temperature <= 0)
  266. {
  267. // Greedy sampling
  268. id = SamplingApi.llama_sample_token_greedy(_ctx, candidates);
  269. }
  270. else
  271. {
  272. var mu = mirostat_mu ?? (2 * mirostatTau);
  273. {
  274. if (mirostat == MirostatType.Mirostat)
  275. {
  276. const int mirostat_m = 100;
  277. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  278. id = SamplingApi.llama_sample_token_mirostat(_ctx, candidates, mirostatTau, mirostatEta, mirostat_m, ref mu);
  279. }
  280. else if (mirostat == MirostatType.Mirostat2)
  281. {
  282. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  283. id = SamplingApi.llama_sample_token_mirostat_v2(_ctx, candidates, mirostatTau, mirostatEta, ref mu);
  284. }
  285. else
  286. {
  287. // Temperature sampling
  288. SamplingApi.llama_sample_top_k(_ctx, candidates, topK, 1);
  289. SamplingApi.llama_sample_tail_free(_ctx, candidates, tfsZ, 1);
  290. SamplingApi.llama_sample_typical(_ctx, candidates, typicalP, 1);
  291. SamplingApi.llama_sample_top_p(_ctx, candidates, topP, 1);
  292. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  293. id = SamplingApi.llama_sample_token(_ctx, candidates);
  294. }
  295. }
  296. mirostat_mu = mu;
  297. }
  298. if (grammar != null)
  299. {
  300. NativeApi.llama_grammar_accept_token(_ctx, grammar, id);
  301. }
  302. return id;
  303. }
  304. /// <summary>
  305. /// Apply the penalty for the tokens. Please don't use it unless you fully know what it does.
  306. /// </summary>
  307. /// <param name="lastTokens"></param>
  308. /// <param name="logitBias"></param>
  309. /// <param name="repeatLastTokensCount"></param>
  310. /// <param name="repeatPenalty"></param>
  311. /// <param name="alphaFrequency"></param>
  312. /// <param name="alphaPresence"></param>
  313. /// <param name="penalizeNL"></param>
  314. /// <returns></returns>
  315. public LLamaTokenDataArray ApplyPenalty(IEnumerable<llama_token> lastTokens, Dictionary<llama_token, float>? logitBias = null,
  316. int repeatLastTokensCount = 64, float repeatPenalty = 1.1f, float alphaFrequency = .0f, float alphaPresence = .0f,
  317. bool penalizeNL = true)
  318. {
  319. var logits = _ctx.GetLogits();
  320. // Apply params.logit_bias map
  321. if (logitBias is not null)
  322. {
  323. foreach (var (key, value) in logitBias)
  324. logits[key] += value;
  325. }
  326. // Save the newline logit value
  327. var nl_token = NativeApi.llama_token_nl(_ctx);
  328. var nl_logit = logits[nl_token];
  329. // Convert logits into token candidates
  330. var candidates_p = LLamaTokenDataArray.Create(logits);
  331. // Extract most recently returned tokens
  332. var last_n_repeat = Math.Min(ContextSize, repeatLastTokensCount);
  333. var last_n_array = lastTokens.TakeLast(last_n_repeat).ToArray();
  334. // Apply penalties to candidates
  335. SamplingApi.llama_sample_repetition_penalty(_ctx, candidates_p, last_n_array, repeatPenalty);
  336. SamplingApi.llama_sample_frequency_and_presence_penalties(_ctx, candidates_p, last_n_array, alphaFrequency, alphaPresence);
  337. // Restore newline token logit value if necessary
  338. if (!penalizeNL)
  339. {
  340. var candidatesSpan = candidates_p.data.Span;
  341. for (var i = 0; i < candidates_p.data.Length; i++)
  342. {
  343. ref var item = ref candidatesSpan[i];
  344. if (item.id == nl_token)
  345. item.logit = nl_logit;
  346. }
  347. candidates_p.sorted = false;
  348. }
  349. return candidates_p;
  350. }
  351. #region eval overloads
  352. /// <summary>
  353. ///
  354. /// </summary>
  355. /// <param name="tokens"></param>
  356. /// <param name="pastTokensCount"></param>
  357. /// <returns>The updated `pastTokensCount`.</returns>
  358. /// <exception cref="RuntimeError"></exception>
  359. public int Eval(llama_token[] tokens, int pastTokensCount)
  360. {
  361. return Eval(tokens.AsSpan(), pastTokensCount);
  362. }
  363. /// <summary>
  364. ///
  365. /// </summary>
  366. /// <param name="tokens"></param>
  367. /// <param name="pastTokensCount"></param>
  368. /// <returns>The updated `pastTokensCount`.</returns>
  369. /// <exception cref="RuntimeError"></exception>
  370. public int Eval(List<llama_token> tokens, int pastTokensCount)
  371. {
  372. #if NET5_0_OR_GREATER
  373. var span = CollectionsMarshal.AsSpan(tokens);
  374. return Eval(span, pastTokensCount);
  375. #else
  376. // on netstandard2.0 we can't use CollectionsMarshal to get directly at the internal memory of
  377. // the list. Instead rent an array and copy the data into it. This avoids an allocation, but can't
  378. // avoid the copying.
  379. var rented = System.Buffers.ArrayPool<llama_token>.Shared.Rent(tokens.Count);
  380. try
  381. {
  382. tokens.CopyTo(rented, 0);
  383. return Eval(rented, pastTokensCount);
  384. }
  385. finally
  386. {
  387. System.Buffers.ArrayPool<llama_token>.Shared.Return(rented);
  388. }
  389. #endif
  390. }
  391. /// <summary>
  392. ///
  393. /// </summary>
  394. /// <param name="tokens"></param>
  395. /// <param name="pastTokensCount"></param>
  396. /// <returns>The updated `pastTokensCount`.</returns>
  397. /// <exception cref="RuntimeError"></exception>
  398. public int Eval(ReadOnlyMemory<llama_token> tokens, int pastTokensCount)
  399. {
  400. return Eval(tokens.Span, pastTokensCount);
  401. }
  402. /// <summary>
  403. ///
  404. /// </summary>
  405. /// <param name="tokens"></param>
  406. /// <param name="pastTokensCount"></param>
  407. /// <returns>The updated `pastTokensCount`.</returns>
  408. /// <exception cref="RuntimeError"></exception>
  409. public int Eval(ReadOnlySpan<llama_token> tokens, int pastTokensCount)
  410. {
  411. var total = tokens.Length;
  412. for(var i = 0; i < total; i += Params.BatchSize)
  413. {
  414. var n_eval = total - i;
  415. if (n_eval > Params.BatchSize)
  416. {
  417. n_eval = Params.BatchSize;
  418. }
  419. if (!_ctx.Eval(tokens.Slice(i, n_eval), pastTokensCount, Params.Threads))
  420. {
  421. _logger?.LogError($"[LLamaContext] Failed to eval.");
  422. throw new RuntimeError("Failed to eval.");
  423. }
  424. pastTokensCount += n_eval;
  425. }
  426. return pastTokensCount;
  427. }
  428. #endregion
  429. /// <summary>
  430. /// Convert a token into a string
  431. /// </summary>
  432. /// <param name="token"></param>
  433. /// <returns></returns>
  434. public string TokenToString(llama_token token)
  435. {
  436. return NativeHandle.TokenToString(token, Encoding);
  437. }
  438. /// <summary>
  439. /// Append a single token to a string builder
  440. /// </summary>
  441. /// <param name="token">Token to decode</param>
  442. /// <param name="dest">string builder to append the result to</param>
  443. public void TokenToString(llama_token token, StringBuilder dest)
  444. {
  445. NativeHandle.TokenToString(token, Encoding, dest);
  446. }
  447. /// <inheritdoc />
  448. public void Dispose()
  449. {
  450. _ctx.Dispose();
  451. }
  452. /// <summary>
  453. /// The state of this model, which can be reloaded later
  454. /// </summary>
  455. public class State
  456. : SafeLLamaHandleBase
  457. {
  458. internal State(IntPtr memory)
  459. : base(memory)
  460. {
  461. }
  462. /// <inheritdoc />
  463. protected override bool ReleaseHandle()
  464. {
  465. Marshal.FreeHGlobal(handle);
  466. return true;
  467. }
  468. }
  469. }
  470. }