1
0

server.cpp 51 KB

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