server.cpp 63 KB

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