1
0

server.cpp 58 KB

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