1
0

server.cpp 66 KB

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