1
0

server.cpp 37 KB

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