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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. using LLama.Exceptions;
  2. using LLama.Extensions;
  3. using LLama.Native;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using LLama.Common;
  11. namespace LLama.OldVersion
  12. {
  13. using llama_token = Int32;
  14. public class LLamaModel : IChatModel, IDisposable
  15. {
  16. LLamaParams _params;
  17. SafeLLamaContextHandle _ctx;
  18. string _path_session;
  19. List<llama_token> _session_tokens;
  20. List<llama_token> _embed_inp;
  21. int _n_ctx;
  22. List<llama_token> _inp_pfx;
  23. List<llama_token> _inp_sfx;
  24. List<llama_token> _llama_token_newline;
  25. List<llama_token> _last_n_tokens;
  26. bool _is_interacting;
  27. bool _is_antiprompt;
  28. bool _input_echo;
  29. bool _verbose;
  30. // HACK - because session saving incurs a non-negligible delay, for now skip re-saving session
  31. // if we loaded a session with at least 75% similarity. It's currently just used to speed up the
  32. // initial prompt so it doesn't need to be an exact match.
  33. bool _need_to_save_session;
  34. int _n_past;
  35. int _n_remain;
  36. int _n_consumed;
  37. int _n_session_consumed;
  38. List<llama_token> _embed;
  39. public string Name { get; set; }
  40. public bool Verbose
  41. {
  42. get
  43. {
  44. return _verbose;
  45. }
  46. set
  47. {
  48. _verbose = value;
  49. }
  50. }
  51. public SafeLLamaContextHandle NativeHandle => _ctx;
  52. /// <summary>
  53. /// Please refer `LLamaParams` to find the meanings of each arg. Be sure to have set the `n_gpu_layers`, otherwise it will
  54. /// load 20 layers to gpu by default.
  55. /// </summary>
  56. /// <param name="model_path">The model file path.</param>
  57. /// <param name="model_name">The model name.</param>
  58. /// <param name="verbose">Whether to print details when running the model.</param>
  59. /// <param name="seed"></param>
  60. /// <param name="n_threads"></param>
  61. /// <param name="n_predict"></param>
  62. /// <param name="n_ctx"></param>
  63. /// <param name="n_batch"></param>
  64. /// <param name="n_keep"></param>
  65. /// <param name="n_gpu_layers"></param>
  66. /// <param name="logit_bias"></param>
  67. /// <param name="top_k"></param>
  68. /// <param name="top_p"></param>
  69. /// <param name="tfs_z"></param>
  70. /// <param name="typical_p"></param>
  71. /// <param name="temp"></param>
  72. /// <param name="repeat_penalty"></param>
  73. /// <param name="repeat_last_n"></param>
  74. /// <param name="frequency_penalty"></param>
  75. /// <param name="presence_penalty"></param>
  76. /// <param name="mirostat"></param>
  77. /// <param name="mirostat_tau"></param>
  78. /// <param name="mirostat_eta"></param>
  79. /// <param name="prompt"></param>
  80. /// <param name="path_session"></param>
  81. /// <param name="input_prefix"></param>
  82. /// <param name="input_suffix"></param>
  83. /// <param name="antiprompt"></param>
  84. /// <param name="lora_adapter"></param>
  85. /// <param name="lora_base"></param>
  86. /// <param name="memory_f16"></param>
  87. /// <param name="random_prompt"></param>
  88. /// <param name="use_color"></param>
  89. /// <param name="interactive"></param>
  90. /// <param name="embedding"></param>
  91. /// <param name="interactive_first"></param>
  92. /// <param name="prompt_cache_all"></param>
  93. /// <param name="instruct"></param>
  94. /// <param name="penalize_nl"></param>
  95. /// <param name="perplexity"></param>
  96. /// <param name="use_mmap"></param>
  97. /// <param name="use_mlock"></param>
  98. /// <param name="mem_test"></param>
  99. /// <param name="verbose_prompt"></param>
  100. /// <param name="encoding"></param>
  101. public LLamaModel(string model_path, string model_name, bool verbose = false, int seed = 0, int n_threads = -1, int n_predict = -1,
  102. int n_ctx = 512, int n_batch = 512, int n_keep = 0, int n_gpu_layers = -1,
  103. Dictionary<llama_token, float> logit_bias = null, int top_k = 40, float top_p = 0.95f,
  104. float tfs_z = 1.00f, float typical_p = 1.00f, float temp = 0.80f, float repeat_penalty = 1.10f,
  105. int repeat_last_n = 64, float frequency_penalty = 0.00f, float presence_penalty = 0.00f,
  106. int mirostat = 0, float mirostat_tau = 5.00f, float mirostat_eta = 0.10f, string prompt = "",
  107. string path_session = "", string input_prefix = "", string input_suffix = "",
  108. List<string> antiprompt = null, string lora_adapter = "", string lora_base = "",
  109. bool memory_f16 = true, bool random_prompt = false, bool use_color = false, bool interactive = false,
  110. bool embedding = false, bool interactive_first = false, bool prompt_cache_all = false, bool instruct = false, bool penalize_nl = true,
  111. bool perplexity = false, bool use_mmap = true, bool use_mlock = false, bool mem_test = false,
  112. bool verbose_prompt = false, string encoding = "UTF-8") : this(new LLamaParams(seed: seed,
  113. n_threads: n_threads,
  114. n_predict: n_predict,
  115. n_ctx: n_ctx,
  116. n_batch: n_batch,
  117. n_keep: n_keep,
  118. n_gpu_layers: n_gpu_layers,
  119. logit_bias: logit_bias,
  120. top_k: top_k,
  121. top_p: top_p,
  122. tfs_z: tfs_z,
  123. typical_p: typical_p,
  124. temp: temp,
  125. repeat_penalty: repeat_penalty,
  126. repeat_last_n: repeat_last_n,
  127. frequency_penalty: frequency_penalty,
  128. presence_penalty: presence_penalty,
  129. mirostat: mirostat,
  130. mirostat_tau: mirostat_tau,
  131. mirostat_eta: mirostat_eta,
  132. model: model_path,
  133. prompt: prompt,
  134. path_session: path_session,
  135. input_prefix: input_prefix,
  136. input_suffix: input_suffix,
  137. antiprompt: antiprompt,
  138. lora_adapter: lora_adapter,
  139. lora_base: lora_base,
  140. memory_f16: memory_f16,
  141. random_prompt: random_prompt,
  142. use_color: use_color,
  143. interactive: interactive,
  144. embedding: embedding,
  145. interactive_first: interactive_first,
  146. prompt_cache_all: prompt_cache_all,
  147. instruct: instruct,
  148. penalize_nl: penalize_nl,
  149. perplexity: perplexity,
  150. use_mmap: use_mmap,
  151. use_mlock: use_mlock,
  152. mem_test: mem_test,
  153. verbose_prompt: verbose_prompt),
  154. model_name, verbose, encoding)
  155. {
  156. }
  157. /// <summary>
  158. /// Please refer `LLamaParams` to find the meanings of each arg. Be sure to have set the `n_gpu_layers`, otherwise it will
  159. /// load 20 layers to gpu by default.
  160. /// </summary>
  161. /// <param name="params">The LLamaModel params</param>
  162. /// <param name="name">Model name</param>
  163. /// <param name="verbose">Whether to output the detailed info.</param>
  164. /// <param name="encoding"></param>
  165. /// <exception cref="RuntimeError"></exception>
  166. public unsafe LLamaModel(LLamaParams @params, string name = "", bool verbose = false, string encoding = "UTF-8")
  167. {
  168. Name = name;
  169. _params = @params;
  170. _verbose = verbose;
  171. _ctx = Utils.llama_init_from_gpt_params(ref _params);
  172. // Add a space in front of the first character to match OG llama tokenizer behavior
  173. _session_tokens = new List<llama_token>();
  174. _path_session = @params.path_session;
  175. if (!string.IsNullOrEmpty(_path_session))
  176. {
  177. if (verbose)
  178. {
  179. LLamaDefaultLogger.Default.Info($"Attempting to load saved session from '{_path_session}'");
  180. }
  181. if (!File.Exists(_path_session))
  182. {
  183. LLamaDefaultLogger.Default.Warn("Session file does not exist, will create.");
  184. }
  185. llama_token[] session_tokens = new llama_token[@params.n_ctx];
  186. ulong n_token_count_out = 0;
  187. if (!NativeApi.llama_load_session_file(_ctx, _path_session, session_tokens, (ulong)@params.n_ctx, &n_token_count_out))
  188. {
  189. throw new RuntimeError($"Failed to load session file {_path_session}");
  190. }
  191. _session_tokens = session_tokens.Take((int)n_token_count_out).ToList();
  192. if (verbose)
  193. {
  194. LLamaDefaultLogger.Default.Info($"Loaded a session with prompt size of {_session_tokens.Count} tokens");
  195. }
  196. }
  197. _n_ctx = NativeApi.llama_n_ctx(_ctx);
  198. WithPrompt(_params.prompt);
  199. // prefix & suffix for instruct mode
  200. _inp_pfx = Utils.llama_tokenize(_ctx, "\n\n### Instruction:\n\n", true, encoding);
  201. _inp_sfx = Utils.llama_tokenize(_ctx, "\n\n### Response:\n\n", false, encoding);
  202. // in instruct mode, we inject a prefix and a suffix to each input by the user
  203. if (_params.instruct)
  204. {
  205. _params.interactive_first = true;
  206. _params.antiprompt.Add("### Instruction:\n\n");
  207. }
  208. // enable interactive mode if reverse prompt or interactive start is specified
  209. if (_params.interactive_first)
  210. {
  211. _params.interactive = true;
  212. }
  213. // determine newline token
  214. _llama_token_newline = Utils.llama_tokenize(_ctx, "\n", false, encoding);
  215. if (_params.verbose_prompt)
  216. {
  217. LLamaDefaultLogger.Default.Info("\n");
  218. LLamaDefaultLogger.Default.Info($"prompt: '{_params.prompt}'");
  219. LLamaDefaultLogger.Default.Info($"number of tokens in prompt = {_embed_inp.Count}");
  220. for (int i = 0; i < _embed_inp.Count; i++)
  221. {
  222. LLamaDefaultLogger.Default.Info($"{_embed_inp[i]} -> '{NativeApi.llama_token_to_str(_ctx, _embed_inp[i])}'");
  223. }
  224. if (_params.n_keep > 0)
  225. {
  226. LLamaDefaultLogger.Default.Info($"static prompt based on n_keep: '");
  227. for (int i = 0; i < _params.n_keep; i++)
  228. {
  229. LLamaDefaultLogger.Default.Info($"{NativeApi.llama_token_to_str(_ctx, _embed_inp[i])}");
  230. }
  231. LLamaDefaultLogger.Default.Info("\n");
  232. }
  233. LLamaDefaultLogger.Default.Info("\n");
  234. }
  235. if (_params.interactive && verbose)
  236. {
  237. LLamaDefaultLogger.Default.Info("interactive mode on.");
  238. }
  239. if (verbose)
  240. {
  241. LLamaDefaultLogger.Default.Info($"sampling: repeat_last_n = {_params.repeat_last_n}, " +
  242. $"repeat_penalty = {_params.repeat_penalty}, presence_penalty = {_params.presence_penalty}, " +
  243. $"frequency_penalty = {_params.frequency_penalty}, top_k = {_params.top_k}, tfs_z = {_params.tfs_z}," +
  244. $" top_p = {_params.top_p}, typical_p = {_params.typical_p}, temp = {_params.temp}, mirostat = {_params.mirostat}," +
  245. $" mirostat_lr = {_params.mirostat_eta}, mirostat_ent = {_params.mirostat_tau}");
  246. LLamaDefaultLogger.Default.Info($"generate: n_ctx = {_n_ctx}, n_batch = {_params.n_batch}, n_predict = {_params.n_predict}, " +
  247. $"n_keep = {_params.n_keep}");
  248. LLamaDefaultLogger.Default.Info("\n");
  249. }
  250. _last_n_tokens = Enumerable.Repeat(0, _n_ctx).ToList();
  251. if (_params.interactive)
  252. {
  253. if (verbose)
  254. {
  255. LLamaDefaultLogger.Default.Info("== Running in interactive mode. ==");
  256. }
  257. _is_interacting = _params.interactive_first;
  258. }
  259. _is_antiprompt = false;
  260. _input_echo = false;
  261. _n_past = 0;
  262. _n_remain = _params.n_predict;
  263. _n_consumed = 0;
  264. _n_session_consumed = 0;
  265. _embed = new List<llama_token>();
  266. }
  267. /// <summary>
  268. /// Apply a prompt to the model.
  269. /// </summary>
  270. /// <param name="prompt"></param>
  271. /// <param name="encoding"></param>
  272. /// <returns></returns>
  273. /// <exception cref="ArgumentException"></exception>
  274. public LLamaModel WithPrompt(string prompt, string encoding = "UTF-8")
  275. {
  276. _params.prompt = prompt.Insert(0, " ");
  277. _embed_inp = Utils.llama_tokenize(_ctx, _params.prompt, true, encoding);
  278. if (_embed_inp.Count > _n_ctx - 4)
  279. {
  280. throw new ArgumentException($"prompt is too long ({_embed_inp.Count} tokens, max {_n_ctx - 4})");
  281. }
  282. ulong n_matching_session_tokens = 0;
  283. if (_session_tokens.Count > 0)
  284. {
  285. foreach (var id in _session_tokens)
  286. {
  287. if (n_matching_session_tokens >= (ulong)_embed_inp.Count || id != _embed_inp[(int)n_matching_session_tokens])
  288. {
  289. break;
  290. }
  291. n_matching_session_tokens++;
  292. }
  293. if (n_matching_session_tokens >= (ulong)_embed_inp.Count)
  294. {
  295. LLamaDefaultLogger.Default.Info("Session file has exact match for prompt!");
  296. }
  297. else if (n_matching_session_tokens < (ulong)(_embed_inp.Count / 2))
  298. {
  299. LLamaDefaultLogger.Default.Warn($"session file has low similarity to prompt ({n_matching_session_tokens} " +
  300. $"/ {_embed_inp.Count} tokens); will mostly be reevaluated.");
  301. }
  302. else
  303. {
  304. LLamaDefaultLogger.Default.Info($"Session file matches {n_matching_session_tokens} / {_embed_inp.Count} " +
  305. $"tokens of prompt.");
  306. }
  307. }
  308. // number of tokens to keep when resetting context
  309. if (_params.n_keep < 0 || _params.n_keep > _embed_inp.Count || _params.instruct)
  310. {
  311. _params.n_keep = _embed_inp.Count;
  312. }
  313. if (_embed_inp.Count > _n_ctx - 4)
  314. {
  315. throw new ArgumentException($"prompt is too long ({_embed_inp.Count} tokens, max {_n_ctx - 4})");
  316. }
  317. _need_to_save_session = !string.IsNullOrEmpty(_path_session) && n_matching_session_tokens < (ulong)(_embed_inp.Count * 3 / 4);
  318. return this;
  319. }
  320. /// <summary>
  321. /// Apply the prompt file to the model.
  322. /// </summary>
  323. /// <param name="promptFileName"></param>
  324. /// <returns></returns>
  325. public LLamaModel WithPromptFile(string promptFileName)
  326. {
  327. return WithPrompt(File.ReadAllText(promptFileName));
  328. }
  329. private void ProcessTextBeforeInfer(string text, string encoding)
  330. {
  331. if (!string.IsNullOrEmpty(_params.input_prefix))
  332. {
  333. text = _params.input_prefix + text;
  334. }
  335. //if (!text.EndsWith("\n"))
  336. //{
  337. // text += "\n";
  338. //}
  339. if (text.Length > 1)
  340. {
  341. // append input suffix if any
  342. if (!string.IsNullOrEmpty(_params.input_suffix))
  343. {
  344. text += _params.input_suffix;
  345. //yield return _params.input_suffix;
  346. }
  347. // instruct mode: insert instruction prefix
  348. if (_params.instruct && !_is_antiprompt)
  349. {
  350. _n_consumed = _embed_inp.Count;
  351. _embed_inp.AddRange(_inp_pfx);
  352. }
  353. var line_inp = Utils.llama_tokenize(_ctx, text, false, encoding);
  354. _embed_inp.AddRange(line_inp);
  355. // instruct mode: insert response suffix
  356. if (_params.instruct)
  357. {
  358. _embed_inp.AddRange(_inp_sfx);
  359. }
  360. _n_remain -= line_inp.Count;
  361. }
  362. }
  363. public void InitChatPrompt(string prompt, string encoding = "UTF-8")
  364. {
  365. WithPrompt(prompt);
  366. }
  367. public void InitChatAntiprompt(string[] antiprompt)
  368. {
  369. _params.antiprompt = antiprompt.ToList();
  370. }
  371. /// <summary>
  372. /// Chat with the LLaMa model under interactive mode.
  373. /// </summary>
  374. /// <param name="text"></param>
  375. /// <param name="prompt"></param>
  376. /// <param name="encoding"></param>
  377. /// <returns></returns>
  378. /// <exception cref="ArgumentException"></exception>
  379. public IEnumerable<string> Chat(string text, string? prompt = null, string encoding = "UTF-8")
  380. {
  381. if (!_params.interactive)
  382. {
  383. throw new ArgumentException("The chat API could be only used under interactive model.");
  384. }
  385. _input_echo = false;
  386. if (!string.IsNullOrEmpty(prompt))
  387. {
  388. WithPrompt(prompt);
  389. }
  390. return Call(text, encoding);
  391. }
  392. /// <summary>
  393. /// Save the state to specified path.
  394. /// </summary>
  395. /// <param name="filename"></param>
  396. public void SaveState(string filename)
  397. {
  398. var stateSize = NativeApi.llama_get_state_size(_ctx);
  399. byte[] stateMemory = new byte[stateSize];
  400. NativeApi.llama_copy_state_data(_ctx, stateMemory);
  401. File.WriteAllBytes(filename, stateMemory);
  402. }
  403. /// <summary>
  404. /// Load the state from specified path.
  405. /// </summary>
  406. /// <param name="filename"></param>
  407. /// <param name="clearPreviousEmbed">Whether to clear previous footprints of this model.</param>
  408. /// <exception cref="RuntimeError"></exception>
  409. public void LoadState(string filename, bool clearPreviousEmbed = true)
  410. {
  411. var stateMemory = File.ReadAllBytes(filename);
  412. int stateSize = (int)NativeApi.llama_get_state_size(_ctx);
  413. if (stateMemory.Length != stateSize)
  414. {
  415. throw new RuntimeError("Failed to validate state size.");
  416. }
  417. NativeApi.llama_set_state_data(_ctx, stateMemory);
  418. if (clearPreviousEmbed)
  419. {
  420. WithPrompt(_params.prompt);
  421. }
  422. }
  423. /// <summary>
  424. /// Tokenize a string.
  425. /// </summary>
  426. /// <param name="text">The utf-8 encoded string to tokenize.</param>
  427. /// <returns>A list of tokens.</returns>
  428. /// <exception cref="RuntimeError">If the tokenization failed.</exception>
  429. public List<llama_token> Tokenize(string text, string encoding = "UTF-8")
  430. {
  431. Debug.Assert(_ctx.DangerousGetHandle() != IntPtr.Zero);
  432. var n_ctx = NativeApi.llama_n_ctx(_ctx);
  433. var tokens = new llama_token[n_ctx];
  434. var n_tokens = NativeApi.llama_tokenize(_ctx, text, Encoding.GetEncoding(encoding), tokens, n_ctx, true);
  435. if (n_tokens < 0)
  436. {
  437. throw new RuntimeError($"Failed to tokenize: text=\"{text}\" n_tokens={n_tokens}");
  438. }
  439. return tokens.Take(n_tokens).ToList();
  440. }
  441. /// <summary>
  442. /// Detokenize a list of tokens.
  443. /// </summary>
  444. /// <param name="tokens">The list of tokens to detokenize.</param>
  445. /// <returns>The detokenized string.</returns>
  446. public string DeTokenize(IEnumerable<llama_token> tokens)
  447. {
  448. Debug.Assert(_ctx.DangerousGetHandle() != IntPtr.Zero);
  449. string output = "";
  450. foreach (var token in tokens)
  451. {
  452. output += Utils.PtrToStringUTF8(NativeApi.llama_token_to_str(_ctx, token));
  453. }
  454. return output;
  455. }
  456. /// <summary>
  457. /// Call the model to run inference.
  458. /// </summary>
  459. /// <param name="text"></param>
  460. /// <param name="encoding"></param>
  461. /// <returns></returns>
  462. /// <exception cref="RuntimeError"></exception>
  463. public IEnumerable<string> Call(string text, string encoding = "UTF-8")
  464. {
  465. _is_antiprompt = false;
  466. if (_n_past > 0)
  467. {
  468. _is_interacting = false;
  469. }
  470. if (_is_interacting)
  471. {
  472. if (_verbose)
  473. {
  474. LLamaDefaultLogger.Default.Warn("In interacting when calling the model, automatically changed it.");
  475. }
  476. _is_interacting = false;
  477. }
  478. ProcessTextBeforeInfer(text, encoding);
  479. while ((_n_remain != 0 || _params.interactive) && !_is_interacting)
  480. {
  481. if (_embed.Count > 0)
  482. {
  483. // infinite text generation via context swapping
  484. // if we run out of context:
  485. // - take the n_keep first tokens from the original prompt (via n_past)
  486. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  487. if (_n_past + _embed.Count > _n_ctx)
  488. {
  489. int n_left = _n_past - _params.n_keep;
  490. _n_past = Math.Max(1, _params.n_keep);
  491. // insert n_left/2 tokens at the start of embed from last_n_tokens
  492. _embed.InsertRange(0, _last_n_tokens.Take(_last_n_tokens.Count - _embed.Count).Skip(_n_ctx - n_left / 2 - _embed.Count));
  493. // stop saving session if we run out of context
  494. _path_session = "";
  495. }
  496. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  497. // REVIEW
  498. if (_n_session_consumed < _session_tokens.Count)
  499. {
  500. int i = 0;
  501. for (; i < _embed.Count; i++)
  502. {
  503. if (_embed[i] != _session_tokens[_n_session_consumed])
  504. {
  505. _session_tokens = _session_tokens.Take(_n_session_consumed).ToList();
  506. break;
  507. }
  508. _n_past++;
  509. _n_session_consumed++;
  510. if (_n_session_consumed >= _session_tokens.Count)
  511. {
  512. i++;
  513. break;
  514. }
  515. }
  516. if (i > 0)
  517. {
  518. _embed.RemoveRange(0, i);
  519. }
  520. }
  521. // evaluate tokens in batches
  522. // embed is typically prepared beforehand to fit within a batch, but not always
  523. for (int i = 0; i < _embed.Count; i += _params.n_batch)
  524. {
  525. int n_eval = _embed.Count - i;
  526. if (n_eval > _params.n_batch)
  527. {
  528. n_eval = _params.n_batch;
  529. }
  530. var array = _embed.Skip(i).ToArray();
  531. if (NativeApi.llama_eval(_ctx, array, n_eval, _n_past, _params.n_threads) != 0)
  532. {
  533. LLamaDefaultLogger.Default.Error($"Failed to eval.");
  534. throw new RuntimeError("Failed to eval.");
  535. }
  536. _n_past += n_eval;
  537. }
  538. if (_embed.Count > 0 && !string.IsNullOrEmpty(_path_session))
  539. {
  540. _session_tokens.AddRange(_embed);
  541. _n_session_consumed = _session_tokens.Count;
  542. }
  543. }
  544. _embed.Clear();
  545. if (_embed_inp.Count <= _n_consumed && !_is_interacting)
  546. {
  547. var temp = _params.temp;
  548. var top_k = _params.top_k <= 0 ? NativeApi.llama_n_vocab(_ctx) : _params.top_k;
  549. var top_p = _params.top_p;
  550. var tfs_z = _params.tfs_z;
  551. var typical_p = _params.typical_p;
  552. var repeat_last_n = _params.repeat_last_n < 0 ? _n_ctx : _params.repeat_last_n;
  553. var repeat_penalty = _params.repeat_penalty;
  554. var alpha_presence = _params.presence_penalty;
  555. var alpha_frequency = _params.frequency_penalty;
  556. var mirostat = _params.mirostat;
  557. var mirostat_tau = _params.mirostat_tau;
  558. var mirostat_eta = _params.mirostat_eta;
  559. var penalize_nl = _params.penalize_nl;
  560. // optionally save the session on first sample (for faster prompt loading next time)
  561. if (!string.IsNullOrEmpty(_path_session) && _need_to_save_session)
  562. {
  563. _need_to_save_session = false;
  564. NativeApi.llama_save_session_file(_ctx, _path_session, _session_tokens.ToArray(), (ulong)_session_tokens.Count);
  565. }
  566. llama_token id = 0;
  567. {
  568. var n_vocab = NativeApi.llama_n_vocab(_ctx);
  569. var logits = Utils.llama_get_logits(_ctx, n_vocab);
  570. // Apply params.logit_bias map
  571. foreach (var (key, value) in _params.logit_bias)
  572. {
  573. logits[key] += value;
  574. }
  575. var candidates = new LLamaTokenData[n_vocab];
  576. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  577. candidates[token_id] = new LLamaTokenData(token_id, logits[token_id], 0.0f);
  578. LLamaTokenDataArray candidates_p = new LLamaTokenDataArray(candidates);
  579. // Apply penalties
  580. float nl_logit = logits[NativeApi.llama_token_nl()];
  581. var last_n_repeat = Math.Min(Math.Min(_last_n_tokens.Count, repeat_last_n), _n_ctx);
  582. SamplingApi.llama_sample_repetition_penalty(_ctx, candidates_p,
  583. _last_n_tokens.Skip(_last_n_tokens.Count - last_n_repeat).ToArray(),
  584. (ulong)last_n_repeat, repeat_penalty);
  585. SamplingApi.llama_sample_frequency_and_presence_penalties(_ctx, candidates_p,
  586. _last_n_tokens.Skip(_last_n_tokens.Count - last_n_repeat).ToArray(),
  587. (ulong)last_n_repeat, alpha_frequency, alpha_presence);
  588. if (!penalize_nl)
  589. {
  590. logits[NativeApi.llama_token_nl()] = nl_logit;
  591. }
  592. if (temp <= 0)
  593. {
  594. // Greedy sampling
  595. id = SamplingApi.llama_sample_token_greedy(_ctx, candidates_p);
  596. }
  597. else
  598. {
  599. if (mirostat == 1)
  600. {
  601. float mirostat_mu = 2.0f * mirostat_tau;
  602. const int mirostat_m = 100;
  603. SamplingApi.llama_sample_temperature(_ctx, candidates_p, temp);
  604. id = SamplingApi.llama_sample_token_mirostat(_ctx, candidates_p, mirostat_tau, mirostat_eta, mirostat_m, ref mirostat_mu);
  605. }
  606. else if (mirostat == 2)
  607. {
  608. float mirostat_mu = 2.0f * mirostat_tau;
  609. SamplingApi.llama_sample_temperature(_ctx, candidates_p, temp);
  610. id = SamplingApi.llama_sample_token_mirostat_v2(_ctx, candidates_p, mirostat_tau, mirostat_eta, ref mirostat_mu);
  611. }
  612. else
  613. {
  614. // Temperature sampling
  615. SamplingApi.llama_sample_top_k(_ctx, candidates_p, top_k, 1);
  616. SamplingApi.llama_sample_tail_free(_ctx, candidates_p, tfs_z, 1);
  617. SamplingApi.llama_sample_typical(_ctx, candidates_p, typical_p, 1);
  618. SamplingApi.llama_sample_top_p(_ctx, candidates_p, top_p, 1);
  619. SamplingApi.llama_sample_temperature(_ctx, candidates_p, temp);
  620. id = SamplingApi.llama_sample_token(_ctx, candidates_p);
  621. }
  622. }
  623. _last_n_tokens.RemoveAt(0);
  624. _last_n_tokens.Add(id);
  625. }
  626. // replace end of text token with newline token when in interactive mode
  627. if (id == NativeApi.llama_token_eos() && _params.interactive && !_params.instruct)
  628. {
  629. id = _llama_token_newline[0];
  630. if (_params.antiprompt.Count != 0)
  631. {
  632. // tokenize and inject first reverse prompt
  633. var first_antiprompt = Utils.llama_tokenize(_ctx, _params.antiprompt[0], false, encoding);
  634. _embed_inp.AddRange(first_antiprompt);
  635. }
  636. }
  637. // add it to the context
  638. _embed.Add(id);
  639. // echo this to console
  640. _input_echo = true;
  641. // decrement remaining sampling budget
  642. _n_remain--;
  643. }
  644. else
  645. {
  646. while (_embed_inp.Count > _n_consumed)
  647. {
  648. _embed.Add(_embed_inp[_n_consumed]);
  649. _last_n_tokens.RemoveAt(0);
  650. _last_n_tokens.Add(_embed_inp[_n_consumed]);
  651. _n_consumed++;
  652. if (_embed.Count >= _params.n_batch)
  653. {
  654. break;
  655. }
  656. }
  657. }
  658. if (_input_echo && !_is_interacting)
  659. {
  660. foreach (var id in _embed)
  661. {
  662. var res = Utils.PtrToStringUTF8(NativeApi.llama_token_to_str(_ctx, id));
  663. yield return res;
  664. }
  665. }
  666. if (_params.interactive && _embed_inp.Count <= _n_consumed)
  667. {
  668. if (_params.antiprompt.Count > 0)
  669. {
  670. string last_output = "";
  671. foreach (var id in _last_n_tokens)
  672. {
  673. last_output += Utils.PtrToStringUTF8(NativeApi.llama_token_to_str(_ctx, id));
  674. }
  675. _is_antiprompt = false;
  676. foreach (var antiprompt in _params.antiprompt)
  677. {
  678. if (last_output.EndsWith(antiprompt))
  679. {
  680. _is_interacting = true;
  681. _is_antiprompt = true;
  682. break;
  683. }
  684. }
  685. }
  686. if (_n_past > 0 && _is_interacting)
  687. {
  688. if (_params.instruct)
  689. {
  690. yield return "\n> ";
  691. }
  692. _input_echo = false;
  693. break;
  694. }
  695. if (_embed.Count > 0 && _embed.Last() == NativeApi.llama_token_eos())
  696. {
  697. if (_params.instruct)
  698. {
  699. _is_interacting = true;
  700. }
  701. else
  702. {
  703. LLamaDefaultLogger.Default.Info(" [end of text]");
  704. }
  705. }
  706. if (_params.interactive && _n_remain <= 0 && _params.n_predict != -1)
  707. {
  708. _n_remain = _params.n_predict;
  709. _is_interacting = true;
  710. }
  711. }
  712. }
  713. if (!string.IsNullOrEmpty(_path_session) && _params.prompt_cache_all)
  714. {
  715. LLamaDefaultLogger.Default.Info($"saving final output to session file {_path_session}");
  716. var session_token_array = _session_tokens.ToArray();
  717. NativeApi.llama_save_session_file(_ctx, _path_session, session_token_array, (ulong)session_token_array.Length);
  718. }
  719. }
  720. /// <inheritdoc />
  721. public void Dispose()
  722. {
  723. _ctx.Dispose();
  724. }
  725. }
  726. }