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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. using LLama.Exceptions;
  2. using LLama.Native;
  3. using System;
  4. using System.Buffers;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.IO;
  9. using System.IO.MemoryMappedFiles;
  10. using LLama.Common;
  11. using System.Runtime.InteropServices;
  12. using LLama.Extensions;
  13. using LLama.Abstractions;
  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 class LLamaContext
  21. : IDisposable
  22. {
  23. private readonly ILLamaLogger? _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. /// The model params set for this model.
  40. /// </summary>
  41. public IModelParams Params { get; set; }
  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 => _ctx;
  47. /// <summary>
  48. /// The encoding set for this model to deal with text input.
  49. /// </summary>
  50. public Encoding Encoding => _encoding;
  51. /// <summary>
  52. ///
  53. /// </summary>
  54. /// <param name="params">Model params.</param>
  55. /// <param name="logger">The logger.</param>
  56. [Obsolete("Use the LLamaWeights.CreateContext instead")]
  57. public LLamaContext(IModelParams @params, ILLamaLogger? logger = null)
  58. {
  59. Params = @params;
  60. _logger = logger;
  61. _encoding = @params.Encoding;
  62. _logger?.Log(nameof(LLamaContext), $"Initializing LLama model with params: {this.Params}", ILLamaLogger.LogLevel.Info);
  63. _ctx = Utils.InitLLamaContextFromModelParams(Params);
  64. }
  65. internal LLamaContext(SafeLLamaContextHandle nativeContext, IModelParams @params, ILLamaLogger? logger = null)
  66. {
  67. Params = @params;
  68. _logger = logger;
  69. _encoding = @params.Encoding;
  70. _ctx = nativeContext;
  71. }
  72. /// <summary>
  73. /// Create a new LLamaContext for the given LLamaWeights
  74. /// </summary>
  75. /// <param name="model"></param>
  76. /// <param name="params"></param>
  77. /// <param name="logger"></param>
  78. /// <exception cref="ObjectDisposedException"></exception>
  79. public LLamaContext(LLamaWeights model, IModelParams @params, ILLamaLogger? logger = null)
  80. {
  81. if (model.NativeHandle.IsClosed)
  82. throw new ObjectDisposedException("Cannot create context, model weights have been disposed");
  83. Params = @params;
  84. _logger = logger;
  85. _encoding = @params.Encoding;
  86. using var pin = @params.ToLlamaContextParams(out var lparams);
  87. _ctx = SafeLLamaContextHandle.Create(model.NativeHandle, lparams);
  88. }
  89. /// <summary>
  90. /// Create a copy of the current state of this context
  91. /// </summary>
  92. /// <returns></returns>
  93. public LLamaContext Clone()
  94. {
  95. using var pin = Params.ToLlamaContextParams(out var lparams);
  96. // Create a blank new context for the model
  97. var ctx = new LLamaContext(SafeLLamaContextHandle.Create(NativeHandle.ModelHandle, lparams), Params);
  98. // Copy across the state
  99. using var state = GetState();
  100. ctx.LoadState(state);
  101. return ctx;
  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. StringBuilder sb = new();
  121. foreach(var token in tokens)
  122. sb.Append(_ctx.TokenToString(token, _encoding));
  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 = NativeApi.llama_get_state_size(_ctx);
  172. unsafe
  173. {
  174. var bigMemory = Marshal.AllocHGlobal((nint)stateSize);
  175. var smallMemory = IntPtr.Zero;
  176. try
  177. {
  178. // Copy the state data into "big memory", discover the actual size required
  179. var actualSize = NativeApi.llama_copy_state_data(_ctx, (byte*)bigMemory);
  180. // Allocate a smaller buffer
  181. smallMemory = Marshal.AllocHGlobal((nint)actualSize);
  182. // Copy into the smaller buffer and free the large one to save excess memory usage
  183. Buffer.MemoryCopy(bigMemory.ToPointer(), smallMemory.ToPointer(), actualSize, actualSize);
  184. Marshal.FreeHGlobal(bigMemory);
  185. bigMemory = IntPtr.Zero;
  186. return new State(smallMemory);
  187. }
  188. catch
  189. {
  190. if (bigMemory != IntPtr.Zero)
  191. Marshal.FreeHGlobal(bigMemory);
  192. if (smallMemory != IntPtr.Zero)
  193. Marshal.FreeHGlobal(smallMemory);
  194. throw;
  195. }
  196. }
  197. }
  198. /// <summary>
  199. /// Load the state from specified path.
  200. /// </summary>
  201. /// <param name="filename"></param>
  202. /// <exception cref="RuntimeError"></exception>
  203. public void LoadState(string filename)
  204. {
  205. // Map state file into memory and pass that pointer directly to `llama_set_state_data` to load from
  206. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Open, null))
  207. using (var view = file.CreateViewAccessor())
  208. {
  209. unsafe
  210. {
  211. byte* ptr = null;
  212. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  213. NativeApi.llama_set_state_data(_ctx, ptr);
  214. view.SafeMemoryMappedViewHandle.ReleasePointer();
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// Load the state from memory.
  220. /// </summary>
  221. /// <param name="stateData"></param>
  222. /// <exception cref="RuntimeError"></exception>
  223. public void LoadState(byte[] stateData)
  224. {
  225. int stateSize = (int)NativeApi.llama_get_state_size(_ctx);
  226. if (stateData.Length > stateSize)
  227. {
  228. throw new RuntimeError("Failed to validate state size.");
  229. }
  230. NativeApi.llama_set_state_data(_ctx, stateData);
  231. }
  232. /// <summary>
  233. /// Load the state from memory.
  234. /// </summary>
  235. /// <param name="state"></param>
  236. /// <exception cref="RuntimeError"></exception>
  237. public void LoadState(State state)
  238. {
  239. unsafe
  240. {
  241. NativeApi.llama_set_state_data(_ctx, (byte*)state.DangerousGetHandle().ToPointer());
  242. }
  243. }
  244. /// <summary>
  245. /// Perform the sampling. Please don't use it unless you fully know what it does.
  246. /// </summary>
  247. /// <param name="candidates"></param>
  248. /// <param name="mirostat_mu"></param>
  249. /// <param name="temperature"></param>
  250. /// <param name="mirostat"></param>
  251. /// <param name="mirostatTau"></param>
  252. /// <param name="mirostatEta"></param>
  253. /// <param name="topK"></param>
  254. /// <param name="topP"></param>
  255. /// <param name="tfsZ"></param>
  256. /// <param name="typicalP"></param>
  257. /// <param name="grammar"></param>
  258. /// <returns></returns>
  259. public llama_token Sample(LLamaTokenDataArray candidates, ref float? mirostat_mu, float temperature = 0.8f, MirostatType mirostat = MirostatType.Disable,
  260. float mirostatTau = 5.0f, float mirostatEta = 0.1f, int topK = 40, float topP = 0.95f, float tfsZ = 1.0f, float typicalP = 1.0f,
  261. SafeLLamaGrammarHandle? grammar = null)
  262. {
  263. llama_token id;
  264. if (grammar != null)
  265. {
  266. SamplingApi.llama_sample_grammar(_ctx, candidates, grammar);
  267. }
  268. if (temperature <= 0)
  269. {
  270. // Greedy sampling
  271. id = SamplingApi.llama_sample_token_greedy(_ctx, candidates);
  272. }
  273. else
  274. {
  275. var mu = mirostat_mu ?? (2 * mirostatTau);
  276. {
  277. if (mirostat == MirostatType.Mirostat)
  278. {
  279. const int mirostat_m = 100;
  280. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  281. id = SamplingApi.llama_sample_token_mirostat(_ctx, candidates, mirostatTau, mirostatEta, mirostat_m, ref mu);
  282. }
  283. else if (mirostat == MirostatType.Mirostat2)
  284. {
  285. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  286. id = SamplingApi.llama_sample_token_mirostat_v2(_ctx, candidates, mirostatTau, mirostatEta, ref mu);
  287. }
  288. else
  289. {
  290. // Temperature sampling
  291. SamplingApi.llama_sample_top_k(_ctx, candidates, topK, 1);
  292. SamplingApi.llama_sample_tail_free(_ctx, candidates, tfsZ, 1);
  293. SamplingApi.llama_sample_typical(_ctx, candidates, typicalP, 1);
  294. SamplingApi.llama_sample_top_p(_ctx, candidates, topP, 1);
  295. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  296. id = SamplingApi.llama_sample_token(_ctx, candidates);
  297. }
  298. }
  299. mirostat_mu = mu;
  300. }
  301. if (grammar != null)
  302. {
  303. NativeApi.llama_grammar_accept_token(_ctx, grammar, id);
  304. }
  305. return id;
  306. }
  307. /// <summary>
  308. /// Apply the penalty for the tokens. Please don't use it unless you fully know what it does.
  309. /// </summary>
  310. /// <param name="lastTokens"></param>
  311. /// <param name="logitBias"></param>
  312. /// <param name="repeatLastTokensCount"></param>
  313. /// <param name="repeatPenalty"></param>
  314. /// <param name="alphaFrequency"></param>
  315. /// <param name="alphaPresence"></param>
  316. /// <param name="penalizeNL"></param>
  317. /// <returns></returns>
  318. public LLamaTokenDataArray ApplyPenalty(IEnumerable<llama_token> lastTokens, Dictionary<llama_token, float>? logitBias = null,
  319. int repeatLastTokensCount = 64, float repeatPenalty = 1.1f, float alphaFrequency = .0f, float alphaPresence = .0f,
  320. bool penalizeNL = true)
  321. {
  322. var n_vocab = _ctx.VocabCount;
  323. var logits = _ctx.GetLogits();
  324. // Apply params.logit_bias map
  325. if(logitBias is not null)
  326. {
  327. foreach (var (key, value) in logitBias)
  328. {
  329. logits[key] += value;
  330. }
  331. }
  332. var candidates = new LLamaTokenData[n_vocab];
  333. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  334. candidates[token_id] = new LLamaTokenData(token_id, logits[token_id], 0.0f);
  335. LLamaTokenDataArray candidates_p = new LLamaTokenDataArray(candidates);
  336. // Apply penalties
  337. float nl_logit = logits[NativeApi.llama_token_nl()];
  338. int lastTokensCount = lastTokens.Count();
  339. var last_n_repeat = Math.Min(Math.Min(lastTokensCount, repeatLastTokensCount), ContextSize);
  340. SamplingApi.llama_sample_repetition_penalty(_ctx, candidates_p,
  341. lastTokens.Skip(lastTokensCount - last_n_repeat).ToArray(),
  342. (ulong)last_n_repeat, repeatPenalty);
  343. SamplingApi.llama_sample_frequency_and_presence_penalties(_ctx, candidates_p,
  344. lastTokens.Skip(lastTokensCount - last_n_repeat).ToArray(),
  345. (ulong)last_n_repeat, alphaFrequency, alphaPresence);
  346. if (!penalizeNL)
  347. {
  348. logits[NativeApi.llama_token_nl()] = nl_logit;
  349. }
  350. return candidates_p;
  351. }
  352. #region eval overloads
  353. /// <summary>
  354. ///
  355. /// </summary>
  356. /// <param name="tokens"></param>
  357. /// <param name="pastTokensCount"></param>
  358. /// <returns>The updated `pastTokensCount`.</returns>
  359. /// <exception cref="RuntimeError"></exception>
  360. public int Eval(llama_token[] tokens, llama_token pastTokensCount)
  361. {
  362. return Eval(tokens.AsSpan(), pastTokensCount);
  363. }
  364. /// <summary>
  365. ///
  366. /// </summary>
  367. /// <param name="tokens"></param>
  368. /// <param name="pastTokensCount"></param>
  369. /// <returns>The updated `pastTokensCount`.</returns>
  370. /// <exception cref="RuntimeError"></exception>
  371. public int Eval(List<llama_token> tokens, llama_token pastTokensCount)
  372. {
  373. #if NET5_0_OR_GREATER
  374. var span = CollectionsMarshal.AsSpan(tokens);
  375. return Eval(span, pastTokensCount);
  376. #else
  377. // on netstandard2.0 we can't use CollectionsMarshal to get directly at the internal memory of
  378. // the list. Instead rent an array and copy the data into it. This avoids an allocation, but can't
  379. // avoid the copying.
  380. var rented = ArrayPool<llama_token>.Shared.Rent(tokens.Count);
  381. try
  382. {
  383. tokens.CopyTo(rented, 0);
  384. return Eval(rented, pastTokensCount);
  385. }
  386. finally
  387. {
  388. ArrayPool<llama_token>.Shared.Return(rented);
  389. }
  390. #endif
  391. }
  392. /// <summary>
  393. ///
  394. /// </summary>
  395. /// <param name="tokens"></param>
  396. /// <param name="pastTokensCount"></param>
  397. /// <returns>The updated `pastTokensCount`.</returns>
  398. /// <exception cref="RuntimeError"></exception>
  399. public int Eval(ReadOnlyMemory<llama_token> tokens, llama_token pastTokensCount)
  400. {
  401. return Eval(tokens.Span, pastTokensCount);
  402. }
  403. /// <summary>
  404. ///
  405. /// </summary>
  406. /// <param name="tokens"></param>
  407. /// <param name="pastTokensCount"></param>
  408. /// <returns>The updated `pastTokensCount`.</returns>
  409. /// <exception cref="RuntimeError"></exception>
  410. public int Eval(ReadOnlySpan<llama_token> tokens, llama_token pastTokensCount)
  411. {
  412. var total = tokens.Length;
  413. for(var i = 0; i < total; i += Params.BatchSize)
  414. {
  415. var n_eval = total - i;
  416. if (n_eval > Params.BatchSize)
  417. {
  418. n_eval = Params.BatchSize;
  419. }
  420. if (!_ctx.Eval(tokens.Slice(i, n_eval), pastTokensCount, Params.Threads))
  421. {
  422. _logger?.Log(nameof(LLamaContext), "Failed to eval.", ILLamaLogger.LogLevel.Error);
  423. throw new RuntimeError("Failed to eval.");
  424. }
  425. pastTokensCount += n_eval;
  426. }
  427. return pastTokensCount;
  428. }
  429. #endregion
  430. internal IEnumerable<string> GenerateResult(IEnumerable<llama_token> ids)
  431. {
  432. foreach(var id in ids)
  433. yield return _ctx.TokenToString(id, _encoding);
  434. }
  435. /// <summary>
  436. /// Convert a token into a string
  437. /// </summary>
  438. /// <param name="token"></param>
  439. /// <returns></returns>
  440. public string TokenToString(llama_token token)
  441. {
  442. return NativeHandle.TokenToString(token, Encoding);
  443. }
  444. /// <inheritdoc />
  445. public virtual void Dispose()
  446. {
  447. GC.SuppressFinalize(this);
  448. _ctx.Dispose();
  449. }
  450. /// <summary>
  451. /// The state of this model, which can be reloaded later
  452. /// </summary>
  453. public class State
  454. : SafeLLamaHandleBase
  455. {
  456. internal State(IntPtr memory)
  457. : base(memory)
  458. {
  459. }
  460. /// <inheritdoc />
  461. protected override bool ReleaseHandle()
  462. {
  463. Marshal.FreeHGlobal(handle);
  464. return true;
  465. }
  466. }
  467. }
  468. }