server.cpp 36 KB

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