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

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