server.cpp 64 KB

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