1
0

server.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include "grammar-parser.h"
  5. #ifndef NDEBUG
  6. // crash the server in debug mode, otherwise send an http 500 error
  7. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  8. #endif
  9. #include "httplib.h"
  10. #include "json.hpp"
  11. // auto generated files (update with ./deps.sh)
  12. #include "index.html.hpp"
  13. #include "index.js.hpp"
  14. #include "completion.js.hpp"
  15. #include "json-schema-to-grammar.mjs.hpp"
  16. #ifndef SERVER_VERBOSE
  17. #define SERVER_VERBOSE 1
  18. #endif
  19. using namespace httplib;
  20. using json = nlohmann::json;
  21. struct server_params
  22. {
  23. std::string hostname = "127.0.0.1";
  24. std::string public_path = "examples/server/public";
  25. int32_t port = 8080;
  26. int32_t read_timeout = 600;
  27. int32_t write_timeout = 600;
  28. };
  29. // completion token output with probabilities
  30. struct completion_token_output
  31. {
  32. struct token_prob
  33. {
  34. llama_token tok;
  35. float prob;
  36. };
  37. std::vector<token_prob> probs;
  38. llama_token tok;
  39. };
  40. static size_t common_part(const std::vector<llama_token> &a, const std::vector<llama_token> &b)
  41. {
  42. size_t i;
  43. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++)
  44. {
  45. }
  46. return i;
  47. }
  48. enum stop_type
  49. {
  50. STOP_FULL,
  51. STOP_PARTIAL,
  52. };
  53. static bool ends_with(const std::string &str, const std::string &suffix)
  54. {
  55. return str.size() >= suffix.size() &&
  56. 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  57. }
  58. static size_t find_partial_stop_string(const std::string &stop,
  59. const std::string &text)
  60. {
  61. if (!text.empty() && !stop.empty())
  62. {
  63. const char text_last_char = text.back();
  64. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--)
  65. {
  66. if (stop[char_index] == text_last_char)
  67. {
  68. const std::string current_partial = stop.substr(0, char_index + 1);
  69. if (ends_with(text, current_partial))
  70. {
  71. return text.size() - char_index - 1;
  72. }
  73. }
  74. }
  75. }
  76. return std::string::npos;
  77. }
  78. template <class Iter>
  79. static std::string tokens_to_str(llama_context *ctx, Iter begin, Iter end)
  80. {
  81. std::string ret;
  82. for (; begin != end; ++begin)
  83. {
  84. ret += llama_token_to_str(ctx, *begin);
  85. }
  86. return ret;
  87. }
  88. static void server_log(const char *level, const char *function, int line,
  89. const char *message, const nlohmann::ordered_json &extra)
  90. {
  91. nlohmann::ordered_json log{
  92. {"timestamp", time(nullptr)},
  93. {"level", level},
  94. {"function", function},
  95. {"line", line},
  96. {"message", message},
  97. };
  98. if (!extra.empty())
  99. {
  100. log.merge_patch(extra);
  101. }
  102. const std::string str = log.dump(-1, ' ', false, json::error_handler_t::replace);
  103. fprintf(stdout, "%.*s\n", (int)str.size(), str.data());
  104. fflush(stdout);
  105. }
  106. // format incomplete utf-8 multibyte character for output
  107. static std::string tokens_to_output_formatted_string(const llama_context *ctx, const llama_token token)
  108. {
  109. std::string out = token == -1 ? "" : llama_token_to_str(ctx, token);
  110. // if first bit is 1, meaning it's a partial character
  111. if (out.size() > 0 && (out[0] & 0x80) == 0x80)
  112. {
  113. std::stringstream ss;
  114. ss << std::hex << (out[0] & 0xff);
  115. std::string res(ss.str());
  116. out = "byte: \\x" + res;
  117. }
  118. return out;
  119. }
  120. // convert a vector of completion_token_output to json
  121. static json probs_vector_to_json(const llama_context *ctx, const std::vector<completion_token_output> probs)
  122. {
  123. json out = json::array();
  124. for (const auto &prob : probs)
  125. {
  126. json probs_for_token = json::array();
  127. for (const auto &p : prob.probs)
  128. {
  129. std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  130. probs_for_token.push_back(json{
  131. {"tok_str", tok_str},
  132. {"prob", p.prob},
  133. });
  134. }
  135. std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  136. out.push_back(json{
  137. {"content", tok_str},
  138. {"probs", probs_for_token},
  139. });
  140. }
  141. return out;
  142. }
  143. static bool server_verbose = false;
  144. #if SERVER_VERBOSE != 1
  145. #define LOG_VERBOSE(MSG, ...)
  146. #else
  147. #define LOG_VERBOSE(MSG, ...) \
  148. do \
  149. { \
  150. if (server_verbose) \
  151. { \
  152. server_log("VERBOSE", __func__, __LINE__, MSG, __VA_ARGS__); \
  153. } \
  154. } while (0)
  155. #endif
  156. #define LOG_ERROR(MSG, ...) server_log("ERROR", __func__, __LINE__, MSG, __VA_ARGS__)
  157. #define LOG_WARNING(MSG, ...) server_log("WARNING", __func__, __LINE__, MSG, __VA_ARGS__)
  158. #define LOG_INFO(MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  159. struct llama_server_context
  160. {
  161. bool stream = false;
  162. bool has_next_token = false;
  163. std::string generated_text;
  164. std::vector<completion_token_output> generated_token_probs;
  165. size_t num_prompt_tokens = 0;
  166. size_t num_tokens_predicted = 0;
  167. size_t n_past = 0;
  168. size_t n_remain = 0;
  169. std::vector<llama_token> embd;
  170. std::vector<llama_token> last_n_tokens;
  171. llama_model *model = nullptr;
  172. llama_context *ctx = nullptr;
  173. gpt_params params;
  174. grammar_parser::parse_state parsed_grammar;
  175. llama_grammar *grammar = nullptr;
  176. bool truncated = false;
  177. bool stopped_eos = false;
  178. bool stopped_word = false;
  179. bool stopped_limit = false;
  180. std::string stopping_word;
  181. int32_t multibyte_pending = 0;
  182. std::mutex mutex;
  183. std::unique_lock<std::mutex> lock()
  184. {
  185. return std::unique_lock<std::mutex>(mutex);
  186. }
  187. ~llama_server_context()
  188. {
  189. if (ctx)
  190. {
  191. llama_free(ctx);
  192. ctx = nullptr;
  193. }
  194. if (model)
  195. {
  196. llama_free_model(model);
  197. model = nullptr;
  198. }
  199. }
  200. void rewind()
  201. {
  202. params.antiprompt.clear();
  203. params.grammar.clear();
  204. num_prompt_tokens = 0;
  205. num_tokens_predicted = 0;
  206. generated_text = "";
  207. generated_text.reserve(params.n_ctx);
  208. generated_token_probs.clear();
  209. truncated = false;
  210. stopped_eos = false;
  211. stopped_word = false;
  212. stopped_limit = false;
  213. stopping_word = "";
  214. multibyte_pending = 0;
  215. n_remain = 0;
  216. n_past = 0;
  217. if (grammar != nullptr) {
  218. llama_grammar_free(grammar);
  219. grammar = nullptr;
  220. }
  221. }
  222. bool loadModel(const gpt_params &params_)
  223. {
  224. params = params_;
  225. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  226. if (model == nullptr)
  227. {
  228. LOG_ERROR("unable to load model", {{"model", params_.model}});
  229. return false;
  230. }
  231. last_n_tokens.resize(params.n_ctx);
  232. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  233. return true;
  234. }
  235. bool loadGrammar()
  236. {
  237. if (!params.grammar.empty()) {
  238. parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  239. // will be empty (default) if there are parse errors
  240. if (parsed_grammar.rules.empty()) {
  241. LOG_ERROR("grammar parse error", {{"grammar", params.grammar}});
  242. return false;
  243. }
  244. grammar_parser::print_grammar(stderr, parsed_grammar);
  245. {
  246. auto it = params.logit_bias.find(llama_token_eos(ctx));
  247. if (it != params.logit_bias.end() && it->second == -INFINITY) {
  248. LOG_WARNING("EOS token is disabled, which will cause most grammars to fail", {});
  249. }
  250. }
  251. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  252. grammar = llama_grammar_init(
  253. grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
  254. }
  255. return true;
  256. }
  257. void loadPrompt()
  258. {
  259. params.prompt.insert(0, 1, ' '); // always add a first space
  260. std::vector<llama_token> prompt_tokens = ::llama_tokenize(ctx, params.prompt, true);
  261. num_prompt_tokens = prompt_tokens.size();
  262. if (params.n_keep < 0)
  263. {
  264. params.n_keep = (int)num_prompt_tokens;
  265. }
  266. params.n_keep = std::min(params.n_ctx - 4, params.n_keep);
  267. // if input prompt is too big, truncate like normal
  268. if (num_prompt_tokens >= (size_t)params.n_ctx)
  269. {
  270. const int n_left = (params.n_ctx - params.n_keep) / 2;
  271. std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + params.n_keep);
  272. const int erased_blocks = (num_prompt_tokens - params.n_keep - n_left - 1) / n_left;
  273. new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + params.n_keep + erased_blocks * n_left, prompt_tokens.end());
  274. std::copy(prompt_tokens.end() - params.n_ctx, prompt_tokens.end(), last_n_tokens.begin());
  275. LOG_VERBOSE("input truncated", {
  276. {"n_ctx", params.n_ctx},
  277. {"n_keep", params.n_keep},
  278. {"n_left", n_left},
  279. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  280. });
  281. truncated = true;
  282. prompt_tokens = new_tokens;
  283. }
  284. else
  285. {
  286. const size_t ps = num_prompt_tokens;
  287. std::fill(last_n_tokens.begin(), last_n_tokens.end() - ps, 0);
  288. std::copy(prompt_tokens.begin(), prompt_tokens.end(), last_n_tokens.end() - ps);
  289. }
  290. // compare the evaluated prompt with the new prompt
  291. n_past = common_part(embd, prompt_tokens);
  292. embd = prompt_tokens;
  293. if (n_past == num_prompt_tokens)
  294. {
  295. // we have to evaluate at least 1 token to generate logits.
  296. n_past--;
  297. }
  298. LOG_VERBOSE("prompt ingested", {
  299. {"n_past", n_past},
  300. {"cached", tokens_to_str(ctx, embd.cbegin(), embd.cbegin() + n_past)},
  301. {"to_eval", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend())},
  302. });
  303. has_next_token = true;
  304. }
  305. void beginCompletion()
  306. {
  307. // number of tokens to keep when resetting context
  308. n_remain = params.n_predict;
  309. llama_set_rng_seed(ctx, params.seed);
  310. }
  311. completion_token_output nextToken()
  312. {
  313. completion_token_output result;
  314. result.tok = -1;
  315. if (embd.size() >= (size_t)params.n_ctx)
  316. {
  317. // Reset context
  318. const int n_left = (params.n_ctx - params.n_keep) / 2;
  319. std::vector<llama_token> new_tokens(embd.begin(), embd.begin() + params.n_keep);
  320. new_tokens.insert(new_tokens.end(), embd.end() - n_left, embd.end());
  321. embd = new_tokens;
  322. n_past = params.n_keep;
  323. truncated = true;
  324. LOG_VERBOSE("input truncated", {
  325. {"n_ctx", params.n_ctx},
  326. {"n_keep", params.n_keep},
  327. {"n_left", n_left},
  328. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  329. });
  330. }
  331. while (n_past < embd.size())
  332. {
  333. int n_eval = (int)embd.size() - n_past;
  334. if (n_eval > params.n_batch)
  335. {
  336. n_eval = params.n_batch;
  337. }
  338. if (llama_eval(ctx, &embd[n_past], n_eval, n_past, params.n_threads))
  339. {
  340. LOG_ERROR("failed to eval", {
  341. {"n_eval", n_eval},
  342. {"n_past", n_past},
  343. {"n_threads", params.n_threads},
  344. {"embd", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend())},
  345. });
  346. has_next_token = false;
  347. return result;
  348. }
  349. n_past += n_eval;
  350. }
  351. if (params.n_predict == 0)
  352. {
  353. has_next_token = false;
  354. result.tok = llama_token_eos(ctx);
  355. return result;
  356. }
  357. // out of user input, sample next token
  358. const float temp = params.temp;
  359. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  360. const float top_p = params.top_p;
  361. const float tfs_z = params.tfs_z;
  362. const float typical_p = params.typical_p;
  363. const int32_t repeat_last_n = params.repeat_last_n < 0 ? params.n_ctx : params.repeat_last_n;
  364. const float repeat_penalty = params.repeat_penalty;
  365. const float alpha_presence = params.presence_penalty;
  366. const float alpha_frequency = params.frequency_penalty;
  367. const int mirostat = params.mirostat;
  368. const float mirostat_tau = params.mirostat_tau;
  369. const float mirostat_eta = params.mirostat_eta;
  370. const bool penalize_nl = params.penalize_nl;
  371. const int32_t n_probs = params.n_probs;
  372. {
  373. auto *logits = llama_get_logits(ctx);
  374. auto n_vocab = llama_n_vocab(ctx);
  375. // Apply params.logit_bias map
  376. for (const auto &it : params.logit_bias)
  377. {
  378. logits[it.first] += it.second;
  379. }
  380. std::vector<llama_token_data> candidates;
  381. candidates.reserve(n_vocab);
  382. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  383. {
  384. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  385. }
  386. llama_token_data_array candidates_p = {candidates.data(), candidates.size(), false};
  387. // Apply penalties
  388. float nl_logit = logits[llama_token_nl(ctx)];
  389. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), params.n_ctx);
  390. llama_sample_repetition_penalty(ctx, &candidates_p,
  391. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  392. last_n_repeat, repeat_penalty);
  393. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  394. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  395. last_n_repeat, alpha_frequency, alpha_presence);
  396. if (!penalize_nl)
  397. {
  398. logits[llama_token_nl(ctx)] = nl_logit;
  399. }
  400. if (grammar != nullptr) {
  401. llama_sample_grammar(ctx, &candidates_p, grammar);
  402. }
  403. if (temp <= 0)
  404. {
  405. // Greedy sampling
  406. result.tok = llama_sample_token_greedy(ctx, &candidates_p);
  407. if (n_probs > 0)
  408. {
  409. llama_sample_softmax(ctx, &candidates_p);
  410. }
  411. }
  412. else
  413. {
  414. if (mirostat == 1)
  415. {
  416. static float mirostat_mu = 2.0f * mirostat_tau;
  417. const int mirostat_m = 100;
  418. llama_sample_temperature(ctx, &candidates_p, temp);
  419. result.tok = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  420. }
  421. else if (mirostat == 2)
  422. {
  423. static float mirostat_mu = 2.0f * mirostat_tau;
  424. llama_sample_temperature(ctx, &candidates_p, temp);
  425. result.tok = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  426. }
  427. else
  428. {
  429. // Temperature sampling
  430. size_t min_keep = std::max(1, n_probs);
  431. llama_sample_top_k(ctx, &candidates_p, top_k, min_keep);
  432. llama_sample_tail_free(ctx, &candidates_p, tfs_z, min_keep);
  433. llama_sample_typical(ctx, &candidates_p, typical_p, min_keep);
  434. llama_sample_top_p(ctx, &candidates_p, top_p, min_keep);
  435. llama_sample_temperature(ctx, &candidates_p, temp);
  436. result.tok = llama_sample_token(ctx, &candidates_p);
  437. }
  438. }
  439. if (grammar != nullptr) {
  440. llama_grammar_accept_token(ctx, grammar, result.tok);
  441. }
  442. for (size_t i = 0; i < std::min(candidates_p.size, (size_t)n_probs); ++i)
  443. {
  444. result.probs.push_back({candidates_p.data[i].id, candidates_p.data[i].p});
  445. }
  446. last_n_tokens.erase(last_n_tokens.begin());
  447. last_n_tokens.push_back(result.tok);
  448. num_tokens_predicted++;
  449. }
  450. // add it to the context
  451. embd.push_back(result.tok);
  452. // decrement remaining sampling budget
  453. --n_remain;
  454. if (!embd.empty() && embd.back() == llama_token_eos(ctx))
  455. {
  456. // stopping_word = llama_token_to_str(ctx, embd.back());
  457. has_next_token = false;
  458. stopped_eos = true;
  459. LOG_VERBOSE("eos token found", {});
  460. return result;
  461. }
  462. has_next_token = params.n_predict == -1 || n_remain != 0;
  463. return result;
  464. }
  465. size_t findStoppingStrings(const std::string &text, const size_t last_token_size,
  466. const stop_type type)
  467. {
  468. size_t stop_pos = std::string::npos;
  469. for (const std::string &word : params.antiprompt)
  470. {
  471. size_t pos;
  472. if (type == STOP_FULL)
  473. {
  474. const size_t tmp = word.size() + last_token_size;
  475. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  476. pos = text.find(word, from_pos);
  477. }
  478. else
  479. {
  480. pos = find_partial_stop_string(word, text);
  481. }
  482. if (pos != std::string::npos &&
  483. (stop_pos == std::string::npos || pos < stop_pos))
  484. {
  485. if (type == STOP_FULL)
  486. {
  487. stopping_word = word;
  488. stopped_word = true;
  489. has_next_token = false;
  490. }
  491. stop_pos = pos;
  492. }
  493. }
  494. return stop_pos;
  495. }
  496. completion_token_output doCompletion()
  497. {
  498. const completion_token_output token_with_probs = nextToken();
  499. const std::string token_text = token_with_probs.tok == -1 ? "" : llama_token_to_str(ctx, token_with_probs.tok);
  500. generated_text += token_text;
  501. if (params.n_probs > 0)
  502. {
  503. generated_token_probs.push_back(token_with_probs);
  504. }
  505. if (multibyte_pending > 0)
  506. {
  507. multibyte_pending -= token_text.size();
  508. }
  509. else if (token_text.size() == 1)
  510. {
  511. const char c = token_text[0];
  512. // 2-byte characters: 110xxxxx 10xxxxxx
  513. if ((c & 0xE0) == 0xC0)
  514. {
  515. multibyte_pending = 1;
  516. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  517. }
  518. else if ((c & 0xF0) == 0xE0)
  519. {
  520. multibyte_pending = 2;
  521. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  522. }
  523. else if ((c & 0xF8) == 0xF0)
  524. {
  525. multibyte_pending = 3;
  526. }
  527. else
  528. {
  529. multibyte_pending = 0;
  530. }
  531. }
  532. if (multibyte_pending > 0 && !has_next_token)
  533. {
  534. has_next_token = true;
  535. n_remain++;
  536. }
  537. if (!has_next_token && n_remain == 0)
  538. {
  539. stopped_limit = true;
  540. }
  541. LOG_VERBOSE("next token", {
  542. {"token", token_with_probs.tok},
  543. {"token_text", tokens_to_output_formatted_string(ctx, token_with_probs.tok)},
  544. {"has_next_token", has_next_token},
  545. {"n_remain", n_remain},
  546. {"num_tokens_predicted", num_tokens_predicted},
  547. {"stopped_eos", stopped_eos},
  548. {"stopped_word", stopped_word},
  549. {"stopped_limit", stopped_limit},
  550. {"stopping_word", stopping_word},
  551. });
  552. return token_with_probs;
  553. }
  554. std::vector<float> getEmbedding()
  555. {
  556. static const int n_embd = llama_n_embd(ctx);
  557. if (!params.embedding)
  558. {
  559. LOG_WARNING("embedding disabled", {
  560. {"params.embedding", params.embedding},
  561. });
  562. return std::vector<float>(n_embd, 0.0f);
  563. }
  564. const float *data = llama_get_embeddings(ctx);
  565. std::vector<float> embedding(data, data + n_embd);
  566. return embedding;
  567. }
  568. };
  569. static void server_print_usage(const char *argv0, const gpt_params &params,
  570. const server_params &sparams)
  571. {
  572. fprintf(stdout, "usage: %s [options]\n", argv0);
  573. fprintf(stdout, "\n");
  574. fprintf(stdout, "options:\n");
  575. fprintf(stdout, " -h, --help show this help message and exit\n");
  576. fprintf(stdout, " -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  577. fprintf(stdout, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  578. fprintf(stdout, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  579. fprintf(stdout, " --rope-freq-base N RoPE base frequency (default: %.1f)\n", params.rope_freq_base);
  580. fprintf(stdout, " --rope-freq-scale N RoPE frequency scaling factor (default: %g)\n", params.rope_freq_scale);
  581. fprintf(stdout, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  582. fprintf(stdout, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  583. fprintf(stdout, " not recommended: doubles context memory required and no measurable increase in quality\n");
  584. if (llama_mlock_supported())
  585. {
  586. fprintf(stdout, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  587. }
  588. if (llama_mmap_supported())
  589. {
  590. fprintf(stdout, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  591. }
  592. fprintf(stdout, " --numa attempt optimizations that help on some NUMA systems\n");
  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 == "--rope-freq-base")
  698. {
  699. if (++i >= argc)
  700. {
  701. invalid_param = true;
  702. break;
  703. }
  704. params.rope_freq_base = std::stof(argv[i]);
  705. }
  706. else if (arg == "--rope-freq-scale")
  707. {
  708. if (++i >= argc)
  709. {
  710. invalid_param = true;
  711. break;
  712. }
  713. params.rope_freq_scale = std::stof(argv[i]);
  714. }
  715. else if (arg == "--memory-f32" || arg == "--memory_f32")
  716. {
  717. params.memory_f16 = false;
  718. }
  719. else if (arg == "--threads" || arg == "-t")
  720. {
  721. if (++i >= argc)
  722. {
  723. invalid_param = true;
  724. break;
  725. }
  726. params.n_threads = std::stoi(argv[i]);
  727. }
  728. else if (arg == "-b" || arg == "--batch-size")
  729. {
  730. if (++i >= argc)
  731. {
  732. invalid_param = true;
  733. break;
  734. }
  735. params.n_batch = std::stoi(argv[i]);
  736. params.n_batch = std::min(512, params.n_batch);
  737. }
  738. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  739. {
  740. if (++i >= argc)
  741. {
  742. invalid_param = true;
  743. break;
  744. }
  745. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  746. params.n_gpu_layers = std::stoi(argv[i]);
  747. #else
  748. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  749. "See main README.md for information on enabling GPU BLAS support",
  750. {{"n_gpu_layers", params.n_gpu_layers}});
  751. #endif
  752. }
  753. else if (arg == "--tensor-split" || arg == "-ts")
  754. {
  755. if (++i >= argc)
  756. {
  757. invalid_param = true;
  758. break;
  759. }
  760. #ifdef GGML_USE_CUBLAS
  761. std::string arg_next = argv[i];
  762. // split string by , and /
  763. const std::regex regex{R"([,/]+)"};
  764. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  765. std::vector<std::string> split_arg{it, {}};
  766. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  767. for (size_t i_device = 0; i_device < LLAMA_MAX_DEVICES; ++i_device)
  768. {
  769. if (i_device < split_arg.size())
  770. {
  771. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  772. }
  773. else
  774. {
  775. params.tensor_split[i_device] = 0.0f;
  776. }
  777. }
  778. #else
  779. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n", {});
  780. #endif // GGML_USE_CUBLAS
  781. }
  782. else if (arg == "--low-vram" || arg == "-lv")
  783. {
  784. #ifdef GGML_USE_CUBLAS
  785. params.low_vram = true;
  786. #else
  787. LOG_WARNING("warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n", {});
  788. #endif // GGML_USE_CUBLAS
  789. }
  790. else if (arg == "--mul-mat-q" || arg == "-mmq")
  791. {
  792. #ifdef GGML_USE_CUBLAS
  793. params.mul_mat_q = true;
  794. #else
  795. LOG_WARNING("warning: llama.cpp was compiled without cuBLAS. It is not possible to use mul_mat_q kernels.\n", {});
  796. #endif // GGML_USE_CUBLAS
  797. }
  798. else if (arg == "--main-gpu" || arg == "-mg")
  799. {
  800. if (++i >= argc)
  801. {
  802. invalid_param = true;
  803. break;
  804. }
  805. #ifdef GGML_USE_CUBLAS
  806. params.main_gpu = std::stoi(argv[i]);
  807. #else
  808. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  809. #endif
  810. }
  811. else if (arg == "--lora")
  812. {
  813. if (++i >= argc)
  814. {
  815. invalid_param = true;
  816. break;
  817. }
  818. params.lora_adapter = argv[i];
  819. params.use_mmap = false;
  820. }
  821. else if (arg == "--lora-base")
  822. {
  823. if (++i >= argc)
  824. {
  825. invalid_param = true;
  826. break;
  827. }
  828. params.lora_base = argv[i];
  829. }
  830. else if (arg == "-v" || arg == "--verbose")
  831. {
  832. #if SERVER_VERBOSE != 1
  833. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  834. #else
  835. server_verbose = true;
  836. #endif
  837. }
  838. else if (arg == "--mlock")
  839. {
  840. params.use_mlock = true;
  841. }
  842. else if (arg == "--no-mmap")
  843. {
  844. params.use_mmap = false;
  845. }
  846. else if (arg == "--numa")
  847. {
  848. params.numa = true;
  849. }
  850. else if (arg == "--embedding")
  851. {
  852. params.embedding = true;
  853. }
  854. else
  855. {
  856. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  857. server_print_usage(argv[0], default_params, default_sparams);
  858. exit(1);
  859. }
  860. }
  861. if (invalid_param)
  862. {
  863. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  864. server_print_usage(argv[0], default_params, default_sparams);
  865. exit(1);
  866. }
  867. }
  868. static json format_generation_settings(llama_server_context &llama)
  869. {
  870. const auto eos_bias = llama.params.logit_bias.find(llama_token_eos(llama.ctx));
  871. const bool ignore_eos = eos_bias != llama.params.logit_bias.end() &&
  872. eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  873. return json{
  874. {"n_ctx", llama.params.n_ctx},
  875. {"model", llama.params.model_alias},
  876. {"seed", llama.params.seed},
  877. {"temp", llama.params.temp},
  878. {"top_k", llama.params.top_k},
  879. {"top_p", llama.params.top_p},
  880. {"tfs_z", llama.params.tfs_z},
  881. {"typical_p", llama.params.typical_p},
  882. {"repeat_last_n", llama.params.repeat_last_n},
  883. {"repeat_penalty", llama.params.repeat_penalty},
  884. {"presence_penalty", llama.params.presence_penalty},
  885. {"frequency_penalty", llama.params.frequency_penalty},
  886. {"mirostat", llama.params.mirostat},
  887. {"mirostat_tau", llama.params.mirostat_tau},
  888. {"mirostat_eta", llama.params.mirostat_eta},
  889. {"penalize_nl", llama.params.penalize_nl},
  890. {"stop", llama.params.antiprompt},
  891. {"n_predict", llama.params.n_predict},
  892. {"n_keep", llama.params.n_keep},
  893. {"ignore_eos", ignore_eos},
  894. {"stream", llama.stream},
  895. {"logit_bias", llama.params.logit_bias},
  896. {"n_probs", llama.params.n_probs},
  897. {"grammar", llama.params.grammar},
  898. };
  899. }
  900. static json format_embedding_response(llama_server_context &llama)
  901. {
  902. return json{
  903. {"embedding", llama.getEmbedding()},
  904. };
  905. }
  906. static json format_timings(llama_server_context &llama)
  907. {
  908. const auto timings = llama_get_timings(llama.ctx);
  909. assert(timings.n_eval == llama.num_tokens_predicted);
  910. return json{
  911. {"prompt_n", timings.n_p_eval},
  912. {"prompt_ms", timings.t_p_eval_ms},
  913. {"prompt_per_token_ms", timings.t_p_eval_ms / timings.n_p_eval},
  914. {"prompt_per_second", 1e3 / timings.t_p_eval_ms * timings.n_p_eval},
  915. {"predicted_n", timings.n_eval},
  916. {"predicted_ms", timings.t_eval_ms},
  917. {"predicted_per_token_ms", timings.t_eval_ms / timings.n_eval},
  918. {"predicted_per_second", 1e3 / timings.t_eval_ms * timings.n_eval},
  919. };
  920. }
  921. static json format_final_response(llama_server_context &llama, const std::string &content, const std::vector<completion_token_output> &probs)
  922. {
  923. json res = json{
  924. {"content", content},
  925. {"stop", true},
  926. {"model", llama.params.model_alias},
  927. {"tokens_predicted", llama.num_tokens_predicted},
  928. {"tokens_evaluated", llama.num_prompt_tokens},
  929. {"generation_settings", format_generation_settings(llama)},
  930. {"prompt", llama.params.prompt},
  931. {"truncated", llama.truncated},
  932. {"stopped_eos", llama.stopped_eos},
  933. {"stopped_word", llama.stopped_word},
  934. {"stopped_limit", llama.stopped_limit},
  935. {"stopping_word", llama.stopping_word},
  936. {"tokens_cached", llama.n_past},
  937. {"timings", format_timings(llama)},
  938. };
  939. if (llama.params.n_probs > 0)
  940. {
  941. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  942. }
  943. return res;
  944. }
  945. static json format_partial_response(llama_server_context &llama, const std::string &content, const std::vector<completion_token_output> &probs)
  946. {
  947. json res = json{
  948. {"content", content},
  949. {"stop", false},
  950. };
  951. if (llama.params.n_probs > 0)
  952. {
  953. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  954. }
  955. return res;
  956. }
  957. static json format_tokenizer_response(const std::vector<llama_token> &tokens)
  958. {
  959. return json{
  960. {"tokens", tokens}};
  961. }
  962. template <typename T>
  963. static T json_value(const json &body, const std::string &key, const T &default_value)
  964. {
  965. // Fallback null to default value
  966. return body.contains(key) && !body.at(key).is_null()
  967. ? body.value(key, default_value)
  968. : default_value;
  969. }
  970. static void parse_options_completion(const json &body, llama_server_context &llama)
  971. {
  972. gpt_params default_params;
  973. llama.stream = json_value(body, "stream", false);
  974. llama.params.n_predict = json_value(body, "n_predict", default_params.n_predict);
  975. llama.params.top_k = json_value(body, "top_k", default_params.top_k);
  976. llama.params.top_p = json_value(body, "top_p", default_params.top_p);
  977. llama.params.tfs_z = json_value(body, "tfs_z", default_params.tfs_z);
  978. llama.params.typical_p = json_value(body, "typical_p", default_params.typical_p);
  979. llama.params.repeat_last_n = json_value(body, "repeat_last_n", default_params.repeat_last_n);
  980. llama.params.temp = json_value(body, "temperature", default_params.temp);
  981. llama.params.repeat_penalty = json_value(body, "repeat_penalty", default_params.repeat_penalty);
  982. llama.params.presence_penalty = json_value(body, "presence_penalty", default_params.presence_penalty);
  983. llama.params.frequency_penalty = json_value(body, "frequency_penalty", default_params.frequency_penalty);
  984. llama.params.mirostat = json_value(body, "mirostat", default_params.mirostat);
  985. llama.params.mirostat_tau = json_value(body, "mirostat_tau", default_params.mirostat_tau);
  986. llama.params.mirostat_eta = json_value(body, "mirostat_eta", default_params.mirostat_eta);
  987. llama.params.penalize_nl = json_value(body, "penalize_nl", default_params.penalize_nl);
  988. llama.params.n_keep = json_value(body, "n_keep", default_params.n_keep);
  989. llama.params.seed = json_value(body, "seed", default_params.seed);
  990. llama.params.prompt = json_value(body, "prompt", default_params.prompt);
  991. llama.params.grammar = json_value(body, "grammar", default_params.grammar);
  992. llama.params.n_probs = json_value(body, "n_probs", default_params.n_probs);
  993. llama.params.logit_bias.clear();
  994. if (json_value(body, "ignore_eos", false))
  995. {
  996. llama.params.logit_bias[llama_token_eos(llama.ctx)] = -INFINITY;
  997. }
  998. const auto &logit_bias = body.find("logit_bias");
  999. if (logit_bias != body.end() && logit_bias->is_array())
  1000. {
  1001. const int n_vocab = llama_n_vocab(llama.ctx);
  1002. for (const auto &el : *logit_bias)
  1003. {
  1004. if (el.is_array() && el.size() == 2 && el[0].is_number_integer())
  1005. {
  1006. llama_token tok = el[0].get<llama_token>();
  1007. if (tok >= 0 && tok < n_vocab)
  1008. {
  1009. if (el[1].is_number())
  1010. {
  1011. llama.params.logit_bias[tok] = el[1].get<float>();
  1012. }
  1013. else if (el[1].is_boolean() && !el[1].get<bool>())
  1014. {
  1015. llama.params.logit_bias[tok] = -INFINITY;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. }
  1021. llama.params.antiprompt.clear();
  1022. const auto &stop = body.find("stop");
  1023. if (stop != body.end() && stop->is_array())
  1024. {
  1025. for (const auto &word : *stop)
  1026. {
  1027. if (!word.empty())
  1028. {
  1029. llama.params.antiprompt.push_back(word);
  1030. }
  1031. }
  1032. }
  1033. LOG_VERBOSE("completion parameters parsed", format_generation_settings(llama));
  1034. }
  1035. static void log_server_request(const Request &req, const Response &res)
  1036. {
  1037. LOG_INFO("request", {
  1038. {"remote_addr", req.remote_addr},
  1039. {"remote_port", req.remote_port},
  1040. {"status", res.status},
  1041. {"method", req.method},
  1042. {"path", req.path},
  1043. {"params", req.params},
  1044. });
  1045. LOG_VERBOSE("request", {
  1046. {"request", req.body},
  1047. {"response", res.body},
  1048. });
  1049. }
  1050. int main(int argc, char **argv)
  1051. {
  1052. // own arguments required by this example
  1053. gpt_params params;
  1054. server_params sparams;
  1055. // struct that contains llama context and inference
  1056. llama_server_context llama;
  1057. server_params_parse(argc, argv, sparams, params);
  1058. if (params.model_alias == "unknown")
  1059. {
  1060. params.model_alias = params.model;
  1061. }
  1062. llama_backend_init(params.numa);
  1063. LOG_INFO("build info", {{"build", BUILD_NUMBER},
  1064. {"commit", BUILD_COMMIT}});
  1065. LOG_INFO("system info", {
  1066. {"n_threads", params.n_threads},
  1067. {"total_threads", std::thread::hardware_concurrency()},
  1068. {"system_info", llama_print_system_info()},
  1069. });
  1070. // load the model
  1071. if (!llama.loadModel(params))
  1072. {
  1073. return 1;
  1074. }
  1075. Server svr;
  1076. svr.set_default_headers({{"Server", "llama.cpp"},
  1077. {"Access-Control-Allow-Origin", "*"},
  1078. {"Access-Control-Allow-Headers", "content-type"}});
  1079. // this is only called if no index.html is found in the public --path
  1080. svr.Get("/", [](const Request &, Response &res)
  1081. {
  1082. res.set_content(reinterpret_cast<const char*>(&index_html), index_html_len, "text/html");
  1083. return false; });
  1084. // this is only called if no index.js is found in the public --path
  1085. svr.Get("/index.js", [](const Request &, Response &res)
  1086. {
  1087. res.set_content(reinterpret_cast<const char *>(&index_js), index_js_len, "text/javascript");
  1088. return false; });
  1089. // this is only called if no index.html is found in the public --path
  1090. svr.Get("/completion.js", [](const Request &, Response &res)
  1091. {
  1092. res.set_content(reinterpret_cast<const char*>(&completion_js), completion_js_len, "application/javascript");
  1093. return false; });
  1094. // this is only called if no index.html is found in the public --path
  1095. svr.Get("/json-schema-to-grammar.mjs", [](const Request &, Response &res)
  1096. {
  1097. res.set_content(reinterpret_cast<const char*>(&json_schema_to_grammar_mjs), json_schema_to_grammar_mjs_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 = json_value<std::string>(body, "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 = json_value<std::string>(body, "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 if (res.status != 500) {
  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. }