server.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include "grammar-parser.h"
  5. #ifndef NDEBUG
  6. // crash the server in debug mode, otherwise send an http 500 error
  7. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  8. #endif
  9. #include "httplib.h"
  10. #include "json.hpp"
  11. // auto generated files (update with ./deps.sh)
  12. #include "index.html.hpp"
  13. #include "index.js.hpp"
  14. #include "completion.js.hpp"
  15. #include "json-schema-to-grammar.mjs.hpp"
  16. #ifndef SERVER_VERBOSE
  17. #define SERVER_VERBOSE 1
  18. #endif
  19. using namespace httplib;
  20. using json = nlohmann::json;
  21. struct server_params
  22. {
  23. std::string hostname = "127.0.0.1";
  24. std::string public_path = "examples/server/public";
  25. int32_t port = 8080;
  26. int32_t read_timeout = 600;
  27. int32_t write_timeout = 600;
  28. };
  29. // completion token output with probabilities
  30. struct completion_token_output
  31. {
  32. struct token_prob
  33. {
  34. llama_token tok;
  35. float prob;
  36. };
  37. std::vector<token_prob> probs;
  38. llama_token tok;
  39. };
  40. static size_t common_part(const std::vector<llama_token> &a, const std::vector<llama_token> &b)
  41. {
  42. size_t i;
  43. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++)
  44. {
  45. }
  46. return i;
  47. }
  48. enum stop_type
  49. {
  50. STOP_FULL,
  51. STOP_PARTIAL,
  52. };
  53. static bool ends_with(const std::string &str, const std::string &suffix)
  54. {
  55. return str.size() >= suffix.size() &&
  56. 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  57. }
  58. static size_t find_partial_stop_string(const std::string &stop,
  59. const std::string &text)
  60. {
  61. if (!text.empty() && !stop.empty())
  62. {
  63. const char text_last_char = text.back();
  64. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--)
  65. {
  66. if (stop[char_index] == text_last_char)
  67. {
  68. const std::string current_partial = stop.substr(0, char_index + 1);
  69. if (ends_with(text, current_partial))
  70. {
  71. return text.size() - char_index - 1;
  72. }
  73. }
  74. }
  75. }
  76. return std::string::npos;
  77. }
  78. template <class Iter>
  79. static std::string tokens_to_str(llama_context *ctx, Iter begin, Iter end)
  80. {
  81. std::string ret;
  82. for (; begin != end; ++begin)
  83. {
  84. ret += llama_token_to_str(ctx, *begin);
  85. }
  86. return ret;
  87. }
  88. static void server_log(const char *level, const char *function, int line,
  89. const char *message, const nlohmann::ordered_json &extra)
  90. {
  91. nlohmann::ordered_json log{
  92. {"timestamp", time(nullptr)},
  93. {"level", level},
  94. {"function", function},
  95. {"line", line},
  96. {"message", message},
  97. };
  98. if (!extra.empty())
  99. {
  100. log.merge_patch(extra);
  101. }
  102. const std::string str = log.dump(-1, ' ', false, json::error_handler_t::replace);
  103. fprintf(stdout, "%.*s\n", (int)str.size(), str.data());
  104. fflush(stdout);
  105. }
  106. // format incomplete utf-8 multibyte character for output
  107. static std::string tokens_to_output_formatted_string(const llama_context *ctx, const llama_token token)
  108. {
  109. std::string out = token == -1 ? "" : llama_token_to_str(ctx, token);
  110. // if the size is 1 and first bit is 1, meaning it's a partial character
  111. // (size > 1 meaning it's already a known token)
  112. if (out.size() == 1 && (out[0] & 0x80) == 0x80)
  113. {
  114. std::stringstream ss;
  115. ss << std::hex << (out[0] & 0xff);
  116. std::string res(ss.str());
  117. out = "byte: \\x" + res;
  118. }
  119. return out;
  120. }
  121. // convert a vector of completion_token_output to json
  122. static json probs_vector_to_json(const llama_context *ctx, const std::vector<completion_token_output> probs)
  123. {
  124. json out = json::array();
  125. for (const auto &prob : probs)
  126. {
  127. json probs_for_token = json::array();
  128. for (const auto &p : prob.probs)
  129. {
  130. std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  131. probs_for_token.push_back(json{
  132. {"tok_str", tok_str},
  133. {"prob", p.prob},
  134. });
  135. }
  136. std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  137. out.push_back(json{
  138. {"content", tok_str},
  139. {"probs", probs_for_token},
  140. });
  141. }
  142. return out;
  143. }
  144. static bool server_verbose = false;
  145. #if SERVER_VERBOSE != 1
  146. #define LOG_VERBOSE(MSG, ...)
  147. #else
  148. #define LOG_VERBOSE(MSG, ...) \
  149. do \
  150. { \
  151. if (server_verbose) \
  152. { \
  153. server_log("VERBOSE", __func__, __LINE__, MSG, __VA_ARGS__); \
  154. } \
  155. } while (0)
  156. #endif
  157. #define LOG_ERROR(MSG, ...) server_log("ERROR", __func__, __LINE__, MSG, __VA_ARGS__)
  158. #define LOG_WARNING(MSG, ...) server_log("WARNING", __func__, __LINE__, MSG, __VA_ARGS__)
  159. #define LOG_INFO(MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  160. struct llama_server_context
  161. {
  162. bool stream = false;
  163. bool has_next_token = false;
  164. std::string generated_text;
  165. std::vector<completion_token_output> generated_token_probs;
  166. size_t num_prompt_tokens = 0;
  167. size_t num_tokens_predicted = 0;
  168. size_t n_past = 0;
  169. size_t n_remain = 0;
  170. json prompt;
  171. std::vector<llama_token> embd;
  172. std::vector<llama_token> last_n_tokens;
  173. llama_model *model = nullptr;
  174. llama_context *ctx = nullptr;
  175. gpt_params params;
  176. grammar_parser::parse_state parsed_grammar;
  177. llama_grammar *grammar = nullptr;
  178. bool truncated = false;
  179. bool stopped_eos = false;
  180. bool stopped_word = false;
  181. bool stopped_limit = false;
  182. std::string stopping_word;
  183. int32_t multibyte_pending = 0;
  184. std::mutex mutex;
  185. std::unique_lock<std::mutex> lock()
  186. {
  187. return std::unique_lock<std::mutex>(mutex);
  188. }
  189. ~llama_server_context()
  190. {
  191. if (ctx)
  192. {
  193. llama_free(ctx);
  194. ctx = nullptr;
  195. }
  196. if (model)
  197. {
  198. llama_free_model(model);
  199. model = nullptr;
  200. }
  201. }
  202. void rewind()
  203. {
  204. params.antiprompt.clear();
  205. params.grammar.clear();
  206. num_prompt_tokens = 0;
  207. num_tokens_predicted = 0;
  208. generated_text = "";
  209. generated_text.reserve(params.n_ctx);
  210. generated_token_probs.clear();
  211. truncated = false;
  212. stopped_eos = false;
  213. stopped_word = false;
  214. stopped_limit = false;
  215. stopping_word = "";
  216. multibyte_pending = 0;
  217. n_remain = 0;
  218. n_past = 0;
  219. if (grammar != nullptr) {
  220. llama_grammar_free(grammar);
  221. grammar = nullptr;
  222. }
  223. }
  224. bool loadModel(const gpt_params &params_)
  225. {
  226. params = params_;
  227. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  228. if (model == nullptr)
  229. {
  230. LOG_ERROR("unable to load model", {{"model", params_.model}});
  231. return false;
  232. }
  233. last_n_tokens.resize(params.n_ctx);
  234. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  235. return true;
  236. }
  237. std::vector<llama_token> tokenize(json json_prompt, bool add_bos)
  238. {
  239. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  240. // or the first element of the json_prompt array is a string.
  241. std::vector<llama_token> prompt_tokens;
  242. if (json_prompt.is_array())
  243. {
  244. bool first = true;
  245. for (const auto& p : json_prompt)
  246. {
  247. if (p.is_string())
  248. {
  249. auto s = p.template get<std::string>();
  250. std::vector<llama_token> p;
  251. if (first)
  252. {
  253. s.insert(0, 1, ' '); // add a space if it's the first
  254. p = ::llama_tokenize(ctx, s, add_bos);
  255. first = false;
  256. }
  257. else
  258. {
  259. p = ::llama_tokenize(ctx, s, false);
  260. }
  261. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  262. }
  263. else
  264. {
  265. if (first)
  266. {
  267. first = false;
  268. }
  269. prompt_tokens.push_back(p.template get<llama_token>());
  270. }
  271. }
  272. }
  273. else
  274. {
  275. auto s = json_prompt.template get<std::string>();
  276. s.insert(0, 1, ' '); // always add a first space
  277. prompt_tokens = ::llama_tokenize(ctx, s, add_bos);
  278. }
  279. return prompt_tokens;
  280. }
  281. bool loadGrammar()
  282. {
  283. if (!params.grammar.empty()) {
  284. parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  285. // will be empty (default) if there are parse errors
  286. if (parsed_grammar.rules.empty()) {
  287. LOG_ERROR("grammar parse error", {{"grammar", params.grammar}});
  288. return false;
  289. }
  290. grammar_parser::print_grammar(stderr, parsed_grammar);
  291. {
  292. auto it = params.logit_bias.find(llama_token_eos(ctx));
  293. if (it != params.logit_bias.end() && it->second == -INFINITY) {
  294. LOG_WARNING("EOS token is disabled, which will cause most grammars to fail", {});
  295. }
  296. }
  297. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  298. grammar = llama_grammar_init(
  299. grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
  300. }
  301. return true;
  302. }
  303. void loadPrompt()
  304. {
  305. auto prompt_tokens = tokenize(prompt, true); // always add BOS
  306. num_prompt_tokens = prompt_tokens.size();
  307. if (params.n_keep < 0)
  308. {
  309. params.n_keep = (int)num_prompt_tokens;
  310. }
  311. params.n_keep = std::min(params.n_ctx - 4, params.n_keep);
  312. // if input prompt is too big, truncate like normal
  313. if (num_prompt_tokens >= (size_t)params.n_ctx)
  314. {
  315. const int n_left = (params.n_ctx - params.n_keep) / 2;
  316. std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + params.n_keep);
  317. const int erased_blocks = (num_prompt_tokens - params.n_keep - n_left - 1) / n_left;
  318. new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + params.n_keep + erased_blocks * n_left, prompt_tokens.end());
  319. std::copy(prompt_tokens.end() - params.n_ctx, prompt_tokens.end(), last_n_tokens.begin());
  320. LOG_VERBOSE("input truncated", {
  321. {"n_ctx", params.n_ctx},
  322. {"n_keep", params.n_keep},
  323. {"n_left", n_left},
  324. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  325. });
  326. truncated = true;
  327. prompt_tokens = new_tokens;
  328. }
  329. else
  330. {
  331. const size_t ps = num_prompt_tokens;
  332. std::fill(last_n_tokens.begin(), last_n_tokens.end() - ps, 0);
  333. std::copy(prompt_tokens.begin(), prompt_tokens.end(), last_n_tokens.end() - ps);
  334. }
  335. // compare the evaluated prompt with the new prompt
  336. n_past = common_part(embd, prompt_tokens);
  337. embd = prompt_tokens;
  338. if (n_past == num_prompt_tokens)
  339. {
  340. // we have to evaluate at least 1 token to generate logits.
  341. n_past--;
  342. }
  343. LOG_VERBOSE("prompt ingested", {
  344. {"n_past", n_past},
  345. {"cached", tokens_to_str(ctx, embd.cbegin(), embd.cbegin() + n_past)},
  346. {"to_eval", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend())},
  347. });
  348. has_next_token = true;
  349. }
  350. void beginCompletion()
  351. {
  352. // number of tokens to keep when resetting context
  353. n_remain = params.n_predict;
  354. llama_set_rng_seed(ctx, params.seed);
  355. }
  356. completion_token_output nextToken()
  357. {
  358. completion_token_output result;
  359. result.tok = -1;
  360. if (embd.size() >= (size_t)params.n_ctx)
  361. {
  362. // Reset context
  363. const int n_left = (params.n_ctx - params.n_keep) / 2;
  364. std::vector<llama_token> new_tokens(embd.begin(), embd.begin() + params.n_keep);
  365. new_tokens.insert(new_tokens.end(), embd.end() - n_left, embd.end());
  366. embd = new_tokens;
  367. n_past = params.n_keep;
  368. truncated = true;
  369. LOG_VERBOSE("input truncated", {
  370. {"n_ctx", params.n_ctx},
  371. {"n_keep", params.n_keep},
  372. {"n_left", n_left},
  373. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  374. });
  375. }
  376. while (n_past < embd.size())
  377. {
  378. int n_eval = (int)embd.size() - n_past;
  379. if (n_eval > params.n_batch)
  380. {
  381. n_eval = params.n_batch;
  382. }
  383. if (llama_eval(ctx, &embd[n_past], n_eval, n_past, params.n_threads))
  384. {
  385. LOG_ERROR("failed to eval", {
  386. {"n_eval", n_eval},
  387. {"n_past", n_past},
  388. {"n_threads", params.n_threads},
  389. {"embd", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend())},
  390. });
  391. has_next_token = false;
  392. return result;
  393. }
  394. n_past += n_eval;
  395. }
  396. if (params.n_predict == 0)
  397. {
  398. has_next_token = false;
  399. result.tok = llama_token_eos(ctx);
  400. return result;
  401. }
  402. // out of user input, sample next token
  403. const float temp = params.temp;
  404. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  405. const float top_p = params.top_p;
  406. const float tfs_z = params.tfs_z;
  407. const float typical_p = params.typical_p;
  408. const int32_t repeat_last_n = params.repeat_last_n < 0 ? params.n_ctx : params.repeat_last_n;
  409. const float repeat_penalty = params.repeat_penalty;
  410. const float alpha_presence = params.presence_penalty;
  411. const float alpha_frequency = params.frequency_penalty;
  412. const int mirostat = params.mirostat;
  413. const float mirostat_tau = params.mirostat_tau;
  414. const float mirostat_eta = params.mirostat_eta;
  415. const bool penalize_nl = params.penalize_nl;
  416. const int32_t n_probs = params.n_probs;
  417. {
  418. auto *logits = llama_get_logits(ctx);
  419. auto n_vocab = llama_n_vocab(ctx);
  420. // Apply params.logit_bias map
  421. for (const auto &it : params.logit_bias)
  422. {
  423. logits[it.first] += it.second;
  424. }
  425. std::vector<llama_token_data> candidates;
  426. candidates.reserve(n_vocab);
  427. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  428. {
  429. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  430. }
  431. llama_token_data_array candidates_p = {candidates.data(), candidates.size(), false};
  432. // Apply penalties
  433. float nl_logit = logits[llama_token_nl(ctx)];
  434. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), params.n_ctx);
  435. llama_sample_repetition_penalty(ctx, &candidates_p,
  436. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  437. last_n_repeat, repeat_penalty);
  438. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  439. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  440. last_n_repeat, alpha_frequency, alpha_presence);
  441. if (!penalize_nl)
  442. {
  443. logits[llama_token_nl(ctx)] = nl_logit;
  444. }
  445. if (grammar != nullptr) {
  446. llama_sample_grammar(ctx, &candidates_p, grammar);
  447. }
  448. if (temp <= 0)
  449. {
  450. // Greedy sampling
  451. result.tok = llama_sample_token_greedy(ctx, &candidates_p);
  452. if (n_probs > 0)
  453. {
  454. llama_sample_softmax(ctx, &candidates_p);
  455. }
  456. }
  457. else
  458. {
  459. if (mirostat == 1)
  460. {
  461. static float mirostat_mu = 2.0f * mirostat_tau;
  462. const int mirostat_m = 100;
  463. llama_sample_temperature(ctx, &candidates_p, temp);
  464. result.tok = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  465. }
  466. else if (mirostat == 2)
  467. {
  468. static float mirostat_mu = 2.0f * mirostat_tau;
  469. llama_sample_temperature(ctx, &candidates_p, temp);
  470. result.tok = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  471. }
  472. else
  473. {
  474. // Temperature sampling
  475. size_t min_keep = std::max(1, n_probs);
  476. llama_sample_top_k(ctx, &candidates_p, top_k, min_keep);
  477. llama_sample_tail_free(ctx, &candidates_p, tfs_z, min_keep);
  478. llama_sample_typical(ctx, &candidates_p, typical_p, min_keep);
  479. llama_sample_top_p(ctx, &candidates_p, top_p, min_keep);
  480. llama_sample_temperature(ctx, &candidates_p, temp);
  481. result.tok = llama_sample_token(ctx, &candidates_p);
  482. }
  483. }
  484. if (grammar != nullptr) {
  485. llama_grammar_accept_token(ctx, grammar, result.tok);
  486. }
  487. for (size_t i = 0; i < std::min(candidates_p.size, (size_t)n_probs); ++i)
  488. {
  489. result.probs.push_back({candidates_p.data[i].id, candidates_p.data[i].p});
  490. }
  491. last_n_tokens.erase(last_n_tokens.begin());
  492. last_n_tokens.push_back(result.tok);
  493. num_tokens_predicted++;
  494. }
  495. // add it to the context
  496. embd.push_back(result.tok);
  497. // decrement remaining sampling budget
  498. --n_remain;
  499. if (!embd.empty() && embd.back() == llama_token_eos(ctx))
  500. {
  501. // stopping_word = llama_token_to_str(ctx, embd.back());
  502. has_next_token = false;
  503. stopped_eos = true;
  504. LOG_VERBOSE("eos token found", {});
  505. return result;
  506. }
  507. has_next_token = params.n_predict == -1 || n_remain != 0;
  508. return result;
  509. }
  510. size_t findStoppingStrings(const std::string &text, const size_t last_token_size,
  511. const stop_type type)
  512. {
  513. size_t stop_pos = std::string::npos;
  514. for (const std::string &word : params.antiprompt)
  515. {
  516. size_t pos;
  517. if (type == STOP_FULL)
  518. {
  519. const size_t tmp = word.size() + last_token_size;
  520. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  521. pos = text.find(word, from_pos);
  522. }
  523. else
  524. {
  525. pos = find_partial_stop_string(word, text);
  526. }
  527. if (pos != std::string::npos &&
  528. (stop_pos == std::string::npos || pos < stop_pos))
  529. {
  530. if (type == STOP_FULL)
  531. {
  532. stopping_word = word;
  533. stopped_word = true;
  534. has_next_token = false;
  535. }
  536. stop_pos = pos;
  537. }
  538. }
  539. return stop_pos;
  540. }
  541. completion_token_output doCompletion()
  542. {
  543. const completion_token_output token_with_probs = nextToken();
  544. const std::string token_text = token_with_probs.tok == -1 ? "" : llama_token_to_str(ctx, token_with_probs.tok);
  545. generated_text += token_text;
  546. if (params.n_probs > 0)
  547. {
  548. generated_token_probs.push_back(token_with_probs);
  549. }
  550. if (multibyte_pending > 0)
  551. {
  552. multibyte_pending -= token_text.size();
  553. }
  554. else if (token_text.size() == 1)
  555. {
  556. const char c = token_text[0];
  557. // 2-byte characters: 110xxxxx 10xxxxxx
  558. if ((c & 0xE0) == 0xC0)
  559. {
  560. multibyte_pending = 1;
  561. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  562. }
  563. else if ((c & 0xF0) == 0xE0)
  564. {
  565. multibyte_pending = 2;
  566. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  567. }
  568. else if ((c & 0xF8) == 0xF0)
  569. {
  570. multibyte_pending = 3;
  571. }
  572. else
  573. {
  574. multibyte_pending = 0;
  575. }
  576. }
  577. if (multibyte_pending > 0 && !has_next_token)
  578. {
  579. has_next_token = true;
  580. n_remain++;
  581. }
  582. if (!has_next_token && n_remain == 0)
  583. {
  584. stopped_limit = true;
  585. }
  586. LOG_VERBOSE("next token", {
  587. {"token", token_with_probs.tok},
  588. {"token_text", tokens_to_output_formatted_string(ctx, token_with_probs.tok)},
  589. {"has_next_token", has_next_token},
  590. {"n_remain", n_remain},
  591. {"num_tokens_predicted", num_tokens_predicted},
  592. {"stopped_eos", stopped_eos},
  593. {"stopped_word", stopped_word},
  594. {"stopped_limit", stopped_limit},
  595. {"stopping_word", stopping_word},
  596. });
  597. return token_with_probs;
  598. }
  599. std::vector<float> getEmbedding()
  600. {
  601. static const int n_embd = llama_n_embd(ctx);
  602. if (!params.embedding)
  603. {
  604. LOG_WARNING("embedding disabled", {
  605. {"params.embedding", params.embedding},
  606. });
  607. return std::vector<float>(n_embd, 0.0f);
  608. }
  609. const float *data = llama_get_embeddings(ctx);
  610. std::vector<float> embedding(data, data + n_embd);
  611. return embedding;
  612. }
  613. };
  614. static void server_print_usage(const char *argv0, const gpt_params &params,
  615. const server_params &sparams)
  616. {
  617. fprintf(stdout, "usage: %s [options]\n", argv0);
  618. fprintf(stdout, "\n");
  619. fprintf(stdout, "options:\n");
  620. fprintf(stdout, " -h, --help show this help message and exit\n");
  621. fprintf(stdout, " -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  622. fprintf(stdout, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  623. fprintf(stdout, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  624. fprintf(stdout, " --rope-freq-base N RoPE base frequency (default: %.1f)\n", params.rope_freq_base);
  625. fprintf(stdout, " --rope-freq-scale N RoPE frequency scaling factor (default: %g)\n", params.rope_freq_scale);
  626. fprintf(stdout, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  627. fprintf(stdout, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  628. fprintf(stdout, " not recommended: doubles context memory required and no measurable increase in quality\n");
  629. if (llama_mlock_supported())
  630. {
  631. fprintf(stdout, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  632. }
  633. if (llama_mmap_supported())
  634. {
  635. fprintf(stdout, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  636. }
  637. fprintf(stdout, " --numa attempt optimizations that help on some NUMA systems\n");
  638. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  639. fprintf(stdout, " -ngl N, --n-gpu-layers N\n");
  640. fprintf(stdout, " number of layers to store in VRAM\n");
  641. fprintf(stdout, " -ts SPLIT --tensor-split SPLIT\n");
  642. fprintf(stdout, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  643. fprintf(stdout, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  644. fprintf(stdout, " -lv, --low-vram don't allocate VRAM scratch buffer\n");
  645. fprintf(stdout, " -nommq, --no-mul-mat-q\n");
  646. fprintf(stdout, " use cuBLAS instead of custom mul_mat_q CUDA kernels.\n");
  647. fprintf(stdout, " Not recommended since this is both slower and uses more VRAM.\n");
  648. #endif
  649. fprintf(stdout, " -m FNAME, --model FNAME\n");
  650. fprintf(stdout, " model path (default: %s)\n", params.model.c_str());
  651. fprintf(stdout, " -a ALIAS, --alias ALIAS\n");
  652. fprintf(stdout, " set an alias for the model, will be added as `model` field in completion response\n");
  653. fprintf(stdout, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  654. fprintf(stdout, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  655. fprintf(stdout, " --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  656. fprintf(stdout, " --port PORT port to listen (default (default: %d)\n", sparams.port);
  657. fprintf(stdout, " --path PUBLIC_PATH path from which to serve static files (default %s)\n", sparams.public_path.c_str());
  658. fprintf(stdout, " -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  659. fprintf(stdout, " --embedding enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  660. fprintf(stdout, "\n");
  661. }
  662. static void server_params_parse(int argc, char **argv, server_params &sparams,
  663. gpt_params &params)
  664. {
  665. gpt_params default_params;
  666. server_params default_sparams;
  667. std::string arg;
  668. bool invalid_param = false;
  669. for (int i = 1; i < argc; i++)
  670. {
  671. arg = argv[i];
  672. if (arg == "--port")
  673. {
  674. if (++i >= argc)
  675. {
  676. invalid_param = true;
  677. break;
  678. }
  679. sparams.port = std::stoi(argv[i]);
  680. }
  681. else if (arg == "--host")
  682. {
  683. if (++i >= argc)
  684. {
  685. invalid_param = true;
  686. break;
  687. }
  688. sparams.hostname = argv[i];
  689. }
  690. else if (arg == "--path")
  691. {
  692. if (++i >= argc)
  693. {
  694. invalid_param = true;
  695. break;
  696. }
  697. sparams.public_path = argv[i];
  698. }
  699. else if (arg == "--timeout" || arg == "-to")
  700. {
  701. if (++i >= argc)
  702. {
  703. invalid_param = true;
  704. break;
  705. }
  706. sparams.read_timeout = std::stoi(argv[i]);
  707. sparams.write_timeout = std::stoi(argv[i]);
  708. }
  709. else if (arg == "-m" || arg == "--model")
  710. {
  711. if (++i >= argc)
  712. {
  713. invalid_param = true;
  714. break;
  715. }
  716. params.model = argv[i];
  717. }
  718. else if (arg == "-a" || arg == "--alias")
  719. {
  720. if (++i >= argc)
  721. {
  722. invalid_param = true;
  723. break;
  724. }
  725. params.model_alias = argv[i];
  726. }
  727. else if (arg == "-h" || arg == "--help")
  728. {
  729. server_print_usage(argv[0], default_params, default_sparams);
  730. exit(0);
  731. }
  732. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  733. {
  734. if (++i >= argc)
  735. {
  736. invalid_param = true;
  737. break;
  738. }
  739. params.n_ctx = std::stoi(argv[i]);
  740. }
  741. else if (arg == "--rope-freq-base")
  742. {
  743. if (++i >= argc)
  744. {
  745. invalid_param = true;
  746. break;
  747. }
  748. params.rope_freq_base = std::stof(argv[i]);
  749. }
  750. else if (arg == "--rope-freq-scale")
  751. {
  752. if (++i >= argc)
  753. {
  754. invalid_param = true;
  755. break;
  756. }
  757. params.rope_freq_scale = std::stof(argv[i]);
  758. }
  759. else if (arg == "--memory-f32" || arg == "--memory_f32")
  760. {
  761. params.memory_f16 = false;
  762. }
  763. else if (arg == "--threads" || arg == "-t")
  764. {
  765. if (++i >= argc)
  766. {
  767. invalid_param = true;
  768. break;
  769. }
  770. params.n_threads = std::stoi(argv[i]);
  771. }
  772. else if (arg == "-b" || arg == "--batch-size")
  773. {
  774. if (++i >= argc)
  775. {
  776. invalid_param = true;
  777. break;
  778. }
  779. params.n_batch = std::stoi(argv[i]);
  780. params.n_batch = std::min(512, params.n_batch);
  781. }
  782. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  783. {
  784. if (++i >= argc)
  785. {
  786. invalid_param = true;
  787. break;
  788. }
  789. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  790. params.n_gpu_layers = std::stoi(argv[i]);
  791. #else
  792. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  793. "See main README.md for information on enabling GPU BLAS support",
  794. {{"n_gpu_layers", params.n_gpu_layers}});
  795. #endif
  796. }
  797. else if (arg == "--tensor-split" || arg == "-ts")
  798. {
  799. if (++i >= argc)
  800. {
  801. invalid_param = true;
  802. break;
  803. }
  804. #ifdef GGML_USE_CUBLAS
  805. std::string arg_next = argv[i];
  806. // split string by , and /
  807. const std::regex regex{R"([,/]+)"};
  808. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  809. std::vector<std::string> split_arg{it, {}};
  810. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  811. for (size_t i_device = 0; i_device < LLAMA_MAX_DEVICES; ++i_device)
  812. {
  813. if (i_device < split_arg.size())
  814. {
  815. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  816. }
  817. else
  818. {
  819. params.tensor_split[i_device] = 0.0f;
  820. }
  821. }
  822. #else
  823. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n", {});
  824. #endif // GGML_USE_CUBLAS
  825. }
  826. else if (arg == "--low-vram" || arg == "-lv")
  827. {
  828. #ifdef GGML_USE_CUBLAS
  829. params.low_vram = true;
  830. #else
  831. LOG_WARNING("warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n", {});
  832. #endif // GGML_USE_CUBLAS
  833. }
  834. else if (arg == "--no-mul-mat-q" || arg == "-nommq")
  835. {
  836. #ifdef GGML_USE_CUBLAS
  837. params.mul_mat_q = false;
  838. #else
  839. LOG_WARNING("warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n", {});
  840. #endif // GGML_USE_CUBLAS
  841. }
  842. else if (arg == "--main-gpu" || arg == "-mg")
  843. {
  844. if (++i >= argc)
  845. {
  846. invalid_param = true;
  847. break;
  848. }
  849. #ifdef GGML_USE_CUBLAS
  850. params.main_gpu = std::stoi(argv[i]);
  851. #else
  852. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  853. #endif
  854. }
  855. else if (arg == "--lora")
  856. {
  857. if (++i >= argc)
  858. {
  859. invalid_param = true;
  860. break;
  861. }
  862. params.lora_adapter = argv[i];
  863. params.use_mmap = false;
  864. }
  865. else if (arg == "--lora-base")
  866. {
  867. if (++i >= argc)
  868. {
  869. invalid_param = true;
  870. break;
  871. }
  872. params.lora_base = argv[i];
  873. }
  874. else if (arg == "-v" || arg == "--verbose")
  875. {
  876. #if SERVER_VERBOSE != 1
  877. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  878. #else
  879. server_verbose = true;
  880. #endif
  881. }
  882. else if (arg == "--mlock")
  883. {
  884. params.use_mlock = true;
  885. }
  886. else if (arg == "--no-mmap")
  887. {
  888. params.use_mmap = false;
  889. }
  890. else if (arg == "--numa")
  891. {
  892. params.numa = true;
  893. }
  894. else if (arg == "--embedding")
  895. {
  896. params.embedding = true;
  897. }
  898. else
  899. {
  900. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  901. server_print_usage(argv[0], default_params, default_sparams);
  902. exit(1);
  903. }
  904. }
  905. if (invalid_param)
  906. {
  907. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  908. server_print_usage(argv[0], default_params, default_sparams);
  909. exit(1);
  910. }
  911. }
  912. static json format_generation_settings(llama_server_context &llama)
  913. {
  914. const auto eos_bias = llama.params.logit_bias.find(llama_token_eos(llama.ctx));
  915. const bool ignore_eos = eos_bias != llama.params.logit_bias.end() &&
  916. eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  917. return json{
  918. {"n_ctx", llama.params.n_ctx},
  919. {"model", llama.params.model_alias},
  920. {"seed", llama.params.seed},
  921. {"temp", llama.params.temp},
  922. {"top_k", llama.params.top_k},
  923. {"top_p", llama.params.top_p},
  924. {"tfs_z", llama.params.tfs_z},
  925. {"typical_p", llama.params.typical_p},
  926. {"repeat_last_n", llama.params.repeat_last_n},
  927. {"repeat_penalty", llama.params.repeat_penalty},
  928. {"presence_penalty", llama.params.presence_penalty},
  929. {"frequency_penalty", llama.params.frequency_penalty},
  930. {"mirostat", llama.params.mirostat},
  931. {"mirostat_tau", llama.params.mirostat_tau},
  932. {"mirostat_eta", llama.params.mirostat_eta},
  933. {"penalize_nl", llama.params.penalize_nl},
  934. {"stop", llama.params.antiprompt},
  935. {"n_predict", llama.params.n_predict},
  936. {"n_keep", llama.params.n_keep},
  937. {"ignore_eos", ignore_eos},
  938. {"stream", llama.stream},
  939. {"logit_bias", llama.params.logit_bias},
  940. {"n_probs", llama.params.n_probs},
  941. {"grammar", llama.params.grammar},
  942. };
  943. }
  944. static json format_embedding_response(llama_server_context &llama)
  945. {
  946. return json{
  947. {"embedding", llama.getEmbedding()},
  948. };
  949. }
  950. static json format_timings(llama_server_context &llama)
  951. {
  952. const auto timings = llama_get_timings(llama.ctx);
  953. assert(timings.n_eval == llama.num_tokens_predicted);
  954. return json{
  955. {"prompt_n", timings.n_p_eval},
  956. {"prompt_ms", timings.t_p_eval_ms},
  957. {"prompt_per_token_ms", timings.t_p_eval_ms / timings.n_p_eval},
  958. {"prompt_per_second", 1e3 / timings.t_p_eval_ms * timings.n_p_eval},
  959. {"predicted_n", timings.n_eval},
  960. {"predicted_ms", timings.t_eval_ms},
  961. {"predicted_per_token_ms", timings.t_eval_ms / timings.n_eval},
  962. {"predicted_per_second", 1e3 / timings.t_eval_ms * timings.n_eval},
  963. };
  964. }
  965. static json format_final_response(llama_server_context &llama, const std::string &content, const std::vector<completion_token_output> &probs)
  966. {
  967. json res = json{
  968. {"content", content},
  969. {"stop", true},
  970. {"model", llama.params.model_alias},
  971. {"tokens_predicted", llama.num_tokens_predicted},
  972. {"tokens_evaluated", llama.num_prompt_tokens},
  973. {"generation_settings", format_generation_settings(llama)},
  974. {"prompt", llama.prompt},
  975. {"truncated", llama.truncated},
  976. {"stopped_eos", llama.stopped_eos},
  977. {"stopped_word", llama.stopped_word},
  978. {"stopped_limit", llama.stopped_limit},
  979. {"stopping_word", llama.stopping_word},
  980. {"tokens_cached", llama.n_past},
  981. {"timings", format_timings(llama)},
  982. };
  983. if (llama.params.n_probs > 0)
  984. {
  985. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  986. }
  987. return res;
  988. }
  989. static json format_partial_response(llama_server_context &llama, const std::string &content, const std::vector<completion_token_output> &probs)
  990. {
  991. json res = json{
  992. {"content", content},
  993. {"stop", false},
  994. };
  995. if (llama.params.n_probs > 0)
  996. {
  997. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  998. }
  999. return res;
  1000. }
  1001. static json format_tokenizer_response(const std::vector<llama_token> &tokens)
  1002. {
  1003. return json{
  1004. {"tokens", tokens}};
  1005. }
  1006. static json format_detokenized_response(std::string content)
  1007. {
  1008. return json{
  1009. {"content", content}};
  1010. }
  1011. template <typename T>
  1012. static T json_value(const json &body, const std::string &key, const T &default_value)
  1013. {
  1014. // Fallback null to default value
  1015. return body.contains(key) && !body.at(key).is_null()
  1016. ? body.value(key, default_value)
  1017. : default_value;
  1018. }
  1019. static void parse_options_completion(const json &body, llama_server_context &llama)
  1020. {
  1021. gpt_params default_params;
  1022. llama.stream = json_value(body, "stream", false);
  1023. llama.params.n_predict = json_value(body, "n_predict", default_params.n_predict);
  1024. llama.params.top_k = json_value(body, "top_k", default_params.top_k);
  1025. llama.params.top_p = json_value(body, "top_p", default_params.top_p);
  1026. llama.params.tfs_z = json_value(body, "tfs_z", default_params.tfs_z);
  1027. llama.params.typical_p = json_value(body, "typical_p", default_params.typical_p);
  1028. llama.params.repeat_last_n = json_value(body, "repeat_last_n", default_params.repeat_last_n);
  1029. llama.params.temp = json_value(body, "temperature", default_params.temp);
  1030. llama.params.repeat_penalty = json_value(body, "repeat_penalty", default_params.repeat_penalty);
  1031. llama.params.presence_penalty = json_value(body, "presence_penalty", default_params.presence_penalty);
  1032. llama.params.frequency_penalty = json_value(body, "frequency_penalty", default_params.frequency_penalty);
  1033. llama.params.mirostat = json_value(body, "mirostat", default_params.mirostat);
  1034. llama.params.mirostat_tau = json_value(body, "mirostat_tau", default_params.mirostat_tau);
  1035. llama.params.mirostat_eta = json_value(body, "mirostat_eta", default_params.mirostat_eta);
  1036. llama.params.penalize_nl = json_value(body, "penalize_nl", default_params.penalize_nl);
  1037. llama.params.n_keep = json_value(body, "n_keep", default_params.n_keep);
  1038. llama.params.seed = json_value(body, "seed", default_params.seed);
  1039. llama.params.grammar = json_value(body, "grammar", default_params.grammar);
  1040. llama.params.n_probs = json_value(body, "n_probs", default_params.n_probs);
  1041. if (body.count("prompt") != 0)
  1042. {
  1043. llama.prompt = body["prompt"];
  1044. }
  1045. else
  1046. {
  1047. llama.prompt = "";
  1048. }
  1049. llama.params.logit_bias.clear();
  1050. if (json_value(body, "ignore_eos", false))
  1051. {
  1052. llama.params.logit_bias[llama_token_eos(llama.ctx)] = -INFINITY;
  1053. }
  1054. const auto &logit_bias = body.find("logit_bias");
  1055. if (logit_bias != body.end() && logit_bias->is_array())
  1056. {
  1057. const int n_vocab = llama_n_vocab(llama.ctx);
  1058. for (const auto &el : *logit_bias)
  1059. {
  1060. if (el.is_array() && el.size() == 2 && el[0].is_number_integer())
  1061. {
  1062. llama_token tok = el[0].get<llama_token>();
  1063. if (tok >= 0 && tok < n_vocab)
  1064. {
  1065. if (el[1].is_number())
  1066. {
  1067. llama.params.logit_bias[tok] = el[1].get<float>();
  1068. }
  1069. else if (el[1].is_boolean() && !el[1].get<bool>())
  1070. {
  1071. llama.params.logit_bias[tok] = -INFINITY;
  1072. }
  1073. }
  1074. }
  1075. }
  1076. }
  1077. llama.params.antiprompt.clear();
  1078. const auto &stop = body.find("stop");
  1079. if (stop != body.end() && stop->is_array())
  1080. {
  1081. for (const auto &word : *stop)
  1082. {
  1083. if (!word.empty())
  1084. {
  1085. llama.params.antiprompt.push_back(word);
  1086. }
  1087. }
  1088. }
  1089. LOG_VERBOSE("completion parameters parsed", format_generation_settings(llama));
  1090. }
  1091. static void log_server_request(const Request &req, const Response &res)
  1092. {
  1093. LOG_INFO("request", {
  1094. {"remote_addr", req.remote_addr},
  1095. {"remote_port", req.remote_port},
  1096. {"status", res.status},
  1097. {"method", req.method},
  1098. {"path", req.path},
  1099. {"params", req.params},
  1100. });
  1101. LOG_VERBOSE("request", {
  1102. {"request", req.body},
  1103. {"response", res.body},
  1104. });
  1105. }
  1106. bool is_at_eob(llama_server_context & server_context, const llama_token * tokens, const size_t n_tokens) {
  1107. return n_tokens && tokens[n_tokens-1] == llama_token_eos(server_context.ctx);
  1108. }
  1109. // Function matching type llama_beam_search_callback_fn_t.
  1110. // Custom callback example is called each time the beams lengths increase:
  1111. // * Show progress by printing ',' following by number of convergent beam tokens if any.
  1112. // * When all beams converge to a common prefix, they are made available in beams_state.beams[0].
  1113. // This is also called when the stop condition is met.
  1114. // Collect tokens into std::vector<llama_token> response which is pointed to by callback_data.
  1115. void beam_search_callback(void * callback_data, llama_beams_state beams_state) {
  1116. auto & llama = *static_cast<llama_server_context*>(callback_data);
  1117. // Mark beams as EOS as needed.
  1118. for (size_t i = 0 ; i < beams_state.n_beams ; ++i) {
  1119. llama_beam_view& beam_view = beams_state.beam_views[i];
  1120. if (!beam_view.eob && is_at_eob(llama, beam_view.tokens, beam_view.n_tokens)) {
  1121. beam_view.eob = true;
  1122. }
  1123. }
  1124. printf(","); // Show progress
  1125. if (const size_t n = beams_state.common_prefix_length) {
  1126. llama.generated_token_probs.resize(llama.generated_token_probs.size() + n);
  1127. assert(0u < beams_state.n_beams);
  1128. const llama_token * tokens = beams_state.beam_views[0].tokens;
  1129. const auto map = [](llama_token tok) { return completion_token_output{{},tok}; };
  1130. std::transform(tokens, tokens + n, llama.generated_token_probs.end() - n, map);
  1131. printf("%lu", n);
  1132. }
  1133. fflush(stdout);
  1134. #if 0 // DEBUG: print current beams for this iteration
  1135. std::cout << "\n\nCurrent beams:\n";
  1136. for (size_t i=0 ; i < beams_state.n_beams ; ++i) {
  1137. std::cout << "beams["<<i<<"]: " << ostream_beam_view{state.ctx,beams_state.beam_views[i]} << std::endl;
  1138. }
  1139. #endif
  1140. }
  1141. struct token_translator {
  1142. llama_context * ctx;
  1143. std::string operator()(llama_token tok) const { return llama_token_to_str(ctx, tok); }
  1144. std::string operator()(completion_token_output cto) const { return (*this)(cto.tok); }
  1145. };
  1146. void append_to_generated_text_from_generated_token_probs(llama_server_context & llama) {
  1147. auto & gtps = llama.generated_token_probs;
  1148. auto translator = token_translator{llama.ctx};
  1149. auto add_strlen = [=](size_t sum, const completion_token_output & cto) { return sum + translator(cto).size(); };
  1150. const size_t len = std::accumulate(gtps.begin(), gtps.end(), size_t(0), add_strlen);
  1151. if (llama.generated_text.capacity() < llama.generated_text.size() + len) {
  1152. llama.generated_text.reserve(llama.generated_text.size() + len);
  1153. }
  1154. for (const completion_token_output & cto : gtps) {
  1155. llama.generated_text += translator(cto);
  1156. }
  1157. }
  1158. int main(int argc, char **argv)
  1159. {
  1160. // own arguments required by this example
  1161. gpt_params params;
  1162. server_params sparams;
  1163. // struct that contains llama context and inference
  1164. llama_server_context llama;
  1165. server_params_parse(argc, argv, sparams, params);
  1166. if (params.model_alias == "unknown")
  1167. {
  1168. params.model_alias = params.model;
  1169. }
  1170. llama_backend_init(params.numa);
  1171. LOG_INFO("build info", {{"build", BUILD_NUMBER},
  1172. {"commit", BUILD_COMMIT}});
  1173. LOG_INFO("system info", {
  1174. {"n_threads", params.n_threads},
  1175. {"total_threads", std::thread::hardware_concurrency()},
  1176. {"system_info", llama_print_system_info()},
  1177. });
  1178. // load the model
  1179. if (!llama.loadModel(params))
  1180. {
  1181. return 1;
  1182. }
  1183. Server svr;
  1184. svr.set_default_headers({{"Server", "llama.cpp"},
  1185. {"Access-Control-Allow-Origin", "*"},
  1186. {"Access-Control-Allow-Headers", "content-type"}});
  1187. // this is only called if no index.html is found in the public --path
  1188. svr.Get("/", [](const Request &, Response &res)
  1189. {
  1190. res.set_content(reinterpret_cast<const char*>(&index_html), index_html_len, "text/html");
  1191. return false; });
  1192. // this is only called if no index.js is found in the public --path
  1193. svr.Get("/index.js", [](const Request &, Response &res)
  1194. {
  1195. res.set_content(reinterpret_cast<const char *>(&index_js), index_js_len, "text/javascript");
  1196. return false; });
  1197. // this is only called if no index.html is found in the public --path
  1198. svr.Get("/completion.js", [](const Request &, Response &res)
  1199. {
  1200. res.set_content(reinterpret_cast<const char*>(&completion_js), completion_js_len, "application/javascript");
  1201. return false; });
  1202. // this is only called if no index.html is found in the public --path
  1203. svr.Get("/json-schema-to-grammar.mjs", [](const Request &, Response &res)
  1204. {
  1205. res.set_content(reinterpret_cast<const char*>(&json_schema_to_grammar_mjs), json_schema_to_grammar_mjs_len, "application/javascript");
  1206. return false; });
  1207. svr.Post("/completion", [&llama](const Request &req, Response &res)
  1208. {
  1209. auto lock = llama.lock();
  1210. llama.rewind();
  1211. llama_reset_timings(llama.ctx);
  1212. parse_options_completion(json::parse(req.body), llama);
  1213. if (!llama.loadGrammar())
  1214. {
  1215. res.status = 400;
  1216. return;
  1217. }
  1218. llama.loadPrompt();
  1219. llama.beginCompletion();
  1220. if (!llama.stream) {
  1221. if (llama.params.n_beams) {
  1222. // Fill llama.generated_token_probs vector with final beam.
  1223. llama_beam_search(llama.ctx, beam_search_callback, &llama, llama.params.n_beams,
  1224. llama.n_past, llama.n_remain, llama.params.n_threads);
  1225. // Translate llama.generated_token_probs to llama.generated_text.
  1226. append_to_generated_text_from_generated_token_probs(llama);
  1227. } else {
  1228. size_t stop_pos = std::string::npos;
  1229. while (llama.has_next_token) {
  1230. const completion_token_output token_with_probs = llama.doCompletion();
  1231. const std::string token_text = token_with_probs.tok == -1 ? "" : llama_token_to_str(llama.ctx, token_with_probs.tok);
  1232. stop_pos = llama.findStoppingStrings(llama.generated_text,
  1233. token_text.size(), STOP_FULL);
  1234. }
  1235. if (stop_pos == std::string::npos) {
  1236. stop_pos = llama.findStoppingStrings(llama.generated_text, 0, STOP_PARTIAL);
  1237. }
  1238. if (stop_pos != std::string::npos) {
  1239. llama.generated_text.erase(llama.generated_text.begin() + stop_pos,
  1240. llama.generated_text.end());
  1241. }
  1242. }
  1243. const json data = format_final_response(llama, llama.generated_text, llama.generated_token_probs);
  1244. llama_print_timings(llama.ctx);
  1245. res.set_content(data.dump(-1, ' ', false, json::error_handler_t::replace),
  1246. "application/json");
  1247. } else {
  1248. const auto chunked_content_provider = [&](size_t, DataSink & sink) {
  1249. size_t sent_count = 0;
  1250. size_t sent_token_probs_index = 0;
  1251. while (llama.has_next_token) {
  1252. const completion_token_output token_with_probs = llama.doCompletion();
  1253. if (token_with_probs.tok == -1 || llama.multibyte_pending > 0) {
  1254. continue;
  1255. }
  1256. const std::string token_text = llama_token_to_str(llama.ctx, token_with_probs.tok);
  1257. size_t pos = std::min(sent_count, llama.generated_text.size());
  1258. const std::string str_test = llama.generated_text.substr(pos);
  1259. bool is_stop_full = false;
  1260. size_t stop_pos =
  1261. llama.findStoppingStrings(str_test, token_text.size(), STOP_FULL);
  1262. if (stop_pos != std::string::npos) {
  1263. is_stop_full = true;
  1264. llama.generated_text.erase(
  1265. llama.generated_text.begin() + pos + stop_pos,
  1266. llama.generated_text.end());
  1267. pos = std::min(sent_count, llama.generated_text.size());
  1268. } else {
  1269. is_stop_full = false;
  1270. stop_pos = llama.findStoppingStrings(str_test, token_text.size(),
  1271. STOP_PARTIAL);
  1272. }
  1273. if (
  1274. stop_pos == std::string::npos ||
  1275. // Send rest of the text if we are at the end of the generation
  1276. (!llama.has_next_token && !is_stop_full && stop_pos > 0)
  1277. ) {
  1278. const std::string to_send = llama.generated_text.substr(pos, std::string::npos);
  1279. sent_count += to_send.size();
  1280. std::vector<completion_token_output> probs_output = {};
  1281. if (llama.params.n_probs > 0) {
  1282. const std::vector<llama_token> to_send_toks = llama_tokenize(llama.ctx, to_send, false);
  1283. size_t probs_pos = std::min(sent_token_probs_index, llama.generated_token_probs.size());
  1284. size_t probs_stop_pos = std::min(sent_token_probs_index + to_send_toks.size(), llama.generated_token_probs.size());
  1285. if (probs_pos < probs_stop_pos) {
  1286. probs_output = std::vector<completion_token_output>(llama.generated_token_probs.begin() + probs_pos, llama.generated_token_probs.begin() + probs_stop_pos);
  1287. }
  1288. sent_token_probs_index = probs_stop_pos;
  1289. }
  1290. const json data = format_partial_response(llama, to_send, probs_output);
  1291. const std::string str =
  1292. "data: " +
  1293. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  1294. "\n\n";
  1295. LOG_VERBOSE("data stream", {
  1296. { "to_send", str }
  1297. });
  1298. if (!sink.write(str.data(), str.size())) {
  1299. LOG_VERBOSE("stream closed", {});
  1300. llama_print_timings(llama.ctx);
  1301. return false;
  1302. }
  1303. }
  1304. if (!llama.has_next_token) {
  1305. // Generation is done, send extra information.
  1306. const json data = format_final_response(llama, "", llama.generated_token_probs);
  1307. const std::string str =
  1308. "data: " +
  1309. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  1310. "\n\n";
  1311. LOG_VERBOSE("data stream", {
  1312. { "to_send", str }
  1313. });
  1314. if (!sink.write(str.data(), str.size())) {
  1315. LOG_VERBOSE("stream closed", {});
  1316. llama_print_timings(llama.ctx);
  1317. return false;
  1318. }
  1319. }
  1320. }
  1321. llama_print_timings(llama.ctx);
  1322. sink.done();
  1323. return true;
  1324. };
  1325. const auto on_complete = [&](bool) {
  1326. llama.mutex.unlock();
  1327. };
  1328. lock.release();
  1329. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  1330. } });
  1331. svr.Get("/model.json", [&llama](const Request &, Response &res)
  1332. {
  1333. const json data = format_generation_settings(llama);
  1334. return res.set_content(data.dump(), "application/json"); });
  1335. svr.Options(R"(/.*)", [](const Request &, Response &res)
  1336. { return res.set_content("", "application/json"); });
  1337. svr.Post("/tokenize", [&llama](const Request &req, Response &res)
  1338. {
  1339. auto lock = llama.lock();
  1340. const json body = json::parse(req.body);
  1341. std::vector<llama_token> tokens;
  1342. if (body.count("content") != 0)
  1343. {
  1344. tokens = llama.tokenize(body["content"], false);
  1345. }
  1346. const json data = format_tokenizer_response(tokens);
  1347. return res.set_content(data.dump(), "application/json"); });
  1348. svr.Post("/detokenize", [&llama](const Request &req, Response &res)
  1349. {
  1350. auto lock = llama.lock();
  1351. const json body = json::parse(req.body);
  1352. std::string content;
  1353. if (body.count("tokens") != 0)
  1354. {
  1355. const std::vector<llama_token> tokens = body["tokens"];
  1356. content = tokens_to_str(llama.ctx, tokens.cbegin(), tokens.cend());
  1357. }
  1358. const json data = format_detokenized_response(content);
  1359. return res.set_content(data.dump(), "application/json"); });
  1360. svr.Post("/embedding", [&llama](const Request &req, Response &res)
  1361. {
  1362. auto lock = llama.lock();
  1363. const json body = json::parse(req.body);
  1364. llama.rewind();
  1365. llama_reset_timings(llama.ctx);
  1366. if (body.count("content") != 0)
  1367. {
  1368. llama.prompt = body["content"];
  1369. }
  1370. else
  1371. {
  1372. llama.prompt = "";
  1373. }
  1374. llama.params.n_predict = 0;
  1375. llama.loadPrompt();
  1376. llama.beginCompletion();
  1377. llama.doCompletion();
  1378. const json data = format_embedding_response(llama);
  1379. return res.set_content(data.dump(), "application/json"); });
  1380. svr.set_logger(log_server_request);
  1381. svr.set_exception_handler([](const Request &, Response &res, std::exception_ptr ep)
  1382. {
  1383. const auto * fmt = "500 Internal Server Error\n%s";
  1384. char buf[BUFSIZ];
  1385. try {
  1386. std::rethrow_exception(std::move(ep));
  1387. } catch (std::exception & e) {
  1388. snprintf(buf, sizeof(buf), fmt, e.what());
  1389. } catch (...) {
  1390. snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
  1391. }
  1392. res.set_content(buf, "text/plain");
  1393. res.status = 500; });
  1394. svr.set_error_handler([](const Request &, Response &res)
  1395. {
  1396. if (res.status == 400) {
  1397. res.set_content("Invalid request", "text/plain");
  1398. } else if (res.status != 500) {
  1399. res.set_content("File Not Found", "text/plain");
  1400. res.status = 404;
  1401. } });
  1402. // set timeouts and change hostname and port
  1403. svr.set_read_timeout(sparams.read_timeout);
  1404. svr.set_write_timeout(sparams.write_timeout);
  1405. if (!svr.bind_to_port(sparams.hostname, sparams.port))
  1406. {
  1407. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  1408. return 1;
  1409. }
  1410. // Set the base directory for serving static files
  1411. svr.set_base_dir(sparams.public_path);
  1412. // to make it ctrl+clickable:
  1413. fprintf(stdout, "\nllama server listening at http://%s:%d\n\n", sparams.hostname.c_str(), sparams.port);
  1414. LOG_INFO("HTTP server listening", {
  1415. {"hostname", sparams.hostname},
  1416. {"port", sparams.port},
  1417. });
  1418. if (!svr.listen_after_bind())
  1419. {
  1420. return 1;
  1421. }
  1422. if (llama.grammar != nullptr) {
  1423. llama_grammar_free(llama.grammar);
  1424. }
  1425. llama_backend_free();
  1426. return 0;
  1427. }