llava-cli.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #include "ggml.h"
  2. #include "common.h"
  3. #include "clip.h"
  4. #include "llava.h"
  5. #include "llama.h"
  6. #include "base64.hpp"
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <vector>
  10. static bool eval_tokens(struct llama_context * ctx_llama, std::vector<llama_token> tokens, int n_batch, int * n_past) {
  11. int N = (int) tokens.size();
  12. for (int i = 0; i < N; i += n_batch) {
  13. int n_eval = (int) tokens.size() - i;
  14. if (n_eval > n_batch) {
  15. n_eval = n_batch;
  16. }
  17. if (llama_decode(ctx_llama, llama_batch_get_one(&tokens[i], n_eval, *n_past, 0))) {
  18. fprintf(stderr, "%s : failed to eval. token %d/%d (batch size %d, n_past %d)\n", __func__, i, N, n_batch, *n_past);
  19. return false;
  20. }
  21. *n_past += n_eval;
  22. }
  23. return true;
  24. }
  25. static bool eval_id(struct llama_context * ctx_llama, int id, int * n_past) {
  26. std::vector<llama_token> tokens;
  27. tokens.push_back(id);
  28. return eval_tokens(ctx_llama, tokens, 1, n_past);
  29. }
  30. static bool eval_string(struct llama_context * ctx_llama, const char* str, int n_batch, int * n_past, bool add_bos){
  31. std::string str2 = str;
  32. std::vector<llama_token> embd_inp = ::llama_tokenize(ctx_llama, str2, add_bos);
  33. eval_tokens(ctx_llama, embd_inp, n_batch, n_past);
  34. return true;
  35. }
  36. // TODO: use common/sampling.h
  37. static llama_token sample_id(llama_context * ctx_llama, gpt_params & params) {
  38. auto & sparams = params.sparams;
  39. // out of user input, sample next token
  40. const float temp = sparams.temp;
  41. const int32_t top_k = sparams.top_k <= 0 ? llama_n_vocab(llama_get_model(ctx_llama)) : sparams.top_k;
  42. const float top_p = sparams.top_p;
  43. const float tfs_z = sparams.tfs_z;
  44. const float typical_p = sparams.typical_p;
  45. // const int32_t repeat_last_n = sparams.repeat_last_n < 0 ? n_ctx : sparams.repeat_last_n;
  46. // const float repeat_penalty = sparams.repeat_penalty;
  47. // const float alpha_presence = sparams.presence_penalty;
  48. // const float alpha_frequency = sparams.frequency_penalty;
  49. const int mirostat = sparams.mirostat;
  50. const float mirostat_tau = sparams.mirostat_tau;
  51. const float mirostat_eta = sparams.mirostat_eta;
  52. // const bool penalize_nl = sparams.penalize_nl;
  53. llama_token id = 0;
  54. {
  55. auto logits = llama_get_logits(ctx_llama);
  56. auto n_vocab = llama_n_vocab(llama_get_model(ctx_llama));
  57. // Apply params.logit_bias map
  58. for (auto it = sparams.logit_bias.begin(); it != sparams.logit_bias.end(); it++) {
  59. logits[it->first] += it->second;
  60. }
  61. std::vector<llama_token_data> candidates;
  62. candidates.reserve(n_vocab);
  63. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  64. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  65. }
  66. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  67. if (temp <= 0) {
  68. // Greedy sampling
  69. id = llama_sample_token_greedy(ctx_llama, &candidates_p);
  70. } else {
  71. if (mirostat == 1) {
  72. static float mirostat_mu = 2.0f * mirostat_tau;
  73. const int mirostat_m = 100;
  74. llama_sample_temp(ctx_llama, &candidates_p, temp);
  75. id = llama_sample_token_mirostat(ctx_llama, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  76. } else if (mirostat == 2) {
  77. static float mirostat_mu = 2.0f * mirostat_tau;
  78. llama_sample_temp(ctx_llama, &candidates_p, temp);
  79. id = llama_sample_token_mirostat_v2(ctx_llama, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  80. } else {
  81. // Temperature sampling
  82. llama_sample_top_k(ctx_llama, &candidates_p, top_k, 1);
  83. llama_sample_tail_free(ctx_llama, &candidates_p, tfs_z, 1);
  84. llama_sample_typical(ctx_llama, &candidates_p, typical_p, 1);
  85. llama_sample_top_p(ctx_llama, &candidates_p, top_p, 1);
  86. llama_sample_temp(ctx_llama, &candidates_p, temp);
  87. id = llama_sample_token(ctx_llama, &candidates_p);
  88. }
  89. }
  90. }
  91. return id;
  92. }
  93. static const char * sample(struct llama_context * ctx_llama, gpt_params & params, int * n_past) {
  94. int id = sample_id(ctx_llama, params);
  95. static std::string ret;
  96. if (id == llama_token_eos(llama_get_model(ctx_llama))) {
  97. ret = "</s>";
  98. } else {
  99. ret = llama_token_to_piece(ctx_llama, id);
  100. }
  101. eval_id(ctx_llama, id, n_past);
  102. return ret.c_str();
  103. }
  104. static const char* IMG_BASE64_TAG_BEGIN = "<img src=\"data:image/jpeg;base64,";
  105. static const char* IMG_BASE64_TAG_END = "\">";
  106. static void find_image_tag_in_prompt(const std::string& prompt, size_t& begin_out, size_t& end_out) {
  107. begin_out = prompt.find(IMG_BASE64_TAG_BEGIN);
  108. end_out = prompt.find(IMG_BASE64_TAG_END, (begin_out == std::string::npos) ? 0UL : begin_out);
  109. }
  110. static bool prompt_contains_image(const std::string& prompt) {
  111. size_t begin, end;
  112. find_image_tag_in_prompt(prompt, begin, end);
  113. return (begin != std::string::npos);
  114. }
  115. // replaces the base64 image tag in the prompt with `replacement`
  116. static llava_image_embed * llava_image_embed_make_with_prompt_base64(struct clip_ctx * ctx_clip, int n_threads, const std::string& prompt) {
  117. size_t img_base64_str_start, img_base64_str_end;
  118. find_image_tag_in_prompt(prompt, img_base64_str_start, img_base64_str_end);
  119. if (img_base64_str_start == std::string::npos || img_base64_str_end == std::string::npos) {
  120. fprintf(stderr, "%s: invalid base64 image tag. must be %s<base64 byte string>%s\n", __func__, IMG_BASE64_TAG_BEGIN, IMG_BASE64_TAG_END);
  121. return NULL;
  122. }
  123. auto base64_bytes_start = img_base64_str_start + strlen(IMG_BASE64_TAG_BEGIN);
  124. auto base64_bytes_count = img_base64_str_end - base64_bytes_start;
  125. auto base64_str = prompt.substr(base64_bytes_start, base64_bytes_count );
  126. auto required_bytes = base64::required_encode_size(base64_str.size());
  127. auto img_bytes = std::vector<unsigned char>(required_bytes);
  128. base64::decode(base64_str.begin(), base64_str.end(), img_bytes.begin());
  129. auto embed = llava_image_embed_make_with_bytes(ctx_clip, n_threads, img_bytes.data(), img_bytes.size());
  130. if (!embed) {
  131. fprintf(stderr, "%s: could not load image from base64 string.\n", __func__);
  132. return NULL;
  133. }
  134. return embed;
  135. }
  136. static std::string remove_image_from_prompt(const std::string& prompt, const char * replacement = "") {
  137. size_t begin, end;
  138. find_image_tag_in_prompt(prompt, begin, end);
  139. if (begin == std::string::npos || end == std::string::npos) {
  140. return prompt;
  141. }
  142. auto pre = prompt.substr(0, begin);
  143. auto post = prompt.substr(end + strlen(IMG_BASE64_TAG_END));
  144. return pre + replacement + post;
  145. }
  146. struct llava_context {
  147. struct clip_ctx * ctx_clip = NULL;
  148. struct llama_context * ctx_llama = NULL;
  149. struct llama_model * model = NULL;
  150. };
  151. static void show_additional_info(int /*argc*/, char ** argv) {
  152. printf("\n example usage: %s -m <llava-v1.5-7b/ggml-model-q5_k.gguf> --mmproj <llava-v1.5-7b/mmproj-model-f16.gguf> --image <path/to/an/image.jpg> [--temp 0.1] [-p \"describe the image in detail.\"]\n", argv[0]);
  153. printf(" note: a lower temperature value like 0.1 is recommended for better quality.\n");
  154. }
  155. static struct llava_image_embed * load_image(llava_context * ctx_llava, gpt_params * params) {
  156. // load and preprocess the image
  157. llava_image_embed * embed = NULL;
  158. auto prompt = params->prompt;
  159. if (prompt_contains_image(prompt)) {
  160. if (!params->image.empty()) {
  161. printf("using base64 encoded image instead of command line image path\n");
  162. }
  163. embed = llava_image_embed_make_with_prompt_base64(ctx_llava->ctx_clip, params->n_threads, prompt);
  164. if (!embed) {
  165. fprintf(stderr, "%s: can't load image from prompt\n", __func__);
  166. return NULL;
  167. }
  168. params->prompt = remove_image_from_prompt(prompt);
  169. } else {
  170. embed = llava_image_embed_make_with_filename(ctx_llava->ctx_clip, params->n_threads, params->image.c_str());
  171. if (!embed) {
  172. fprintf(stderr, "%s: is %s really an image file?\n", __func__, params->image.c_str());
  173. return NULL;
  174. }
  175. }
  176. return embed;
  177. }
  178. static void process_prompt(struct llava_context * ctx_llava, struct llava_image_embed * image_embed, gpt_params * params, const std::string & prompt) {
  179. int n_past = 0;
  180. const int max_tgt_len = params->n_predict < 0 ? 256 : params->n_predict;
  181. // llava chat format is "<system_prompt>\nUSER:<image_embeddings>\n<textual_prompt>\nASSISTANT:"
  182. eval_string(ctx_llava->ctx_llama, "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\nUSER:", params->n_batch, &n_past, true);
  183. llava_eval_image_embed(ctx_llava->ctx_llama, image_embed, params->n_batch, &n_past);
  184. eval_string(ctx_llava->ctx_llama, (prompt + "\nASSISTANT:").c_str(), params->n_batch, &n_past, false);
  185. // generate the response
  186. printf("\n");
  187. for (int i = 0; i < max_tgt_len; i++) {
  188. const char * tmp = sample(ctx_llava->ctx_llama, *params, &n_past);
  189. if (strcmp(tmp, "</s>") == 0) break;
  190. printf("%s", tmp);
  191. fflush(stdout);
  192. }
  193. printf("\n");
  194. }
  195. static struct llava_context * llava_init(gpt_params * params) {
  196. const char * clip_path = params->mmproj.c_str();
  197. auto prompt = params->prompt;
  198. if (prompt.empty()) {
  199. prompt = "describe the image in detail.";
  200. }
  201. auto ctx_clip = clip_model_load(clip_path, /*verbosity=*/ 1);
  202. llama_backend_init(params->numa);
  203. llama_model_params model_params = llama_model_default_params();
  204. llama_model * model = llama_load_model_from_file(params->model.c_str(), model_params);
  205. if (model == NULL) {
  206. fprintf(stderr , "%s: error: unable to load model\n" , __func__);
  207. return NULL;
  208. }
  209. llama_context_params ctx_params = llama_context_default_params();
  210. ctx_params.n_ctx = params->n_ctx < 2048 ? 2048 : params->n_ctx; // we need a longer context size to process image embeddings
  211. ctx_params.n_threads = params->n_threads;
  212. ctx_params.n_threads_batch = params->n_threads_batch == -1 ? params->n_threads : params->n_threads_batch;
  213. llama_context * ctx_llama = llama_new_context_with_model(model, ctx_params);
  214. if (ctx_llama == NULL) {
  215. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  216. return NULL;
  217. }
  218. auto ctx_llava = (struct llava_context *)malloc(sizeof(llava_context));
  219. ctx_llava->ctx_llama = ctx_llama;
  220. ctx_llava->ctx_clip = ctx_clip;
  221. ctx_llava->model = model;
  222. return ctx_llava;
  223. }
  224. static void llava_free(struct llava_context * ctx_llava) {
  225. if (ctx_llava->ctx_clip) {
  226. clip_free(ctx_llava->ctx_clip);
  227. ctx_llava->ctx_clip = NULL;
  228. }
  229. llama_free(ctx_llava->ctx_llama);
  230. llama_free_model(ctx_llava->model);
  231. llama_backend_free();
  232. }
  233. int main(int argc, char ** argv) {
  234. ggml_time_init();
  235. gpt_params params;
  236. if (!gpt_params_parse(argc, argv, params)) {
  237. show_additional_info(argc, argv);
  238. return 1;
  239. }
  240. if (params.mmproj.empty() || (params.image.empty() && !prompt_contains_image(params.prompt))) {
  241. gpt_print_usage(argc, argv, params);
  242. show_additional_info(argc, argv);
  243. return 1;
  244. }
  245. auto ctx_llava = llava_init(&params);
  246. if (ctx_llava == NULL) {
  247. fprintf(stderr, "%s: error: failed to init llava\n", __func__);
  248. return 1;
  249. }
  250. auto image_embed = load_image(ctx_llava, &params);
  251. // process the prompt
  252. process_prompt(ctx_llava, image_embed, &params, params.prompt);
  253. llama_print_timings(ctx_llava->ctx_llama);
  254. llava_image_embed_free(image_embed);
  255. llava_free(ctx_llava);
  256. return 0;
  257. }