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.

GptModel.cs 26 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. using LLama.Native;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. using LLama.Exceptions;
  7. using System.Linq;
  8. using System.Text.RegularExpressions;
  9. using System.Runtime.InteropServices;
  10. using System.Diagnostics;
  11. namespace LLama
  12. {
  13. using llama_token = Int32;
  14. public class LLamaModel: IChatModel
  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. // HACK - because session saving incurs a non-negligible delay, for now skip re-saving session
  30. // if we loaded a session with at least 75% similarity. It's currently just used to speed up the
  31. // initial prompt so it doesn't need to be an exact match.
  32. bool _need_to_save_session;
  33. int _n_past;
  34. int _n_remain;
  35. int _n_consumed;
  36. int _n_session_consumed;
  37. List<llama_token> _embed;
  38. // params related to chat API only
  39. bool _first_time_chat = true;
  40. public string Name { get; set; }
  41. public LLamaModel(string model_path, string model_name, bool echo_input = false, bool verbose = false, int seed = 0, int n_threads = -1, int n_predict = -1,
  42. int n_parts = -1, int n_ctx = 512, int n_batch = 512, int n_keep = 0,
  43. Dictionary<llama_token, float> logit_bias = null, int top_k = 40, float top_p = 0.95f,
  44. float tfs_z = 1.00f, float typical_p = 1.00f, float temp = 0.80f, float repeat_penalty = 1.10f,
  45. int repeat_last_n = 64, float frequency_penalty = 0.00f, float presence_penalty = 0.00f,
  46. int mirostat = 0, float mirostat_tau = 5.00f, float mirostat_eta = 0.10f, string prompt = "",
  47. string path_session = "", string input_prefix = "", string input_suffix = "",
  48. List<string> antiprompt = null, string lora_adapter = "", string lora_base = "",
  49. bool memory_f16 = true, bool random_prompt = false, bool use_color = false, bool interactive = false,
  50. bool embedding = false, bool interactive_first = false, bool instruct = false, bool penalize_nl = true,
  51. bool perplexity = false, bool use_mmap = true, bool use_mlock = false, bool mem_test = false,
  52. bool verbose_prompt = false) : this(new LLamaParams(seed, n_threads, n_predict, n_parts, n_ctx, n_batch,
  53. n_keep, logit_bias, top_k, top_p, tfs_z, typical_p, temp, repeat_penalty, repeat_last_n, frequency_penalty,
  54. presence_penalty, mirostat, mirostat_tau, mirostat_eta, model_path, prompt, path_session, input_prefix,
  55. input_suffix, antiprompt, lora_adapter, lora_base, memory_f16, random_prompt, use_color, interactive, embedding,
  56. interactive_first, instruct, penalize_nl, perplexity, use_mmap, use_mlock, mem_test, verbose_prompt), model_name, echo_input, verbose)
  57. {
  58. }
  59. public unsafe LLamaModel(LLamaParams @params, string name = "", bool echo_input = false, bool verbose = false)
  60. {
  61. Name = name;
  62. _params = @params;
  63. _ctx = Utils.llama_init_from_gpt_params(ref _params);
  64. // Add a space in front of the first character to match OG llama tokenizer behavior
  65. _params.prompt.Insert(0, " ");
  66. _session_tokens = new List<llama_token>();
  67. _path_session = @params.path_session;
  68. if (!string.IsNullOrEmpty(_path_session))
  69. {
  70. if (verbose)
  71. {
  72. Logger.Default.Info($"Attempting to load saved session from '{_path_session}'");
  73. }
  74. if (!File.Exists(_path_session))
  75. {
  76. Logger.Default.Warn("Session file does not exist, will create.");
  77. }
  78. llama_token[] session_tokens = new llama_token[@params.n_ctx];
  79. ulong n_token_count_out = 0;
  80. if (!NativeApi.llama_load_session_file(_ctx, _path_session, session_tokens, (ulong)@params.n_ctx, &n_token_count_out))
  81. {
  82. throw new RuntimeError($"Failed to load session file {_path_session}");
  83. }
  84. _session_tokens = session_tokens.Take((int)n_token_count_out).ToList();
  85. if (verbose)
  86. {
  87. Logger.Default.Info($"Loaded a session with prompt size of {_session_tokens.Count} tokens");
  88. }
  89. }
  90. _embed_inp = Utils.llama_tokenize(_ctx, _params.prompt, true);
  91. _n_ctx = NativeApi.llama_n_ctx(_ctx);
  92. if (_embed_inp.Count > _n_ctx - 4)
  93. {
  94. throw new ArgumentException($"prompt is too long ({_embed_inp.Count} tokens, max {_n_ctx - 4})");
  95. }
  96. ulong n_matching_session_tokens = 0;
  97. if (_session_tokens.Count > 0)
  98. {
  99. foreach (var id in _session_tokens)
  100. {
  101. if (n_matching_session_tokens >= (ulong)_embed_inp.Count || id != _embed_inp[(int)n_matching_session_tokens])
  102. {
  103. break;
  104. }
  105. n_matching_session_tokens++;
  106. }
  107. if (n_matching_session_tokens >= (ulong)_embed_inp.Count && verbose)
  108. {
  109. Logger.Default.Info("Session file has exact match for prompt!");
  110. }
  111. else if (n_matching_session_tokens < (ulong)(_embed_inp.Count / 2))
  112. {
  113. Logger.Default.Warn($"session file has low similarity to prompt ({n_matching_session_tokens} " +
  114. $"/ {_embed_inp.Count} tokens); will mostly be reevaluated.");
  115. }
  116. else if(verbose)
  117. {
  118. Logger.Default.Info($"Session file matches {n_matching_session_tokens} / {_embed_inp.Count} " +
  119. $"tokens of prompt.");
  120. }
  121. }
  122. // number of tokens to keep when resetting context
  123. if (_params.n_keep < 0 || _params.n_keep > (int)_embed_inp.Count || _params.instruct)
  124. {
  125. _params.n_keep = _embed_inp.Count;
  126. }
  127. // prefix & suffix for instruct mode
  128. _inp_pfx = Utils.llama_tokenize(_ctx, "\n\n### Instruction:\n\n", true);
  129. _inp_sfx = Utils.llama_tokenize(_ctx, "\n\n### Response:\n\n", false);
  130. // in instruct mode, we inject a prefix and a suffix to each input by the user
  131. if (_params.instruct)
  132. {
  133. _params.interactive_first = true;
  134. _params.antiprompt.Add("### Instruction:\n\n");
  135. }
  136. // enable interactive mode if reverse prompt or interactive start is specified
  137. if (_params.antiprompt.Count != 0 || _params.interactive_first)
  138. {
  139. _params.interactive = true;
  140. }
  141. // determine newline token
  142. _llama_token_newline = Utils.llama_tokenize(_ctx, "\n", false);
  143. if (_params.verbose_prompt)
  144. {
  145. Logger.Default.Info("\n");
  146. Logger.Default.Info($"prompt: '{_params.prompt}'");
  147. Logger.Default.Info($"number of tokens in prompt = {_embed_inp.Count}");
  148. for (int i = 0; i < _embed_inp.Count; i++)
  149. {
  150. Logger.Default.Info($"{_embed_inp[i]} -> '{NativeApi.llama_token_to_str(_ctx, _embed_inp[i])}'");
  151. }
  152. if (_params.n_keep > 0)
  153. {
  154. Logger.Default.Info($"static prompt based on n_keep: '");
  155. for (int i = 0; i < _params.n_keep; i++)
  156. {
  157. Logger.Default.Info($"{NativeApi.llama_token_to_str(_ctx, _embed_inp[i])}");
  158. }
  159. Logger.Default.Info("\n");
  160. }
  161. Logger.Default.Info("\n");
  162. }
  163. if (_params.interactive && verbose)
  164. {
  165. Logger.Default.Info("interactive mode on.");
  166. }
  167. if (verbose)
  168. {
  169. Logger.Default.Info($"sampling: repeat_last_n = {_params.repeat_last_n}, " +
  170. $"repeat_penalty = {_params.repeat_penalty}, presence_penalty = {_params.presence_penalty}, " +
  171. $"frequency_penalty = {_params.frequency_penalty}, top_k = {_params.top_k}, tfs_z = {_params.tfs_z}," +
  172. $" top_p = {_params.top_p}, typical_p = {_params.typical_p}, temp = {_params.temp}, mirostat = {_params.mirostat}," +
  173. $" mirostat_lr = {_params.mirostat_eta}, mirostat_ent = {_params.mirostat_tau}");
  174. Logger.Default.Info($"generate: n_ctx = {_n_ctx}, n_batch = {_params.n_batch}, n_predict = {_params.n_predict}, " +
  175. $"n_keep = {_params.n_keep}");
  176. Logger.Default.Info("\n");
  177. }
  178. _last_n_tokens = Enumerable.Repeat(0, _n_ctx).ToList();
  179. if (_params.interactive)
  180. {
  181. if (verbose)
  182. {
  183. Logger.Default.Info("== Running in interactive mode. ==");
  184. }
  185. _is_interacting = _params.interactive_first;
  186. }
  187. _is_antiprompt = false;
  188. _input_echo = echo_input;
  189. _need_to_save_session = !string.IsNullOrEmpty(_path_session) && n_matching_session_tokens < (ulong)(_embed_inp.Count * 3 / 4);
  190. _n_past = 0;
  191. _n_remain = _params.n_predict;
  192. _n_consumed = 0;
  193. _n_session_consumed = 0;
  194. _embed = new List<llama_token>();
  195. }
  196. public LLamaModel WithPrompt(string prompt)
  197. {
  198. _params.prompt = prompt;
  199. if (!_params.prompt.EndsWith(" "))
  200. {
  201. _params.prompt.Insert(0, " ");
  202. }
  203. _embed_inp = Utils.llama_tokenize(_ctx, _params.prompt, true);
  204. if (_embed_inp.Count > _n_ctx - 4)
  205. {
  206. throw new ArgumentException($"prompt is too long ({_embed_inp.Count} tokens, max {_n_ctx - 4})");
  207. }
  208. return this;
  209. }
  210. public LLamaModel WithPromptFile(string promptFileName)
  211. {
  212. return WithPrompt(File.ReadAllText(promptFileName));
  213. }
  214. private string ProcessTextBeforeInfer(string text)
  215. {
  216. if (!string.IsNullOrEmpty(_params.input_prefix))
  217. {
  218. text = _params.input_prefix + text;
  219. }
  220. if (!text.EndsWith("\n"))
  221. {
  222. text += "\n";
  223. }
  224. if (text.Length > 1)
  225. {
  226. // append input suffix if any
  227. if (!string.IsNullOrEmpty(_params.input_suffix))
  228. {
  229. text += _params.input_suffix;
  230. Console.Write(_params.input_suffix);
  231. }
  232. // instruct mode: insert instruction prefix
  233. if (_params.instruct && !_is_antiprompt)
  234. {
  235. _n_consumed = _embed_inp.Count;
  236. _embed_inp.AddRange(_inp_pfx);
  237. }
  238. var line_inp = Utils.llama_tokenize(_ctx, text, false);
  239. _embed_inp.AddRange(line_inp);
  240. // instruct mode: insert response suffix
  241. if (_params.instruct)
  242. {
  243. _embed_inp.AddRange(_inp_sfx);
  244. }
  245. _n_remain -= line_inp.Count;
  246. }
  247. return text;
  248. }
  249. public void InitChatPrompt(string prompt)
  250. {
  251. WithPrompt(prompt);
  252. }
  253. public void InitChatAntiprompt(string[] antiprompt)
  254. {
  255. _params.antiprompt = antiprompt.ToList();
  256. }
  257. public IEnumerable<string> Chat(string text, string? prompt = null)
  258. {
  259. _params.interactive = true;
  260. _input_echo = false;
  261. if (!string.IsNullOrEmpty(prompt))
  262. {
  263. WithPrompt(prompt);
  264. }
  265. return Call(text);
  266. }
  267. public IEnumerable<string> Call(string text)
  268. {
  269. _is_interacting = _is_antiprompt = false;
  270. ProcessTextBeforeInfer(text);
  271. while ((_n_remain != 0 || _params.interactive) && !_is_interacting)
  272. {
  273. if (_embed.Count > 0)
  274. {
  275. // infinite text generation via context swapping
  276. // if we run out of context:
  277. // - take the n_keep first tokens from the original prompt (via n_past)
  278. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  279. if (_n_past + _embed.Count > _n_ctx)
  280. {
  281. int n_left = _n_past - _params.n_keep;
  282. _n_past = _params.n_keep;
  283. // insert n_left/2 tokens at the start of embed from last_n_tokens
  284. _embed.InsertRange(0, _last_n_tokens.GetRange(_n_ctx - n_left / 2 - _embed.Count, _embed.Count));
  285. // stop saving session if we run out of context
  286. _path_session = "";
  287. // Console.WriteLine("\n---\n");
  288. // Console.Write("resetting: '");
  289. // for (int i = 0; i < embed.Count; i++) {
  290. // Console.Write(llama_token_to_str(ctx, embed[i]));
  291. // }
  292. // Console.WriteLine("'\n");
  293. // Console.WriteLine("\n---\n");
  294. }
  295. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  296. // REVIEW
  297. if (_n_session_consumed < _session_tokens.Count)
  298. {
  299. int i = 0;
  300. for (; i < _embed.Count; i++)
  301. {
  302. if (!_embed[i].Equals(_session_tokens[_n_session_consumed]))
  303. {
  304. _session_tokens.RemoveRange(_n_session_consumed, _session_tokens.Count - _n_session_consumed);
  305. break;
  306. }
  307. _n_past++;
  308. _n_session_consumed++;
  309. if (_n_session_consumed >= _session_tokens.Count)
  310. {
  311. i++;
  312. break;
  313. }
  314. }
  315. if (i > 0)
  316. {
  317. _embed.RemoveRange(0, i);
  318. }
  319. }
  320. // evaluate tokens in batches
  321. // embed is typically prepared beforehand to fit within a batch, but not always
  322. for (int i = 0; i < _embed.Count; i += _params.n_batch)
  323. {
  324. int n_eval = _embed.Count - i;
  325. if (n_eval > _params.n_batch)
  326. {
  327. n_eval = _params.n_batch;
  328. }
  329. var array = _embed.GetRange(i, n_eval).ToArray();
  330. if (NativeApi.llama_eval(_ctx, array, n_eval, _n_past, _params.n_threads) != 0)
  331. {
  332. Logger.Default.Error($"Failed to eval");
  333. throw new RuntimeError("Failed to eval");
  334. }
  335. _n_past += n_eval;
  336. }
  337. if (_embed.Count > 0 && !string.IsNullOrEmpty(_path_session))
  338. {
  339. _session_tokens.AddRange(_embed);
  340. _n_session_consumed = _session_tokens.Count;
  341. }
  342. }
  343. _embed.Clear();
  344. if (_embed_inp.Count <= _n_consumed && !_is_interacting)
  345. {
  346. var temp = _params.temp;
  347. var top_k = _params.top_k <= 0 ? NativeApi.llama_n_vocab(_ctx) : _params.top_k;
  348. var top_p = _params.top_p;
  349. var tfs_z = _params.tfs_z;
  350. var typical_p = _params.typical_p;
  351. var repeat_last_n = _params.repeat_last_n < 0 ? _n_ctx : _params.repeat_last_n;
  352. var repeat_penalty = _params.repeat_penalty;
  353. var alpha_presence = _params.presence_penalty;
  354. var alpha_frequency = _params.frequency_penalty;
  355. var mirostat = _params.mirostat;
  356. var mirostat_tau = _params.mirostat_tau;
  357. var mirostat_eta = _params.mirostat_eta;
  358. var penalize_nl = _params.penalize_nl;
  359. // optionally save the session on first sample (for faster prompt loading next time)
  360. if (!string.IsNullOrEmpty(_path_session) && _need_to_save_session)
  361. {
  362. _need_to_save_session = false;
  363. NativeApi.llama_save_session_file(_ctx, _path_session, _session_tokens.ToArray(), (ulong)_session_tokens.Count);
  364. }
  365. llama_token id = 0;
  366. {
  367. var n_vocab = NativeApi.llama_n_vocab(_ctx);
  368. var logits = Utils.llama_get_logits(_ctx, n_vocab);
  369. // Apply params.logit_bias map
  370. foreach (KeyValuePair<int, float> it in _params.logit_bias)
  371. {
  372. logits[it.Key] += it.Value;
  373. }
  374. var candidates = new List<LLamaTokenData>();
  375. candidates.Capacity = n_vocab;
  376. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  377. {
  378. candidates.Add(new LLamaTokenData(token_id, logits[token_id], 0.0f));
  379. }
  380. LLamaTokenDataArray candidates_p = new LLamaTokenDataArray(candidates.ToArray(), (ulong)candidates.Count, false);
  381. // Apply penalties
  382. float nl_logit = logits[NativeApi.llama_token_nl()];
  383. var last_n_repeat = Math.Min(Math.Min(_last_n_tokens.Count, repeat_last_n), _n_ctx);
  384. SamplingApi.llama_sample_repetition_penalty(_ctx, candidates_p,
  385. _last_n_tokens.GetRange(_last_n_tokens.Count - last_n_repeat, last_n_repeat).ToArray(),
  386. (ulong)last_n_repeat, repeat_penalty);
  387. SamplingApi.llama_sample_frequency_and_presence_penalties(_ctx, candidates_p,
  388. _last_n_tokens.GetRange(_last_n_tokens.Count - last_n_repeat, last_n_repeat).ToArray(),
  389. (ulong)last_n_repeat, alpha_frequency, alpha_presence);
  390. if (!penalize_nl)
  391. {
  392. logits[NativeApi.llama_token_nl()] = nl_logit;
  393. }
  394. if (temp <= 0)
  395. {
  396. // Greedy sampling
  397. id = SamplingApi.llama_sample_token_greedy(_ctx, candidates_p);
  398. }
  399. else
  400. {
  401. if (mirostat == 1)
  402. {
  403. float mirostat_mu = 2.0f * mirostat_tau;
  404. const int mirostat_m = 100;
  405. SamplingApi.llama_sample_temperature(_ctx, candidates_p, temp);
  406. id = SamplingApi.llama_sample_token_mirostat(_ctx, candidates_p, mirostat_tau, mirostat_eta, mirostat_m, mirostat_mu);
  407. }
  408. else if (mirostat == 2)
  409. {
  410. float mirostat_mu = 2.0f * mirostat_tau;
  411. SamplingApi.llama_sample_temperature(_ctx, candidates_p, temp);
  412. id = SamplingApi.llama_sample_token_mirostat_v2(_ctx, candidates_p, mirostat_tau, mirostat_eta, mirostat_mu);
  413. }
  414. else
  415. {
  416. // Temperature sampling
  417. SamplingApi.llama_sample_top_k(_ctx, candidates_p, top_k, 1);
  418. SamplingApi.llama_sample_tail_free(_ctx, candidates_p, tfs_z, 1);
  419. SamplingApi.llama_sample_typical(_ctx, candidates_p, typical_p, 1);
  420. SamplingApi.llama_sample_top_p(_ctx, candidates_p, top_p, 1);
  421. SamplingApi.llama_sample_temperature(_ctx, candidates_p, temp);
  422. id = SamplingApi.llama_sample_token(_ctx, candidates_p);
  423. }
  424. }
  425. _last_n_tokens.RemoveAt(0);
  426. _last_n_tokens.Add(id);
  427. }
  428. // replace end of text token with newline token when in interactive mode
  429. if (id == NativeApi.llama_token_eos() && _params.interactive && !_params.instruct)
  430. {
  431. id = _llama_token_newline[0];
  432. if (_params.antiprompt.Count != 0)
  433. {
  434. // tokenize and inject first reverse prompt
  435. var first_antiprompt = Utils.llama_tokenize(_ctx, _params.antiprompt[0], false);
  436. _embed_inp.AddRange(first_antiprompt);
  437. }
  438. }
  439. // add it to the context
  440. _embed.Add(id);
  441. // echo this to console
  442. _input_echo = true;
  443. // decrement remaining sampling budget
  444. _n_remain--;
  445. }
  446. else
  447. {
  448. // Assuming that the necessary variables have been defined and initialized,
  449. // the C# equivalent code could be:
  450. while (_embed_inp.Count > _n_consumed)
  451. {
  452. _embed.Add(_embed_inp[_n_consumed]);
  453. _last_n_tokens.RemoveAt(0);
  454. _last_n_tokens.Add(_embed_inp[_n_consumed]);
  455. _n_consumed++;
  456. if (_embed.Count >= _params.n_batch)
  457. {
  458. break;
  459. }
  460. }
  461. }
  462. if (_input_echo)
  463. {
  464. foreach (var id in _embed)
  465. {
  466. yield return Utils.PtrToStringUTF8(NativeApi.llama_token_to_str(_ctx, id));
  467. }
  468. }
  469. if (_params.interactive && _embed_inp.Count <= _n_consumed)
  470. {
  471. if (_params.antiprompt.Count > 0)
  472. {
  473. string last_output = "";
  474. foreach (var id in _last_n_tokens)
  475. {
  476. last_output += Utils.PtrToStringUTF8(NativeApi.llama_token_to_str(_ctx, id));
  477. }
  478. _is_antiprompt = false;
  479. foreach (var antiprompt in _params.antiprompt)
  480. {
  481. if (last_output.EndsWith(antiprompt))
  482. {
  483. _is_interacting = true;
  484. _is_antiprompt = true;
  485. break;
  486. }
  487. }
  488. }
  489. if(_n_past > 0 && _is_interacting)
  490. {
  491. _input_echo = false;
  492. break;
  493. }
  494. if (_embed.Count > 0 && _embed.Last() == NativeApi.llama_token_eos())
  495. {
  496. if (_params.instruct) {
  497. _is_interacting = true;
  498. } else
  499. {
  500. Logger.Default.Info(" [end of text]");
  501. }
  502. }
  503. if (_params.interactive && _n_remain <= 0 && _params.n_predict != -1) {
  504. _n_remain = _params.n_predict;
  505. _is_interacting = true;
  506. }
  507. }
  508. }
  509. }
  510. }
  511. }

C#/.NET上易用的LLM高性能推理框架,支持LLaMA和LLaVA系列模型。

Contributors (1)