1
0

server.cpp 64 KB

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