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.

LLamaModel.cs 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 Microsoft.Win32.SafeHandles;
  13. namespace LLama
  14. {
  15. using llama_token = Int32;
  16. /// <summary>
  17. /// The abstraction of a LLama model, which holds the context in the native library.
  18. /// </summary>
  19. public class LLamaModel: IDisposable
  20. {
  21. // TODO: expose more properties.
  22. ILLamaLogger? _logger;
  23. Encoding _encoding;
  24. SafeLLamaContextHandle _ctx;
  25. /// <summary>
  26. /// The context size.
  27. /// </summary>
  28. public int ContextSize { get; }
  29. /// <summary>
  30. /// The model params set for this model.
  31. /// </summary>
  32. public ModelParams Params { get; set; }
  33. /// <summary>
  34. /// The native handle, which is used to be passed to the native APIs. Please avoid using it
  35. /// unless you know what is the usage of the Native API.
  36. /// </summary>
  37. public SafeLLamaContextHandle NativeHandle => _ctx;
  38. /// <summary>
  39. /// The encoding set for this model to deal with text input.
  40. /// </summary>
  41. public Encoding Encoding => _encoding;
  42. /// <summary>
  43. ///
  44. /// </summary>
  45. /// <param name="Params">Model params.</param>
  46. /// <param name="encoding">Encoding to deal with text input.</param>
  47. /// <param name="logger">The logger.</param>
  48. public LLamaModel(ModelParams Params, string encoding = "UTF-8", ILLamaLogger? logger = null)
  49. {
  50. _logger = logger;
  51. this.Params = Params;
  52. _encoding = Encoding.GetEncoding(encoding);
  53. _logger?.Log(nameof(LLamaModel), $"Initializing LLama model with params: {this.Params}", ILLamaLogger.LogLevel.Info);
  54. _ctx = Utils.InitLLamaContextFromModelParams(this.Params);
  55. ContextSize = NativeApi.llama_n_ctx(_ctx);
  56. }
  57. /// <summary>
  58. /// Tokenize a string.
  59. /// </summary>
  60. /// <param name="text"></param>
  61. /// <param name="addBos">Whether to add a bos to the text.</param>
  62. /// <returns></returns>
  63. public IEnumerable<llama_token> Tokenize(string text, bool addBos = true)
  64. {
  65. // TODO: reconsider whether to convert to array here.
  66. return Utils.Tokenize(_ctx, text, addBos, _encoding);
  67. }
  68. /// <summary>
  69. /// Detokenize the tokens to text.
  70. /// </summary>
  71. /// <param name="tokens"></param>
  72. /// <returns></returns>
  73. public string DeTokenize(IEnumerable<llama_token> tokens)
  74. {
  75. StringBuilder sb = new();
  76. foreach(var token in tokens)
  77. {
  78. sb.Append(Utils.PtrToString(NativeApi.llama_token_to_str(_ctx, token), _encoding));
  79. }
  80. return sb.ToString();
  81. }
  82. /// <summary>
  83. /// Save the state to specified path.
  84. /// </summary>
  85. /// <param name="filename"></param>
  86. public void SaveState(string filename)
  87. {
  88. // Delete that file before overwriting it
  89. if (File.Exists(filename))
  90. File.Delete(filename);
  91. // Estimate size of state to write to disk, this is always equal to or greater than the actual size
  92. var estimatedStateSize = (long)NativeApi.llama_get_state_size(_ctx);
  93. // Map the file and write the bytes directly to it. This saves copying the bytes into a C# array
  94. long writtenBytes;
  95. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Create, null, estimatedStateSize))
  96. using (var view = file.CreateViewAccessor(0, estimatedStateSize))
  97. {
  98. unsafe
  99. {
  100. byte* ptr = null;
  101. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  102. writtenBytes = (long)NativeApi.llama_copy_state_data(_ctx, ptr);
  103. view.SafeMemoryMappedViewHandle.ReleasePointer();
  104. }
  105. }
  106. // Truncate the file to the actual size of data that was written
  107. using (var fileStream = new FileStream(filename, FileMode.Open))
  108. fileStream.SetLength(writtenBytes);
  109. }
  110. /// <summary>
  111. /// Get the state data as a byte array.
  112. /// </summary>
  113. /// <returns></returns>
  114. [Obsolete("Use `GetState` instead, this supports larger states (over 2GB)")]
  115. public byte[] GetStateData()
  116. {
  117. var stateSize = NativeApi.llama_get_state_size(_ctx);
  118. byte[] stateMemory = new byte[stateSize];
  119. NativeApi.llama_copy_state_data(_ctx, stateMemory);
  120. return stateMemory;
  121. }
  122. /// <summary>
  123. /// Get the state data as an opaque handle
  124. /// </summary>
  125. /// <returns></returns>
  126. public State GetState()
  127. {
  128. var stateSize = NativeApi.llama_get_state_size(_ctx);
  129. unsafe
  130. {
  131. var bigMemory = Marshal.AllocHGlobal((nint)stateSize);
  132. var smallMemory = IntPtr.Zero;
  133. try
  134. {
  135. // Copy the state data into "big memory", discover the actual size required
  136. var actualSize = NativeApi.llama_copy_state_data(_ctx, (byte*)bigMemory);
  137. // Allocate a smaller buffer
  138. smallMemory = Marshal.AllocHGlobal((nint)actualSize);
  139. // Copy into the smaller buffer and free the large one to save excess memory usage
  140. Buffer.MemoryCopy(bigMemory.ToPointer(), smallMemory.ToPointer(), actualSize, actualSize);
  141. Marshal.FreeHGlobal(bigMemory);
  142. bigMemory = IntPtr.Zero;
  143. return new State(smallMemory);
  144. }
  145. catch
  146. {
  147. if (bigMemory != IntPtr.Zero)
  148. Marshal.FreeHGlobal(bigMemory);
  149. if (smallMemory != IntPtr.Zero)
  150. Marshal.FreeHGlobal(smallMemory);
  151. throw;
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// Load the state from specified path.
  157. /// </summary>
  158. /// <param name="filename"></param>
  159. /// <exception cref="RuntimeError"></exception>
  160. public void LoadState(string filename)
  161. {
  162. // Map state file into memory and pass that pointer directly to `llama_set_state_data` to load from
  163. using (var file = MemoryMappedFile.CreateFromFile(filename, FileMode.Open, null))
  164. using (var view = file.CreateViewAccessor())
  165. {
  166. unsafe
  167. {
  168. byte* ptr = null;
  169. view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
  170. NativeApi.llama_set_state_data(_ctx, ptr);
  171. view.SafeMemoryMappedViewHandle.ReleasePointer();
  172. }
  173. }
  174. }
  175. /// <summary>
  176. /// Load the state from memory.
  177. /// </summary>
  178. /// <param name="stateData"></param>
  179. /// <exception cref="RuntimeError"></exception>
  180. public void LoadState(byte[] stateData)
  181. {
  182. int stateSize = (int)NativeApi.llama_get_state_size(_ctx);
  183. if (stateData.Length > stateSize)
  184. {
  185. throw new RuntimeError("Failed to validate state size.");
  186. }
  187. NativeApi.llama_set_state_data(_ctx, stateData);
  188. }
  189. /// <summary>
  190. /// Load the state from memory.
  191. /// </summary>
  192. /// <param name="state"></param>
  193. /// <exception cref="RuntimeError"></exception>
  194. public void LoadState(State state)
  195. {
  196. unsafe
  197. {
  198. NativeApi.llama_set_state_data(_ctx, (byte*)state.DangerousGetHandle().ToPointer());
  199. }
  200. }
  201. /// <summary>
  202. /// Perform the sampling. Please don't use it unless you fully know what it does.
  203. /// </summary>
  204. /// <param name="candidates"></param>
  205. /// <param name="temperature"></param>
  206. /// <param name="mirostat"></param>
  207. /// <param name="mirostatTau"></param>
  208. /// <param name="mirostatEta"></param>
  209. /// <param name="topK"></param>
  210. /// <param name="topP"></param>
  211. /// <param name="tfsZ"></param>
  212. /// <param name="typicalP"></param>
  213. /// <returns></returns>
  214. public llama_token Sample(LLamaTokenDataArray candidates, float temperature = 0.8f, MiroStateType mirostat = MiroStateType.Disable,
  215. float mirostatTau = 5.0f, float mirostatEta = 0.1f, int topK = 40, float topP = 0.95f, float tfsZ = 1.0f, float typicalP = 1.0f)
  216. {
  217. llama_token id = 0;
  218. if (temperature <= 0)
  219. {
  220. // Greedy sampling
  221. id = SamplingApi.llama_sample_token_greedy(_ctx, candidates);
  222. }
  223. else
  224. {
  225. if (mirostat == MiroStateType.MiroState)
  226. {
  227. float mirostat_mu = 2.0f * mirostatTau;
  228. const int mirostat_m = 100;
  229. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  230. id = SamplingApi.llama_sample_token_mirostat(_ctx, candidates, mirostatTau, mirostatEta, mirostat_m, ref mirostat_mu);
  231. }
  232. else if (mirostat == MiroStateType.MiroState2)
  233. {
  234. float mirostat_mu = 2.0f * mirostatTau;
  235. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  236. id = SamplingApi.llama_sample_token_mirostat_v2(_ctx, candidates, mirostatTau, mirostatEta, ref mirostat_mu);
  237. }
  238. else
  239. {
  240. // Temperature sampling
  241. SamplingApi.llama_sample_top_k(_ctx, candidates, topK, 1);
  242. SamplingApi.llama_sample_tail_free(_ctx, candidates, tfsZ, 1);
  243. SamplingApi.llama_sample_typical(_ctx, candidates, typicalP, 1);
  244. SamplingApi.llama_sample_top_p(_ctx, candidates, topP, 1);
  245. SamplingApi.llama_sample_temperature(_ctx, candidates, temperature);
  246. id = SamplingApi.llama_sample_token(_ctx, candidates);
  247. }
  248. }
  249. return id;
  250. }
  251. /// <summary>
  252. /// Apply the penalty for the tokens. Please don't use it unless you fully know what it does.
  253. /// </summary>
  254. /// <param name="lastTokens"></param>
  255. /// <param name="logitBias"></param>
  256. /// <param name="repeatLastTokensCount"></param>
  257. /// <param name="repeatPenalty"></param>
  258. /// <param name="alphaFrequency"></param>
  259. /// <param name="alphaPresence"></param>
  260. /// <param name="penalizeNL"></param>
  261. /// <returns></returns>
  262. public LLamaTokenDataArray ApplyPenalty(IEnumerable<llama_token> lastTokens, Dictionary<llama_token, float>? logitBias = null,
  263. int repeatLastTokensCount = 64, float repeatPenalty = 1.1f, float alphaFrequency = .0f, float alphaPresence = .0f,
  264. bool penalizeNL = true)
  265. {
  266. var n_vocab = NativeApi.llama_n_vocab(_ctx);
  267. var logits = Utils.GetLogits(_ctx, n_vocab);
  268. // Apply params.logit_bias map
  269. if(logitBias is not null)
  270. {
  271. foreach (var (key, value) in logitBias)
  272. {
  273. logits[key] += value;
  274. }
  275. }
  276. var candidates = new List<LLamaTokenData>();
  277. candidates.Capacity = n_vocab;
  278. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  279. {
  280. candidates.Add(new LLamaTokenData(token_id, logits[token_id], 0.0f));
  281. }
  282. LLamaTokenDataArray candidates_p = new LLamaTokenDataArray(candidates.ToArray(), (ulong)candidates.Count, false);
  283. // Apply penalties
  284. float nl_logit = logits[NativeApi.llama_token_nl()];
  285. int lastTokensCount = lastTokens.Count();
  286. var last_n_repeat = Math.Min(Math.Min(lastTokensCount, repeatLastTokensCount), ContextSize);
  287. SamplingApi.llama_sample_repetition_penalty(_ctx, candidates_p,
  288. lastTokens.Skip(lastTokensCount - last_n_repeat).ToArray(),
  289. (ulong)last_n_repeat, repeatPenalty);
  290. SamplingApi.llama_sample_frequency_and_presence_penalties(_ctx, candidates_p,
  291. lastTokens.Skip(lastTokensCount - last_n_repeat).ToArray(),
  292. (ulong)last_n_repeat, alphaFrequency, alphaPresence);
  293. if (!penalizeNL)
  294. {
  295. logits[NativeApi.llama_token_nl()] = nl_logit;
  296. }
  297. return candidates_p;
  298. }
  299. /// <summary>
  300. ///
  301. /// </summary>
  302. /// <param name="tokens"></param>
  303. /// <param name="pastTokensCount"></param>
  304. /// <returns>The updated `pastTokensCount`.</returns>
  305. /// <exception cref="RuntimeError"></exception>
  306. public llama_token Eval(llama_token[] tokens, llama_token pastTokensCount)
  307. {
  308. int total = tokens.Length;
  309. for(int i = 0; i < total; i += Params.BatchSize)
  310. {
  311. int n_eval = total - i;
  312. if(n_eval > Params.BatchSize)
  313. {
  314. n_eval = Params.BatchSize;
  315. }
  316. if(Utils.Eval(_ctx, tokens, i, n_eval, pastTokensCount, Params.Threads) != 0)
  317. {
  318. _logger?.Log(nameof(LLamaModel), "Failed to eval.", ILLamaLogger.LogLevel.Error);
  319. throw new RuntimeError("Failed to eval.");
  320. }
  321. pastTokensCount += n_eval;
  322. }
  323. return pastTokensCount;
  324. }
  325. // TODO: add comment
  326. internal IEnumerable<string> GenerateResult(IEnumerable<llama_token> ids)
  327. {
  328. foreach(var id in ids)
  329. {
  330. yield return Utils.TokenToString(id, _ctx, _encoding);
  331. }
  332. }
  333. /// <inheritdoc />
  334. public virtual void Dispose()
  335. {
  336. _ctx.Dispose();
  337. }
  338. /// <summary>
  339. /// The state of this model, which can be reloaded later
  340. /// </summary>
  341. public class State
  342. : SafeHandleZeroOrMinusOneIsInvalid
  343. {
  344. internal State(IntPtr memory)
  345. : base(true)
  346. {
  347. SetHandle(memory);
  348. }
  349. /// <inheritdoc />
  350. protected override bool ReleaseHandle()
  351. {
  352. Marshal.FreeHGlobal(handle);
  353. return true;
  354. }
  355. }
  356. }
  357. }