server.cpp 66 KB

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