server.cpp 57 KB

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