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.

Model.cs 24 kB

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

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

Contributors (1)