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

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