server.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. // single thread
  5. #define CPPHTTPLIB_THREAD_POOL_COUNT 1
  6. #ifndef NDEBUG
  7. // crash the server in debug mode, otherwise send an http 500 error
  8. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  9. #endif
  10. #include "httplib.h"
  11. #include "json.hpp"
  12. #ifndef SERVER_VERBOSE
  13. #define SERVER_VERBOSE 1
  14. #endif
  15. using namespace httplib;
  16. using json = nlohmann::json;
  17. struct server_params {
  18. std::string hostname = "127.0.0.1";
  19. int32_t port = 8080;
  20. int32_t read_timeout = 600;
  21. int32_t write_timeout = 600;
  22. };
  23. // completion token output with probabilities
  24. struct completion_token_output {
  25. struct token_prob {
  26. llama_token tok;
  27. float prob;
  28. };
  29. std::vector<token_prob> probs;
  30. llama_token tok;
  31. };
  32. static size_t common_part(const std::vector<llama_token> & a, const std::vector<llama_token> & b) {
  33. size_t i;
  34. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  35. return i;
  36. }
  37. enum stop_type {
  38. STOP_FULL,
  39. STOP_PARTIAL,
  40. };
  41. static bool ends_with(const std::string & str, const std::string & suffix) {
  42. return str.size() >= suffix.size() &&
  43. 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  44. }
  45. static size_t find_partial_stop_string(const std::string & stop,
  46. const std::string & text) {
  47. if (!text.empty() && !stop.empty()) {
  48. const char text_last_char = text.back();
  49. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  50. if (stop[char_index] == text_last_char) {
  51. const std::string current_partial = stop.substr(0, char_index + 1);
  52. if (ends_with(text, current_partial)) {
  53. return text.size() - char_index - 1;
  54. }
  55. }
  56. }
  57. }
  58. return std::string::npos;
  59. }
  60. template<class Iter>
  61. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  62. std::string ret;
  63. for (; begin != end; ++begin) {
  64. ret += llama_token_to_str(ctx, *begin);
  65. }
  66. return ret;
  67. }
  68. static void server_log(const char * level, const char * function, int line,
  69. const char * message, const nlohmann::ordered_json & extra) {
  70. nlohmann::ordered_json log {
  71. { "timestamp", time(nullptr) },
  72. { "level", level },
  73. { "function", function },
  74. { "line", line },
  75. { "message", message },
  76. };
  77. if (!extra.empty()) {
  78. log.merge_patch(extra);
  79. }
  80. const std::string str = log.dump(-1, ' ', false, json::error_handler_t::replace);
  81. fprintf(stdout, "%.*s\n", (int)str.size(), str.data());
  82. fflush(stdout);
  83. }
  84. // format incomplete utf-8 multibyte character for output
  85. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  86. std::string out = token == -1 ? "" : llama_token_to_str(ctx, token);
  87. // if first bit is 1, meaning it's a partial character
  88. if (out.size() > 0 && (out[0] & 0x80) == 0x80) {
  89. std::stringstream ss;
  90. ss<< std::hex << (out[0] & 0xff);
  91. std::string res ( ss.str() );
  92. out = "byte: \\x" + res;
  93. }
  94. return out;
  95. }
  96. // convert a vector of completion_token_output to json
  97. static json probs_vector_to_json(const llama_context * ctx, const std::vector<completion_token_output> probs) {
  98. json out = json::array();
  99. for (const auto & prob : probs) {
  100. json probs_for_token = json::array();
  101. for (const auto & p : prob.probs) {
  102. std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  103. probs_for_token.push_back(json {
  104. { "tok_str", tok_str },
  105. { "prob", p.prob },
  106. });
  107. }
  108. std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  109. out.push_back(json {
  110. {"content", tok_str},
  111. {"probs", probs_for_token},
  112. });
  113. }
  114. return out;
  115. }
  116. static bool server_verbose = false;
  117. #if SERVER_VERBOSE != 1
  118. # define LOG_VERBOSE(MSG, ...)
  119. #else
  120. # define LOG_VERBOSE(MSG, ...) \
  121. do { \
  122. if (server_verbose) { \
  123. server_log("VERBOSE", __func__, __LINE__, MSG, __VA_ARGS__); \
  124. } \
  125. } while(0)
  126. #endif
  127. #define LOG_ERROR(MSG, ...) server_log("ERROR", __func__, __LINE__, MSG, __VA_ARGS__)
  128. #define LOG_WARNING(MSG, ...) server_log("WARNING", __func__, __LINE__, MSG, __VA_ARGS__)
  129. #define LOG_INFO(MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  130. struct llama_server_context {
  131. bool stream = false;
  132. bool has_next_token = false;
  133. std::string generated_text;
  134. std::vector<completion_token_output> generated_token_probs;
  135. size_t num_tokens_predicted = 0;
  136. size_t n_past = 0;
  137. size_t n_remain = 0;
  138. std::vector<llama_token> embd;
  139. std::vector<llama_token> last_n_tokens;
  140. llama_model * model = nullptr;
  141. llama_context * ctx = nullptr;
  142. gpt_params params;
  143. bool truncated = false;
  144. bool stopped_eos = false;
  145. bool stopped_word = false;
  146. bool stopped_limit = false;
  147. std::string stopping_word;
  148. int32_t multibyte_pending = 0;
  149. ~llama_server_context() {
  150. if (ctx) {
  151. llama_free(ctx);
  152. ctx = nullptr;
  153. }
  154. if (model) {
  155. llama_free_model(model);
  156. model = nullptr;
  157. }
  158. }
  159. void rewind() {
  160. params.antiprompt.clear();
  161. num_tokens_predicted = 0;
  162. generated_text = "";
  163. generated_text.reserve(params.n_ctx);
  164. generated_token_probs.clear();
  165. truncated = false;
  166. stopped_eos = false;
  167. stopped_word = false;
  168. stopped_limit = false;
  169. stopping_word = "";
  170. multibyte_pending = 0;
  171. n_remain = 0;
  172. n_past = 0;
  173. }
  174. bool loadModel(const gpt_params & params_) {
  175. params = params_;
  176. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  177. if (model == nullptr) {
  178. LOG_ERROR("unable to load model", { { "model", params_.model } });
  179. return false;
  180. }
  181. last_n_tokens.resize(params.n_ctx);
  182. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  183. return true;
  184. }
  185. void loadPrompt() {
  186. params.prompt.insert(0, 1, ' '); // always add a first space
  187. std::vector<llama_token> prompt_tokens = ::llama_tokenize(ctx, params.prompt, true);
  188. if (params.n_keep < 0) {
  189. params.n_keep = (int)prompt_tokens.size();
  190. }
  191. params.n_keep = std::min(params.n_ctx - 4, params.n_keep);
  192. // if input prompt is too big, truncate like normal
  193. if (prompt_tokens.size() >= (size_t)params.n_ctx) {
  194. const int n_left = (params.n_ctx - params.n_keep) / 2;
  195. std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + params.n_keep);
  196. const int erased_blocks = (prompt_tokens.size() - params.n_keep - n_left - 1) / n_left;
  197. new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + params.n_keep + erased_blocks * n_left, prompt_tokens.end());
  198. std::copy(prompt_tokens.end() - params.n_ctx, prompt_tokens.end(), last_n_tokens.begin());
  199. LOG_VERBOSE("input truncated", {
  200. { "n_ctx", params.n_ctx },
  201. { "n_keep", params.n_keep },
  202. { "n_left", n_left },
  203. { "new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend()) },
  204. });
  205. truncated = true;
  206. prompt_tokens = new_tokens;
  207. } else {
  208. const size_t ps = prompt_tokens.size();
  209. std::fill(last_n_tokens.begin(), last_n_tokens.end() - ps, 0);
  210. std::copy(prompt_tokens.begin(), prompt_tokens.end(), last_n_tokens.end() - ps);
  211. }
  212. // compare the evaluated prompt with the new prompt
  213. n_past = common_part(embd, prompt_tokens);
  214. embd = prompt_tokens;
  215. if (n_past == prompt_tokens.size()) {
  216. // we have to evaluate at least 1 token to generate logits.
  217. n_past--;
  218. }
  219. LOG_VERBOSE("prompt ingested", {
  220. { "n_past", n_past },
  221. { "cached", tokens_to_str(ctx, embd.cbegin(), embd.cbegin() + n_past) },
  222. { "to_eval", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend()) },
  223. });
  224. has_next_token = true;
  225. }
  226. void beginCompletion() {
  227. // number of tokens to keep when resetting context
  228. n_remain = params.n_predict;
  229. llama_set_rng_seed(ctx, params.seed);
  230. }
  231. completion_token_output nextToken() {
  232. completion_token_output result;
  233. result.tok = -1;
  234. if (embd.size() >= (size_t)params.n_ctx) {
  235. // Reset context
  236. const int n_left = (params.n_ctx - params.n_keep) / 2;
  237. std::vector<llama_token> new_tokens(embd.begin(), embd.begin() + params.n_keep);
  238. new_tokens.insert(new_tokens.end(), embd.end() - n_left, embd.end());
  239. embd = new_tokens;
  240. n_past = params.n_keep;
  241. truncated = true;
  242. LOG_VERBOSE("input truncated", {
  243. { "n_ctx", params.n_ctx },
  244. { "n_keep", params.n_keep },
  245. { "n_left", n_left },
  246. { "new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend()) },
  247. });
  248. }
  249. while (n_past < embd.size()) {
  250. int n_eval = (int)embd.size() - n_past;
  251. if (n_eval > params.n_batch) {
  252. n_eval = params.n_batch;
  253. }
  254. if (llama_eval(ctx, &embd[n_past], n_eval, n_past, params.n_threads)) {
  255. LOG_ERROR("failed to eval", {
  256. { "n_eval", n_eval },
  257. { "n_past", n_past },
  258. { "n_threads", params.n_threads },
  259. { "embd", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend()) },
  260. });
  261. has_next_token = false;
  262. return result;
  263. }
  264. n_past += n_eval;
  265. }
  266. if (params.n_predict == 0) {
  267. has_next_token = false;
  268. result.tok = llama_token_eos();
  269. return result;
  270. }
  271. // out of user input, sample next token
  272. const float temp = params.temp;
  273. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  274. const float top_p = params.top_p;
  275. const float tfs_z = params.tfs_z;
  276. const float typical_p = params.typical_p;
  277. const int32_t repeat_last_n = params.repeat_last_n < 0 ? params.n_ctx : params.repeat_last_n;
  278. const float repeat_penalty = params.repeat_penalty;
  279. const float alpha_presence = params.presence_penalty;
  280. const float alpha_frequency = params.frequency_penalty;
  281. const int mirostat = params.mirostat;
  282. const float mirostat_tau = params.mirostat_tau;
  283. const float mirostat_eta = params.mirostat_eta;
  284. const bool penalize_nl = params.penalize_nl;
  285. const int32_t n_probs = params.n_probs;
  286. {
  287. auto * logits = llama_get_logits(ctx);
  288. auto n_vocab = llama_n_vocab(ctx);
  289. // Apply params.logit_bias map
  290. for (const auto & it : params.logit_bias) {
  291. logits[it.first] += it.second;
  292. }
  293. std::vector<llama_token_data> candidates;
  294. candidates.reserve(n_vocab);
  295. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  296. candidates.emplace_back(llama_token_data{ token_id, logits[token_id], 0.0f });
  297. }
  298. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  299. // Apply penalties
  300. float nl_logit = logits[llama_token_nl()];
  301. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), params.n_ctx);
  302. llama_sample_repetition_penalty(ctx, &candidates_p,
  303. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  304. last_n_repeat, repeat_penalty);
  305. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  306. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  307. last_n_repeat, alpha_frequency, alpha_presence);
  308. if (!penalize_nl) {
  309. logits[llama_token_nl()] = nl_logit;
  310. }
  311. if (temp <= 0) {
  312. // Greedy sampling
  313. result.tok = llama_sample_token_greedy(ctx, &candidates_p);
  314. if (n_probs > 0) {
  315. llama_sample_softmax(ctx, &candidates_p);
  316. }
  317. } else {
  318. if (mirostat == 1) {
  319. static float mirostat_mu = 2.0f * mirostat_tau;
  320. const int mirostat_m = 100;
  321. llama_sample_temperature(ctx, &candidates_p, temp);
  322. result.tok = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  323. } else if (mirostat == 2) {
  324. static float mirostat_mu = 2.0f * mirostat_tau;
  325. llama_sample_temperature(ctx, &candidates_p, temp);
  326. result.tok = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  327. } else {
  328. // Temperature sampling
  329. size_t min_keep = std::max(1, n_probs);
  330. llama_sample_top_k(ctx, &candidates_p, top_k, min_keep);
  331. llama_sample_tail_free(ctx, &candidates_p, tfs_z, min_keep);
  332. llama_sample_typical(ctx, &candidates_p, typical_p, min_keep);
  333. llama_sample_top_p(ctx, &candidates_p, top_p, min_keep);
  334. llama_sample_temperature(ctx, &candidates_p, temp);
  335. result.tok = llama_sample_token(ctx, &candidates_p);
  336. }
  337. }
  338. for (size_t i = 0; i < std::min(candidates_p.size, (size_t) n_probs); ++i) {
  339. result.probs.push_back({candidates_p.data[i].id, candidates_p.data[i].p});
  340. }
  341. last_n_tokens.erase(last_n_tokens.begin());
  342. last_n_tokens.push_back(result.tok);
  343. num_tokens_predicted++;
  344. }
  345. // add it to the context
  346. embd.push_back(result.tok);
  347. // decrement remaining sampling budget
  348. --n_remain;
  349. if (!embd.empty() && embd.back() == llama_token_eos()) {
  350. //stopping_word = llama_token_to_str(ctx, embd.back());
  351. has_next_token = false;
  352. stopped_eos = true;
  353. LOG_VERBOSE("eos token found", {});
  354. return result;
  355. }
  356. has_next_token = params.n_predict == -1 || n_remain != 0;
  357. return result;
  358. }
  359. size_t findStoppingStrings(const std::string & text, const size_t last_token_size,
  360. const stop_type type) {
  361. size_t stop_pos = std::string::npos;
  362. for (const std::string & word : params.antiprompt) {
  363. size_t pos;
  364. if (type == STOP_FULL) {
  365. const size_t tmp = word.size() + last_token_size;
  366. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  367. pos = text.find(word, from_pos);
  368. }
  369. else {
  370. pos = find_partial_stop_string(word, text);
  371. }
  372. if (pos != std::string::npos &&
  373. (stop_pos == std::string::npos || pos < stop_pos)) {
  374. if (type == STOP_FULL) {
  375. stopping_word = word;
  376. stopped_word = true;
  377. has_next_token = false;
  378. }
  379. stop_pos = pos;
  380. }
  381. }
  382. return stop_pos;
  383. }
  384. completion_token_output doCompletion() {
  385. const completion_token_output token_with_probs = nextToken();
  386. const std::string token_text = token_with_probs.tok == -1 ? "" : llama_token_to_str(ctx, token_with_probs.tok);
  387. generated_text += token_text;
  388. if (params.n_probs > 0) {
  389. generated_token_probs.push_back(token_with_probs);
  390. }
  391. if (multibyte_pending > 0) {
  392. multibyte_pending -= token_text.size();
  393. } else if (token_text.size() == 1) {
  394. const char c = token_text[0];
  395. // 2-byte characters: 110xxxxx 10xxxxxx
  396. if ((c & 0xE0) == 0xC0) {
  397. multibyte_pending = 1;
  398. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  399. } else if ((c & 0xF0) == 0xE0) {
  400. multibyte_pending = 2;
  401. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  402. } else if ((c & 0xF8) == 0xF0) {
  403. multibyte_pending = 3;
  404. } else {
  405. multibyte_pending = 0;
  406. }
  407. }
  408. if (multibyte_pending > 0 && !has_next_token) {
  409. has_next_token = true;
  410. n_remain++;
  411. }
  412. if (!has_next_token && n_remain == 0) {
  413. stopped_limit = true;
  414. }
  415. LOG_VERBOSE("next token", {
  416. { "token", token_with_probs.tok },
  417. { "token_text", tokens_to_output_formatted_string(ctx, token_with_probs.tok) },
  418. { "has_next_token", has_next_token },
  419. { "n_remain", n_remain },
  420. { "num_tokens_predicted", num_tokens_predicted },
  421. { "stopped_eos", stopped_eos },
  422. { "stopped_word", stopped_word },
  423. { "stopped_limit", stopped_limit },
  424. { "stopping_word", stopping_word },
  425. });
  426. return token_with_probs;
  427. }
  428. std::vector<float> getEmbedding() {
  429. static const int n_embd = llama_n_embd(ctx);
  430. if (!params.embedding) {
  431. LOG_WARNING("embedding disabled", {
  432. { "params.embedding", params.embedding },
  433. });
  434. return std::vector<float>(n_embd, 0.0f);
  435. }
  436. const float * data = llama_get_embeddings(ctx);
  437. std::vector<float> embedding(data, data + n_embd);
  438. return embedding;
  439. }
  440. };
  441. static void server_print_usage(const char * argv0, const gpt_params & params,
  442. const server_params & sparams) {
  443. fprintf(stderr, "usage: %s [options]\n", argv0);
  444. fprintf(stderr, "\n");
  445. fprintf(stderr, "options:\n");
  446. fprintf(stderr, " -h, --help show this help message and exit\n");
  447. fprintf(stderr, " -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  448. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  449. fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  450. fprintf(stderr, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  451. fprintf(stderr, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  452. fprintf(stderr, " not recommended: doubles context memory required and no measurable increase in quality\n");
  453. if (llama_mlock_supported()) {
  454. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  455. }
  456. if (llama_mmap_supported()) {
  457. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  458. }
  459. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  460. fprintf(stderr, " -ngl N, --n-gpu-layers N\n");
  461. fprintf(stderr, " number of layers to store in VRAM\n");
  462. fprintf(stderr, " -ts SPLIT --tensor-split SPLIT\n");
  463. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  464. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  465. fprintf(stderr, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  466. fprintf(stderr, " -lv, --low-vram don't allocate VRAM scratch buffer\n");
  467. #endif
  468. fprintf(stderr, " -m FNAME, --model FNAME\n");
  469. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  470. fprintf(stderr, " -a ALIAS, --alias ALIAS\n");
  471. fprintf(stderr, " set an alias for the model, will be added as `model` field in completion response\n");
  472. fprintf(stderr, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  473. fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  474. fprintf(stderr, " --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  475. fprintf(stderr, " --port PORT port to listen (default (default: %d)\n", sparams.port);
  476. fprintf(stderr, " -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  477. fprintf(stderr, " --embedding enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  478. fprintf(stderr, "\n");
  479. }
  480. static void server_params_parse(int argc, char ** argv, server_params & sparams,
  481. gpt_params & params) {
  482. gpt_params default_params;
  483. server_params default_sparams;
  484. std::string arg;
  485. bool invalid_param = false;
  486. for (int i = 1; i < argc; i++) {
  487. arg = argv[i];
  488. if (arg == "--port") {
  489. if (++i >= argc) {
  490. invalid_param = true;
  491. break;
  492. }
  493. sparams.port = std::stoi(argv[i]);
  494. } else if (arg == "--host") {
  495. if (++i >= argc) {
  496. invalid_param = true;
  497. break;
  498. }
  499. sparams.hostname = argv[i];
  500. } else if (arg == "--timeout" || arg == "-to") {
  501. if (++i >= argc) {
  502. invalid_param = true;
  503. break;
  504. }
  505. sparams.read_timeout = std::stoi(argv[i]);
  506. sparams.write_timeout = std::stoi(argv[i]);
  507. } else if (arg == "-m" || arg == "--model") {
  508. if (++i >= argc) {
  509. invalid_param = true;
  510. break;
  511. }
  512. params.model = argv[i];
  513. } else if (arg == "-a" || arg == "--alias") {
  514. if (++i >= argc) {
  515. invalid_param = true;
  516. break;
  517. }
  518. params.model_alias = argv[i];
  519. } else if (arg == "-h" || arg == "--help") {
  520. server_print_usage(argv[0], default_params, default_sparams);
  521. exit(0);
  522. } else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size") {
  523. if (++i >= argc) {
  524. invalid_param = true;
  525. break;
  526. }
  527. params.n_ctx = std::stoi(argv[i]);
  528. } else if (arg == "--memory-f32" || arg == "--memory_f32") {
  529. params.memory_f16 = false;
  530. } else if (arg == "--threads" || arg == "-t") {
  531. if (++i >= argc) {
  532. invalid_param = true;
  533. break;
  534. }
  535. params.n_threads = std::stoi(argv[i]);
  536. } else if (arg == "-b" || arg == "--batch-size") {
  537. if (++i >= argc) {
  538. invalid_param = true;
  539. break;
  540. }
  541. params.n_batch = std::stoi(argv[i]);
  542. params.n_batch = std::min(512, params.n_batch);
  543. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  544. if (++i >= argc) {
  545. invalid_param = true;
  546. break;
  547. }
  548. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  549. params.n_gpu_layers = std::stoi(argv[i]);
  550. #else
  551. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  552. "See main README.md for information on enabling GPU BLAS support", { { "n_gpu_layers", params.n_gpu_layers } });
  553. #endif
  554. }
  555. else if (arg == "--tensor-split" || arg == "-ts") {
  556. if (++i >= argc) {
  557. invalid_param = true;
  558. break;
  559. }
  560. #ifdef GGML_USE_CUBLAS
  561. std::string arg_next = argv[i];
  562. // split string by , and /
  563. const std::regex regex{ R"([,/]+)" };
  564. std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
  565. std::vector<std::string> split_arg{ it, {} };
  566. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  567. for (size_t i_device = 0; i_device < LLAMA_MAX_DEVICES; ++i_device) {
  568. if (i_device < split_arg.size()) {
  569. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  570. }
  571. else {
  572. params.tensor_split[i_device] = 0.0f;
  573. }
  574. }
  575. #else
  576. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.", {});
  577. #endif // GGML_USE_CUBLAS
  578. }
  579. else if (arg == "--low-vram" || arg == "-lv")
  580. {
  581. #ifdef GGML_USE_CUBLAS
  582. params.low_vram = true;
  583. #else
  584. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
  585. #endif // GGML_USE_CUBLAS
  586. }
  587. else if (arg == "--main-gpu" || arg == "-mg") {
  588. if (++i >= argc) {
  589. invalid_param = true;
  590. break;
  591. }
  592. #ifdef GGML_USE_CUBLAS
  593. params.main_gpu = std::stoi(argv[i]);
  594. #else
  595. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  596. #endif
  597. } else if (arg == "--lora") {
  598. if (++i >= argc) {
  599. invalid_param = true;
  600. break;
  601. }
  602. params.lora_adapter = argv[i];
  603. params.use_mmap = false;
  604. } else if (arg == "--lora-base") {
  605. if (++i >= argc) {
  606. invalid_param = true;
  607. break;
  608. }
  609. params.lora_base = argv[i];
  610. } else if (arg == "-v" || arg == "--verbose") {
  611. #if SERVER_VERBOSE != 1
  612. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  613. #else
  614. server_verbose = true;
  615. #endif
  616. } else if (arg == "--mlock") {
  617. params.use_mlock = true;
  618. } else if (arg == "--no-mmap") {
  619. params.use_mmap = false;
  620. } else if (arg == "--embedding") {
  621. params.embedding = true;
  622. } else {
  623. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  624. server_print_usage(argv[0], default_params, default_sparams);
  625. exit(1);
  626. }
  627. }
  628. if (invalid_param) {
  629. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  630. server_print_usage(argv[0], default_params, default_sparams);
  631. exit(1);
  632. }
  633. }
  634. static json format_generation_settings(llama_server_context & llama) {
  635. const auto eos_bias = llama.params.logit_bias.find(llama_token_eos());
  636. const bool ignore_eos = eos_bias != llama.params.logit_bias.end() &&
  637. eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  638. return json {
  639. { "seed", llama.params.seed },
  640. { "temp", llama.params.temp },
  641. { "top_k", llama.params.top_k },
  642. { "top_p", llama.params.top_p },
  643. { "tfs_z", llama.params.tfs_z },
  644. { "typical_p", llama.params.typical_p },
  645. { "repeat_last_n", llama.params.repeat_last_n },
  646. { "repeat_penalty", llama.params.repeat_penalty },
  647. { "presence_penalty", llama.params.presence_penalty },
  648. { "frequency_penalty", llama.params.frequency_penalty },
  649. { "mirostat", llama.params.mirostat },
  650. { "mirostat_tau", llama.params.mirostat_tau },
  651. { "mirostat_eta", llama.params.mirostat_eta },
  652. { "penalize_nl", llama.params.penalize_nl },
  653. { "stop", llama.params.antiprompt },
  654. { "n_predict", llama.params.n_predict },
  655. { "n_keep", llama.params.n_keep },
  656. { "ignore_eos", ignore_eos },
  657. { "stream", llama.stream },
  658. { "logit_bias", llama.params.logit_bias },
  659. { "n_probs", llama.params.n_probs },
  660. };
  661. }
  662. static json format_embedding_response(llama_server_context & llama) {
  663. return json {
  664. { "embedding", llama.getEmbedding() },
  665. };
  666. }
  667. static json format_final_response(llama_server_context & llama, const std::string & content, const std::vector<completion_token_output> & probs) {
  668. json res = json {
  669. { "content", content },
  670. { "stop", true },
  671. { "model", llama.params.model_alias },
  672. { "tokens_predicted", llama.num_tokens_predicted },
  673. { "generation_settings", format_generation_settings(llama) },
  674. { "prompt", llama.params.prompt },
  675. { "truncated", llama.truncated },
  676. { "stopped_eos", llama.stopped_eos },
  677. { "stopped_word", llama.stopped_word },
  678. { "stopped_limit", llama.stopped_limit },
  679. { "stopping_word", llama.stopping_word },
  680. };
  681. if (llama.params.n_probs > 0) {
  682. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  683. }
  684. return res;
  685. }
  686. static json format_partial_response(llama_server_context & llama, const std::string & content, const std::vector<completion_token_output> & probs) {
  687. json res = json {
  688. { "content", content },
  689. { "stop", false },
  690. };
  691. if (llama.params.n_probs > 0) {
  692. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  693. }
  694. return res;
  695. }
  696. static json format_tokenizer_response(const std::vector<llama_token> & tokens) {
  697. return json {
  698. { "tokens", tokens }
  699. };
  700. }
  701. static void parse_options_completion(const json & body, llama_server_context & llama) {
  702. gpt_params default_params;
  703. llama.stream = body.value("stream", false);
  704. llama.params.n_predict = body.value("n_predict", default_params.n_predict);
  705. llama.params.top_k = body.value("top_k", default_params.top_k);
  706. llama.params.top_p = body.value("top_p", default_params.top_p);
  707. llama.params.tfs_z = body.value("tfs_z", default_params.tfs_z);
  708. llama.params.typical_p = body.value("typical_p", default_params.typical_p);
  709. llama.params.repeat_last_n = body.value("repeat_last_n", default_params.repeat_last_n);
  710. llama.params.temp = body.value("temperature", default_params.temp);
  711. llama.params.repeat_penalty = body.value("repeat_penalty", default_params.repeat_penalty);
  712. llama.params.presence_penalty = body.value("presence_penalty", default_params.presence_penalty);
  713. llama.params.frequency_penalty = body.value("frequency_penalty", default_params.frequency_penalty);
  714. llama.params.mirostat = body.value("mirostat", default_params.mirostat);
  715. llama.params.mirostat_tau = body.value("mirostat_tau", default_params.mirostat_tau);
  716. llama.params.mirostat_eta = body.value("mirostat_eta", default_params.mirostat_eta);
  717. llama.params.penalize_nl = body.value("penalize_nl", default_params.penalize_nl);
  718. llama.params.n_keep = body.value("n_keep", default_params.n_keep);
  719. llama.params.seed = body.value("seed", default_params.seed);
  720. llama.params.prompt = body.value("prompt", default_params.prompt);
  721. llama.params.n_probs = body.value("n_probs", default_params.n_probs);
  722. llama.params.logit_bias.clear();
  723. if (body.value("ignore_eos", false)) {
  724. llama.params.logit_bias[llama_token_eos()] = -INFINITY;
  725. }
  726. const auto & logit_bias = body.find("logit_bias");
  727. if (logit_bias != body.end() && logit_bias->is_array()) {
  728. const int n_vocab = llama_n_vocab(llama.ctx);
  729. for (const auto & el : *logit_bias) {
  730. if (el.is_array() && el.size() == 2 && el[0].is_number_integer()) {
  731. llama_token tok = el[0].get<llama_token>();
  732. if (tok >= 0 && tok < n_vocab) {
  733. if (el[1].is_number()) {
  734. llama.params.logit_bias[tok] = el[1].get<float>();
  735. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  736. llama.params.logit_bias[tok] = -INFINITY;
  737. }
  738. }
  739. }
  740. }
  741. }
  742. llama.params.antiprompt.clear();
  743. const auto & stop = body.find("stop");
  744. if (stop != body.end() && stop->is_array()) {
  745. for (const auto & word : *stop) {
  746. if (!word.empty()) {
  747. llama.params.antiprompt.push_back(word);
  748. }
  749. }
  750. }
  751. LOG_VERBOSE("completion parameters parsed", format_generation_settings(llama));
  752. }
  753. static void log_server_request(const Request & req, const Response & res) {
  754. LOG_INFO("request", {
  755. { "remote_addr", req.remote_addr },
  756. { "remote_port", req.remote_port },
  757. { "status", res.status },
  758. { "path", req.path },
  759. { "request", req.body },
  760. { "response", res.body },
  761. });
  762. }
  763. int main(int argc, char ** argv) {
  764. // own arguments required by this example
  765. gpt_params params;
  766. server_params sparams;
  767. // struct that contains llama context and inference
  768. llama_server_context llama;
  769. server_params_parse(argc, argv, sparams, params);
  770. if (params.model_alias == "unknown") {
  771. params.model_alias = params.model;
  772. }
  773. llama_init_backend(params.numa);
  774. LOG_INFO("build info", {
  775. { "build", BUILD_NUMBER },
  776. { "commit", BUILD_COMMIT }
  777. });
  778. LOG_INFO("system info", {
  779. { "n_threads", params.n_threads },
  780. { "total_threads", std::thread::hardware_concurrency() },
  781. { "system_info", llama_print_system_info() },
  782. });
  783. // load the model
  784. if (!llama.loadModel(params)) {
  785. return 1;
  786. }
  787. Server svr;
  788. svr.set_default_headers({
  789. { "Access-Control-Allow-Origin", "*" },
  790. { "Access-Control-Allow-Headers", "content-type" }
  791. });
  792. svr.Get("/", [](const Request &, Response & res) {
  793. res.set_content("<h1>llama.cpp server works</h1>", "text/html");
  794. });
  795. svr.Post("/completion", [&llama](const Request & req, Response & res) {
  796. llama.rewind();
  797. llama_reset_timings(llama.ctx);
  798. parse_options_completion(json::parse(req.body), llama);
  799. llama.loadPrompt();
  800. llama.beginCompletion();
  801. if (!llama.stream) {
  802. size_t stop_pos = std::string::npos;
  803. while (llama.has_next_token) {
  804. const completion_token_output token_with_probs = llama.doCompletion();
  805. const std::string token_text = llama_token_to_str(llama.ctx, token_with_probs.tok);
  806. stop_pos = llama.findStoppingStrings(llama.generated_text,
  807. token_text.size(), STOP_FULL);
  808. }
  809. if (stop_pos == std::string::npos) {
  810. stop_pos = llama.findStoppingStrings(llama.generated_text, 0, STOP_PARTIAL);
  811. }
  812. if (stop_pos != std::string::npos) {
  813. llama.generated_text.erase(llama.generated_text.begin() + stop_pos,
  814. llama.generated_text.end());
  815. }
  816. const json data = format_final_response(llama, llama.generated_text, llama.generated_token_probs);
  817. llama_print_timings(llama.ctx);
  818. res.set_content(data.dump(-1, ' ', false, json::error_handler_t::replace),
  819. "application/json");
  820. } else {
  821. const auto chunked_content_provider = [&](size_t, DataSink & sink) {
  822. size_t sent_count = 0;
  823. size_t sent_token_probs_index = 0;
  824. while (llama.has_next_token) {
  825. const completion_token_output token_with_probs = llama.doCompletion();
  826. const std::string token_text = llama_token_to_str(llama.ctx, token_with_probs.tok);
  827. if (llama.multibyte_pending > 0) {
  828. continue;
  829. }
  830. size_t pos = std::min(sent_count, llama.generated_text.size());
  831. const std::string str_test = llama.generated_text.substr(pos);
  832. size_t stop_pos =
  833. llama.findStoppingStrings(str_test, token_text.size(), STOP_FULL);
  834. if (stop_pos != std::string::npos) {
  835. llama.generated_text.erase(
  836. llama.generated_text.begin() + pos + stop_pos,
  837. llama.generated_text.end());
  838. pos = std::min(sent_count, llama.generated_text.size());
  839. } else {
  840. stop_pos = llama.findStoppingStrings(str_test, token_text.size(),
  841. STOP_PARTIAL);
  842. }
  843. const std::string to_send = llama.generated_text.substr(pos, stop_pos);
  844. sent_count += to_send.size();
  845. std::vector<completion_token_output> probs_output = {};
  846. if (llama.params.n_probs > 0) {
  847. const std::vector<llama_token> to_send_toks = llama_tokenize(llama.ctx, to_send, false);
  848. size_t probs_pos = std::min(sent_token_probs_index, llama.generated_token_probs.size());
  849. size_t probs_stop_pos = std::min(sent_token_probs_index + to_send_toks.size(), llama.generated_token_probs.size());
  850. if (probs_pos < probs_stop_pos) {
  851. probs_output = std::vector<completion_token_output>(llama.generated_token_probs.begin() + probs_pos, llama.generated_token_probs.begin() + probs_stop_pos);
  852. }
  853. sent_token_probs_index = probs_stop_pos;
  854. }
  855. const json data = llama.has_next_token
  856. ? format_partial_response(llama, to_send, probs_output)
  857. // Generation is done, send extra information.
  858. : format_final_response(llama, to_send, llama.generated_token_probs);
  859. const std::string str =
  860. "data: " +
  861. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  862. "\n\n";
  863. LOG_VERBOSE("data stream", {
  864. { "to_send", str }
  865. });
  866. if (!sink.write(str.data(), str.size())) {
  867. LOG_VERBOSE("stream closed", {});
  868. llama_print_timings(llama.ctx);
  869. return false;
  870. }
  871. }
  872. llama_print_timings(llama.ctx);
  873. sink.done();
  874. return true;
  875. };
  876. res.set_chunked_content_provider("text/event-stream", chunked_content_provider);
  877. }
  878. });
  879. svr.Options(R"(/.*)", [](const Request &, Response & res) {
  880. return res.set_content("", "application/json");
  881. });
  882. svr.Post("/tokenize", [&llama](const Request & req, Response & res) {
  883. const json body = json::parse(req.body);
  884. const std::string content = body.value("content", "");
  885. const std::vector<llama_token> tokens = llama_tokenize(llama.ctx, content, false);
  886. const json data = format_tokenizer_response(tokens);
  887. return res.set_content(data.dump(), "application/json");
  888. });
  889. svr.Post("/embedding", [&llama](const Request & req, Response & res) {
  890. const json body = json::parse(req.body);
  891. llama.rewind();
  892. llama_reset_timings(llama.ctx);
  893. llama.params.prompt = body.value("content", "");
  894. llama.params.n_predict = 0;
  895. llama.loadPrompt();
  896. llama.beginCompletion();
  897. llama.doCompletion();
  898. const json data = format_embedding_response(llama);
  899. return res.set_content(data.dump(), "application/json");
  900. });
  901. svr.set_logger(log_server_request);
  902. svr.set_exception_handler([](const Request &, Response & res, std::exception_ptr ep) {
  903. const auto * fmt = "500 Internal Server Error\n%s";
  904. char buf[BUFSIZ];
  905. try {
  906. std::rethrow_exception(std::move(ep));
  907. } catch (std::exception & e) {
  908. snprintf(buf, sizeof(buf), fmt, e.what());
  909. } catch (...) {
  910. snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
  911. }
  912. res.set_content(buf, "text/plain");
  913. res.status = 500;
  914. });
  915. // set timeouts and change hostname and port
  916. svr.set_read_timeout(sparams.read_timeout);
  917. svr.set_write_timeout(sparams.write_timeout);
  918. if (!svr.bind_to_port(sparams.hostname, sparams.port)) {
  919. LOG_ERROR("couldn't bind to server socket", {
  920. { "hostname", sparams.hostname },
  921. { "port", sparams.port },
  922. });
  923. return 1;
  924. }
  925. LOG_INFO("HTTP server listening", {
  926. { "hostname", sparams.hostname },
  927. { "port", sparams.port },
  928. });
  929. if (!svr.listen_after_bind()) {
  930. return 1;
  931. }
  932. return 0;
  933. }