binding.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "binding.h"
  4. #include <cassert>
  5. #include <cinttypes>
  6. #include <cmath>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <fstream>
  10. #include <iostream>
  11. #include <regex>
  12. #include <sstream>
  13. #include <string>
  14. #include <vector>
  15. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  16. #include <signal.h>
  17. #include <unistd.h>
  18. #elif defined(_WIN32)
  19. #define WIN32_LEAN_AND_MEAN
  20. #define NOMINMAX
  21. #include <signal.h>
  22. #include <windows.h>
  23. #endif
  24. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || \
  25. defined(_WIN32)
  26. void sigint_handler(int signo) {
  27. if (signo == SIGINT) {
  28. _exit(130);
  29. }
  30. }
  31. #endif
  32. int get_embeddings(void *params_ptr, void *state_pr, float *res_embeddings) {
  33. gpt_params *params_p = (gpt_params *)params_ptr;
  34. llama_context *ctx = (llama_context *)state_pr;
  35. gpt_params params = *params_p;
  36. if (params.seed <= 0) {
  37. params.seed = time(NULL);
  38. }
  39. std::mt19937 rng(params.seed);
  40. llama_init_backend(params.numa);
  41. int n_past = 0;
  42. // Add a space in front of the first character to match OG llama tokenizer
  43. // behavior
  44. params.prompt.insert(0, 1, ' ');
  45. // tokenize the prompt
  46. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  47. // determine newline token
  48. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  49. if (embd_inp.size() > 0) {
  50. if (llama_eval(ctx, embd_inp.data(), embd_inp.size(), n_past,
  51. params.n_threads)) {
  52. fprintf(stderr, "%s : failed to eval\n", __func__);
  53. return 1;
  54. }
  55. }
  56. const int n_embd = llama_n_embd(ctx);
  57. const auto embeddings = llama_get_embeddings(ctx);
  58. for (int i = 0; i < n_embd; i++) {
  59. res_embeddings[i] = embeddings[i];
  60. }
  61. return 0;
  62. }
  63. int get_token_embeddings(void *params_ptr, void *state_pr, int *tokens,
  64. int tokenSize, float *res_embeddings) {
  65. gpt_params *params_p = (gpt_params *)params_ptr;
  66. llama_context *ctx = (llama_context *)state_pr;
  67. gpt_params params = *params_p;
  68. for (int i = 0; i < tokenSize; i++) {
  69. auto token_str = llama_token_to_str(ctx, tokens[i]);
  70. if (token_str == nullptr) {
  71. continue;
  72. }
  73. std::vector<std::string> my_vector;
  74. std::string str_token(token_str); // create a new std::string from the char*
  75. params_p->prompt += str_token;
  76. }
  77. return get_embeddings(params_ptr, state_pr, res_embeddings);
  78. }
  79. int eval(void *params_ptr, void *state_pr, char *text) {
  80. gpt_params *params_p = (gpt_params *)params_ptr;
  81. llama_context *ctx = (llama_context *)state_pr;
  82. auto n_past = 0;
  83. auto last_n_tokens_data =
  84. std::vector<llama_token>(params_p->repeat_last_n, 0);
  85. auto tokens = std::vector<llama_token>(params_p->n_ctx);
  86. auto n_prompt_tokens =
  87. llama_tokenize(ctx, text, tokens.data(), tokens.size(), true);
  88. if (n_prompt_tokens < 1) {
  89. fprintf(stderr, "%s : failed to tokenize prompt\n", __func__);
  90. return 1;
  91. }
  92. // evaluate prompt
  93. return llama_eval(ctx, tokens.data(), n_prompt_tokens, n_past,
  94. params_p->n_threads);
  95. }
  96. int llama_predict(void *params_ptr, void *state_pr, char *result, bool debug) {
  97. gpt_params *params_p = (gpt_params *)params_ptr;
  98. llama_context *ctx = (llama_context *)state_pr;
  99. gpt_params params = *params_p;
  100. const int n_ctx = llama_n_ctx(ctx);
  101. if (params.seed <= 0) {
  102. params.seed = time(NULL);
  103. }
  104. std::mt19937 rng(params.seed);
  105. std::string path_session = params.path_prompt_cache;
  106. std::vector<llama_token> session_tokens;
  107. if (!path_session.empty()) {
  108. if (debug) {
  109. fprintf(stderr, "%s: attempting to load saved session from '%s'\n",
  110. __func__, path_session.c_str());
  111. }
  112. // fopen to check for existing session
  113. FILE *fp = std::fopen(path_session.c_str(), "rb");
  114. if (fp != NULL) {
  115. std::fclose(fp);
  116. session_tokens.resize(n_ctx);
  117. size_t n_token_count_out = 0;
  118. if (!llama_load_session_file(
  119. ctx, path_session.c_str(), session_tokens.data(),
  120. session_tokens.capacity(), &n_token_count_out)) {
  121. fprintf(stderr, "%s: error: failed to load session file '%s'\n",
  122. __func__, path_session.c_str());
  123. return 1;
  124. }
  125. session_tokens.resize(n_token_count_out);
  126. llama_set_rng_seed(ctx, params.seed);
  127. if (debug) {
  128. fprintf(stderr, "%s: loaded a session with prompt size of %d tokens\n",
  129. __func__, (int)session_tokens.size());
  130. }
  131. } else {
  132. if (debug) {
  133. fprintf(stderr, "%s: session file does not exist, will create\n",
  134. __func__);
  135. }
  136. }
  137. }
  138. std::vector<llama_token> embd_inp;
  139. if (!params.prompt.empty() || session_tokens.empty()) {
  140. // Add a space in front of the first character to match OG llama tokenizer
  141. // behavior
  142. params.prompt.insert(0, 1, ' ');
  143. embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  144. } else {
  145. embd_inp = session_tokens;
  146. }
  147. // debug message about similarity of saved session, if applicable
  148. size_t n_matching_session_tokens = 0;
  149. if (session_tokens.size()) {
  150. for (llama_token id : session_tokens) {
  151. if (n_matching_session_tokens >= embd_inp.size() ||
  152. id != embd_inp[n_matching_session_tokens]) {
  153. break;
  154. }
  155. n_matching_session_tokens++;
  156. }
  157. if (debug) {
  158. if (params.prompt.empty() &&
  159. n_matching_session_tokens == embd_inp.size()) {
  160. fprintf(stderr, "%s: using full prompt from session file\n", __func__);
  161. } else if (n_matching_session_tokens >= embd_inp.size()) {
  162. fprintf(stderr, "%s: session file has exact match for prompt!\n",
  163. __func__);
  164. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  165. fprintf(stderr,
  166. "%s: warning: session file has low similarity to prompt (%zu / "
  167. "%zu tokens); will mostly be reevaluated\n",
  168. __func__, n_matching_session_tokens, embd_inp.size());
  169. } else {
  170. fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
  171. __func__, n_matching_session_tokens, embd_inp.size());
  172. }
  173. }
  174. }
  175. // if we will use the cache for the full prompt without reaching the end of
  176. // the cache, force reevaluation of the last token token to recalculate the
  177. // cached logits
  178. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() &&
  179. session_tokens.size() > embd_inp.size()) {
  180. session_tokens.resize(embd_inp.size() - 1);
  181. }
  182. // number of tokens to keep when resetting context
  183. if (params.n_keep < 0 || params.n_keep > (int)embd_inp.size()) {
  184. params.n_keep = (int)embd_inp.size();
  185. }
  186. // determine newline token
  187. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  188. // TODO: replace with ring-buffer
  189. std::vector<llama_token> last_n_tokens(n_ctx);
  190. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  191. bool need_to_save_session =
  192. !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  193. int n_past = 0;
  194. int n_remain = params.n_predict;
  195. int n_consumed = 0;
  196. int n_session_consumed = 0;
  197. std::vector<llama_token> embd;
  198. std::string res = "";
  199. // do one empty run to warm up the model
  200. {
  201. const std::vector<llama_token> tmp = {
  202. llama_token_bos(),
  203. };
  204. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  205. llama_reset_timings(ctx);
  206. }
  207. while (n_remain != 0) {
  208. // predict
  209. if (embd.size() > 0) {
  210. // infinite text generation via context swapping
  211. // if we run out of context:
  212. // - take the n_keep first tokens from the original prompt (via n_past)
  213. // - take half of the last (n_ctx - n_keep) tokens and recompute the
  214. // logits in batches
  215. if (n_past + (int)embd.size() > n_ctx) {
  216. const int n_left = n_past - params.n_keep;
  217. // always keep the first token - BOS
  218. n_past = std::max(1, params.n_keep);
  219. // insert n_left/2 tokens at the start of embd from last_n_tokens
  220. embd.insert(embd.begin(),
  221. last_n_tokens.begin() + n_ctx - n_left / 2 - embd.size(),
  222. last_n_tokens.end() - embd.size());
  223. // stop saving session if we run out of context
  224. path_session.clear();
  225. // printf("\n---\n");
  226. // printf("resetting: '");
  227. // for (int i = 0; i < (int) embd.size(); i++) {
  228. // printf("%s", llama_token_to_str(ctx, embd[i]));
  229. // }
  230. // printf("'\n");
  231. // printf("\n---\n");
  232. }
  233. // try to reuse a matching prefix from the loaded session instead of
  234. // re-eval (via n_past)
  235. if (n_session_consumed < (int)session_tokens.size()) {
  236. size_t i = 0;
  237. for (; i < embd.size(); i++) {
  238. if (embd[i] != session_tokens[n_session_consumed]) {
  239. session_tokens.resize(n_session_consumed);
  240. break;
  241. }
  242. n_past++;
  243. n_session_consumed++;
  244. if (n_session_consumed >= (int)session_tokens.size()) {
  245. ++i;
  246. break;
  247. }
  248. }
  249. if (i > 0) {
  250. embd.erase(embd.begin(), embd.begin() + i);
  251. }
  252. }
  253. // evaluate tokens in batches
  254. // embd is typically prepared beforehand to fit within a batch, but not
  255. // always
  256. for (int i = 0; i < (int)embd.size(); i += params.n_batch) {
  257. int n_eval = (int)embd.size() - i;
  258. if (n_eval > params.n_batch) {
  259. n_eval = params.n_batch;
  260. }
  261. if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
  262. fprintf(stderr, "%s : failed to eval\n", __func__);
  263. return 1;
  264. }
  265. n_past += n_eval;
  266. }
  267. if (embd.size() > 0 && !path_session.empty()) {
  268. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  269. n_session_consumed = session_tokens.size();
  270. }
  271. }
  272. embd.clear();
  273. if ((int)embd_inp.size() <= n_consumed) {
  274. // out of user input, sample next token
  275. const float temp = params.temp;
  276. const int32_t top_k =
  277. params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  278. const float top_p = params.top_p;
  279. const float tfs_z = params.tfs_z;
  280. const float typical_p = params.typical_p;
  281. const int32_t repeat_last_n =
  282. params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
  283. const float repeat_penalty = params.repeat_penalty;
  284. const float alpha_presence = params.presence_penalty;
  285. const float alpha_frequency = params.frequency_penalty;
  286. const int mirostat = params.mirostat;
  287. const float mirostat_tau = params.mirostat_tau;
  288. const float mirostat_eta = params.mirostat_eta;
  289. const bool penalize_nl = params.penalize_nl;
  290. // optionally save the session on first sample (for faster prompt loading
  291. // next time)
  292. if (!path_session.empty() && need_to_save_session &&
  293. !params.prompt_cache_ro) {
  294. need_to_save_session = false;
  295. llama_save_session_file(ctx, path_session.c_str(),
  296. session_tokens.data(), session_tokens.size());
  297. }
  298. llama_token id = 0;
  299. {
  300. auto logits = llama_get_logits(ctx);
  301. auto n_vocab = llama_n_vocab(ctx);
  302. // Apply params.logit_bias map
  303. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end();
  304. it++) {
  305. logits[it->first] += it->second;
  306. }
  307. std::vector<llama_token_data> candidates;
  308. candidates.reserve(n_vocab);
  309. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  310. candidates.emplace_back(
  311. llama_token_data{token_id, logits[token_id], 0.0f});
  312. }
  313. llama_token_data_array candidates_p = {candidates.data(),
  314. candidates.size(), false};
  315. // Apply penalties
  316. float nl_logit = logits[llama_token_nl()];
  317. auto last_n_repeat =
  318. std::min(std::min((int)last_n_tokens.size(), repeat_last_n), n_ctx);
  319. llama_sample_repetition_penalty(
  320. ctx, &candidates_p,
  321. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  322. last_n_repeat, repeat_penalty);
  323. llama_sample_frequency_and_presence_penalties(
  324. ctx, &candidates_p,
  325. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  326. last_n_repeat, alpha_frequency, alpha_presence);
  327. if (!penalize_nl) {
  328. logits[llama_token_nl()] = nl_logit;
  329. }
  330. if (temp <= 0) {
  331. // Greedy sampling
  332. id = llama_sample_token_greedy(ctx, &candidates_p);
  333. } else {
  334. if (mirostat == 1) {
  335. static float mirostat_mu = 2.0f * mirostat_tau;
  336. const int mirostat_m = 100;
  337. llama_sample_temperature(ctx, &candidates_p, temp);
  338. id = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau,
  339. mirostat_eta, mirostat_m,
  340. &mirostat_mu);
  341. } else if (mirostat == 2) {
  342. static float mirostat_mu = 2.0f * mirostat_tau;
  343. llama_sample_temperature(ctx, &candidates_p, temp);
  344. id = llama_sample_token_mirostat_v2(
  345. ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  346. } else {
  347. // Temperature sampling
  348. llama_sample_top_k(ctx, &candidates_p, top_k, 1);
  349. llama_sample_tail_free(ctx, &candidates_p, tfs_z, 1);
  350. llama_sample_typical(ctx, &candidates_p, typical_p, 1);
  351. llama_sample_top_p(ctx, &candidates_p, top_p, 1);
  352. llama_sample_temperature(ctx, &candidates_p, temp);
  353. id = llama_sample_token(ctx, &candidates_p);
  354. }
  355. }
  356. // printf("`%d`", candidates_p.size);
  357. last_n_tokens.erase(last_n_tokens.begin());
  358. last_n_tokens.push_back(id);
  359. }
  360. // add it to the context
  361. embd.push_back(id);
  362. // decrement remaining sampling budget
  363. --n_remain;
  364. // call the token callback, no need to check if one is actually
  365. // registered, that will be handled on the Go side.
  366. auto token_str = llama_token_to_str(ctx, id);
  367. if (!tokenCallback(state_pr, (char *)token_str)) {
  368. break;
  369. }
  370. } else {
  371. // some user input remains from prompt or interaction, forward it to
  372. // processing
  373. while ((int)embd_inp.size() > n_consumed) {
  374. embd.push_back(embd_inp[n_consumed]);
  375. last_n_tokens.erase(last_n_tokens.begin());
  376. last_n_tokens.push_back(embd_inp[n_consumed]);
  377. ++n_consumed;
  378. if ((int)embd.size() >= params.n_batch) {
  379. break;
  380. }
  381. }
  382. }
  383. for (auto id : embd) {
  384. res += llama_token_to_str(ctx, id);
  385. }
  386. // check for stop prompt
  387. if (params.antiprompt.size()) {
  388. std::string last_output;
  389. for (auto id : last_n_tokens) {
  390. last_output += llama_token_to_str(ctx, id);
  391. }
  392. // Check if each of the reverse prompts appears at the end of the output.
  393. for (std::string &antiprompt : params.antiprompt) {
  394. // size_t extra_padding = params.interactive ? 0 : 2;
  395. size_t extra_padding = 2;
  396. size_t search_start_pos =
  397. last_output.length() >
  398. static_cast<size_t>(antiprompt.length() + extra_padding)
  399. ? last_output.length() -
  400. static_cast<size_t>(antiprompt.length() + extra_padding)
  401. : 0;
  402. if (last_output.find(antiprompt.c_str(), search_start_pos) !=
  403. std::string::npos) {
  404. goto end;
  405. }
  406. }
  407. }
  408. // end of text token
  409. if (!embd.empty() && embd.back() == llama_token_eos()) {
  410. break;
  411. }
  412. }
  413. if (!path_session.empty() && params.prompt_cache_all &&
  414. !params.prompt_cache_ro) {
  415. if (debug) {
  416. fprintf(stderr, "\n%s: saving final output to session file '%s'\n",
  417. __func__, path_session.c_str());
  418. }
  419. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(),
  420. session_tokens.size());
  421. }
  422. end:
  423. #if defined(_WIN32)
  424. signal(SIGINT, SIG_DFL);
  425. #endif
  426. if (debug) {
  427. llama_print_timings(ctx);
  428. llama_reset_timings(ctx);
  429. }
  430. strcpy(result, res.c_str());
  431. return 0;
  432. }
  433. void llama_binding_free_model(void *state_ptr) {
  434. llama_context *ctx = (llama_context *)state_ptr;
  435. llama_free(ctx);
  436. }
  437. void llama_free_params(void *params_ptr) {
  438. gpt_params *params = (gpt_params *)params_ptr;
  439. delete params;
  440. }
  441. std::vector<std::string> create_vector(const char **strings, int count) {
  442. std::vector<std::string> *vec = new std::vector<std::string>;
  443. for (int i = 0; i < count; i++) {
  444. vec->push_back(std::string(strings[i]));
  445. }
  446. return *vec;
  447. }
  448. void delete_vector(std::vector<std::string> *vec) { delete vec; }
  449. int load_state(void *ctx, char *statefile, char *modes) {
  450. llama_context *state = (llama_context *)ctx;
  451. const llama_context *constState = static_cast<const llama_context *>(state);
  452. const size_t state_size = llama_get_state_size(state);
  453. uint8_t *state_mem = new uint8_t[state_size];
  454. {
  455. FILE *fp_read = fopen(statefile, modes);
  456. if (state_size != llama_get_state_size(constState)) {
  457. fprintf(stderr, "\n%s : failed to validate state size\n", __func__);
  458. return 1;
  459. }
  460. const size_t ret = fread(state_mem, 1, state_size, fp_read);
  461. if (ret != state_size) {
  462. fprintf(stderr, "\n%s : failed to read state\n", __func__);
  463. return 1;
  464. }
  465. llama_set_state_data(
  466. state, state_mem); // could also read directly from memory mapped file
  467. fclose(fp_read);
  468. }
  469. return 0;
  470. }
  471. void save_state(void *ctx, char *dst, char *modes) {
  472. llama_context *state = (llama_context *)ctx;
  473. const size_t state_size = llama_get_state_size(state);
  474. uint8_t *state_mem = new uint8_t[state_size];
  475. // Save state (rng, logits, embedding and kv_cache) to file
  476. {
  477. FILE *fp_write = fopen(dst, modes);
  478. llama_copy_state_data(
  479. state, state_mem); // could also copy directly to memory mapped file
  480. fwrite(state_mem, 1, state_size, fp_write);
  481. fclose(fp_write);
  482. }
  483. }
  484. void *llama_allocate_params(
  485. const char *prompt, int seed, int threads, int tokens, int top_k,
  486. float top_p, float temp, float repeat_penalty, int repeat_last_n,
  487. bool ignore_eos, bool memory_f16, int n_batch, int n_keep,
  488. const char **antiprompt, int antiprompt_count, float tfs_z, float typical_p,
  489. float frequency_penalty, float presence_penalty, int mirostat,
  490. float mirostat_eta, float mirostat_tau, bool penalize_nl,
  491. const char *logit_bias, const char *session_file, bool prompt_cache_all,
  492. bool mlock, bool mmap, const char *maingpu, const char *tensorsplit,
  493. bool prompt_cache_ro) {
  494. gpt_params *params = new gpt_params;
  495. params->seed = seed;
  496. params->n_threads = threads;
  497. params->n_predict = tokens;
  498. params->repeat_last_n = repeat_last_n;
  499. params->prompt_cache_ro = prompt_cache_ro;
  500. params->top_k = top_k;
  501. params->top_p = top_p;
  502. params->memory_f16 = memory_f16;
  503. params->temp = temp;
  504. params->use_mmap = mmap;
  505. params->use_mlock = mlock;
  506. params->repeat_penalty = repeat_penalty;
  507. params->n_batch = n_batch;
  508. params->n_keep = n_keep;
  509. if (maingpu[0] != '\0') {
  510. params->main_gpu = std::stoi(maingpu);
  511. }
  512. if (tensorsplit[0] != '\0') {
  513. std::string arg_next = tensorsplit;
  514. // split string by , and /
  515. const std::regex regex{R"([,/]+)"};
  516. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  517. std::vector<std::string> split_arg{it, {}};
  518. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  519. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  520. if (i < split_arg.size()) {
  521. params->tensor_split[i] = std::stof(split_arg[i]);
  522. } else {
  523. params->tensor_split[i] = 0.0f;
  524. }
  525. }
  526. }
  527. params->prompt_cache_all = prompt_cache_all;
  528. params->path_prompt_cache = session_file;
  529. if (ignore_eos) {
  530. params->logit_bias[llama_token_eos()] = -INFINITY;
  531. }
  532. if (antiprompt_count > 0) {
  533. params->antiprompt = create_vector(antiprompt, antiprompt_count);
  534. }
  535. params->tfs_z = tfs_z;
  536. params->typical_p = typical_p;
  537. params->presence_penalty = presence_penalty;
  538. params->mirostat = mirostat;
  539. params->mirostat_eta = mirostat_eta;
  540. params->mirostat_tau = mirostat_tau;
  541. params->penalize_nl = penalize_nl;
  542. std::stringstream ss(logit_bias);
  543. llama_token key;
  544. char sign;
  545. std::string value_str;
  546. if (ss >> key && ss >> sign && std::getline(ss, value_str) &&
  547. (sign == '+' || sign == '-')) {
  548. params->logit_bias[key] =
  549. std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  550. }
  551. params->frequency_penalty = frequency_penalty;
  552. params->prompt = prompt;
  553. return params;
  554. }
  555. void *load_model(const char *fname, int n_ctx, int n_seed, bool memory_f16,
  556. bool mlock, bool embeddings, bool mmap, bool low_vram,
  557. bool vocab_only, int n_gpu_layers, int n_batch,
  558. const char *maingpu, const char *tensorsplit, bool numa) {
  559. // load the model
  560. auto lparams = llama_context_default_params();
  561. lparams.n_ctx = n_ctx;
  562. lparams.seed = n_seed;
  563. lparams.f16_kv = memory_f16;
  564. lparams.embedding = embeddings;
  565. lparams.use_mlock = mlock;
  566. lparams.n_gpu_layers = n_gpu_layers;
  567. lparams.use_mmap = mmap;
  568. lparams.low_vram = low_vram;
  569. lparams.vocab_only = vocab_only;
  570. if (maingpu[0] != '\0') {
  571. lparams.main_gpu = std::stoi(maingpu);
  572. }
  573. if (tensorsplit[0] != '\0') {
  574. std::string arg_next = tensorsplit;
  575. // split string by , and /
  576. const std::regex regex{R"([,/]+)"};
  577. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  578. std::vector<std::string> split_arg{it, {}};
  579. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  580. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  581. if (i < split_arg.size()) {
  582. lparams.tensor_split[i] = std::stof(split_arg[i]);
  583. } else {
  584. lparams.tensor_split[i] = 0.0f;
  585. }
  586. }
  587. }
  588. lparams.n_batch = n_batch;
  589. llama_init_backend(numa);
  590. void *res = nullptr;
  591. try {
  592. llama_model *model = llama_load_model_from_file(fname, lparams);
  593. if (model == NULL) {
  594. fprintf(stderr, "error: failed to load model \n");
  595. return res;
  596. }
  597. llama_context *lctx = llama_new_context_with_model(model, lparams);
  598. if (lctx == NULL) {
  599. fprintf(stderr, "error: failed to create context with model \n");
  600. llama_free_model(model);
  601. return res;
  602. }
  603. } catch (std::runtime_error &e) {
  604. fprintf(stderr, "failed %s", e.what());
  605. return res;
  606. }
  607. return res;
  608. }