server.cpp 51 KB

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