server.cpp 62 KB

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