1
0

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