1
0

server.cpp 43 KB

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