server.cpp 51 KB

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