llava-cli.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. static const char * sample(struct llama_sampling_context * ctx_sampling,
  37. struct llama_context * ctx_llama,
  38. int * n_past) {
  39. const llama_token id = llama_sampling_sample(ctx_sampling, ctx_llama, NULL);
  40. llama_sampling_accept(ctx_sampling, ctx_llama, id, true);
  41. static std::string ret;
  42. if (id == llama_token_eos(llama_get_model(ctx_llama))) {
  43. ret = "</s>";
  44. } else {
  45. ret = llama_token_to_piece(ctx_llama, id);
  46. }
  47. eval_id(ctx_llama, id, n_past);
  48. return ret.c_str();
  49. }
  50. static const char* IMG_BASE64_TAG_BEGIN = "<img src=\"data:image/jpeg;base64,";
  51. static const char* IMG_BASE64_TAG_END = "\">";
  52. static void find_image_tag_in_prompt(const std::string& prompt, size_t& begin_out, size_t& end_out) {
  53. begin_out = prompt.find(IMG_BASE64_TAG_BEGIN);
  54. end_out = prompt.find(IMG_BASE64_TAG_END, (begin_out == std::string::npos) ? 0UL : begin_out);
  55. }
  56. static bool prompt_contains_image(const std::string& prompt) {
  57. size_t begin, end;
  58. find_image_tag_in_prompt(prompt, begin, end);
  59. return (begin != std::string::npos);
  60. }
  61. // replaces the base64 image tag in the prompt with `replacement`
  62. static llava_image_embed * llava_image_embed_make_with_prompt_base64(struct clip_ctx * ctx_clip, int n_threads, const std::string& prompt) {
  63. size_t img_base64_str_start, img_base64_str_end;
  64. find_image_tag_in_prompt(prompt, img_base64_str_start, img_base64_str_end);
  65. if (img_base64_str_start == std::string::npos || img_base64_str_end == std::string::npos) {
  66. fprintf(stderr, "%s: invalid base64 image tag. must be %s<base64 byte string>%s\n", __func__, IMG_BASE64_TAG_BEGIN, IMG_BASE64_TAG_END);
  67. return NULL;
  68. }
  69. auto base64_bytes_start = img_base64_str_start + strlen(IMG_BASE64_TAG_BEGIN);
  70. auto base64_bytes_count = img_base64_str_end - base64_bytes_start;
  71. auto base64_str = prompt.substr(base64_bytes_start, base64_bytes_count );
  72. auto required_bytes = base64::required_encode_size(base64_str.size());
  73. auto img_bytes = std::vector<unsigned char>(required_bytes);
  74. base64::decode(base64_str.begin(), base64_str.end(), img_bytes.begin());
  75. auto embed = llava_image_embed_make_with_bytes(ctx_clip, n_threads, img_bytes.data(), img_bytes.size());
  76. if (!embed) {
  77. fprintf(stderr, "%s: could not load image from base64 string.\n", __func__);
  78. return NULL;
  79. }
  80. return embed;
  81. }
  82. static std::string remove_image_from_prompt(const std::string& prompt, const char * replacement = "") {
  83. size_t begin, end;
  84. find_image_tag_in_prompt(prompt, begin, end);
  85. if (begin == std::string::npos || end == std::string::npos) {
  86. return prompt;
  87. }
  88. auto pre = prompt.substr(0, begin);
  89. auto post = prompt.substr(end + strlen(IMG_BASE64_TAG_END));
  90. return pre + replacement + post;
  91. }
  92. struct llava_context {
  93. struct clip_ctx * ctx_clip = NULL;
  94. struct llama_context * ctx_llama = NULL;
  95. struct llama_model * model = NULL;
  96. };
  97. static void show_additional_info(int /*argc*/, char ** argv) {
  98. fprintf(stderr, "\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]);
  99. fprintf(stderr, " note: a lower temperature value like 0.1 is recommended for better quality.\n");
  100. }
  101. static struct llava_image_embed * load_image(llava_context * ctx_llava, gpt_params * params) {
  102. // load and preprocess the image
  103. llava_image_embed * embed = NULL;
  104. auto prompt = params->prompt;
  105. if (prompt_contains_image(prompt)) {
  106. if (!params->image.empty()) {
  107. fprintf(stderr, "using base64 encoded image instead of command line image path\n");
  108. }
  109. embed = llava_image_embed_make_with_prompt_base64(ctx_llava->ctx_clip, params->n_threads, prompt);
  110. if (!embed) {
  111. fprintf(stderr, "%s: can't load image from prompt\n", __func__);
  112. return NULL;
  113. }
  114. params->prompt = remove_image_from_prompt(prompt);
  115. } else {
  116. embed = llava_image_embed_make_with_filename(ctx_llava->ctx_clip, params->n_threads, params->image.c_str());
  117. if (!embed) {
  118. fprintf(stderr, "%s: is %s really an image file?\n", __func__, params->image.c_str());
  119. return NULL;
  120. }
  121. }
  122. return embed;
  123. }
  124. static void process_prompt(struct llava_context * ctx_llava, struct llava_image_embed * image_embed, gpt_params * params, const std::string & prompt) {
  125. int n_past = 0;
  126. const int max_tgt_len = params->n_predict < 0 ? 256 : params->n_predict;
  127. const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx_llava->ctx_llama));
  128. std::string system_prompt, user_prompt;
  129. size_t image_pos = prompt.find("<image>");
  130. if (image_pos != std::string::npos) {
  131. // new templating mode: Provide the full prompt including system message and use <image> as a placeholder for the image
  132. system_prompt = prompt.substr(0, image_pos);
  133. user_prompt = prompt.substr(image_pos + std::string("<image>").length());
  134. // We replace \n with actual newlines in user_prompt, just in case -e was not used in templating string
  135. size_t pos = 0;
  136. while ((pos = user_prompt.find("\\n", pos)) != std::string::npos) {
  137. user_prompt.replace(pos, 2, "\n");
  138. pos += 1; // Advance past the replaced newline
  139. }
  140. while ((pos = system_prompt.find("\\n", pos)) != std::string::npos) {
  141. system_prompt.replace(pos, 2, "\n");
  142. pos += 1; // Advance past the replaced newline
  143. }
  144. printf("system_prompt: %s\n", system_prompt.c_str());
  145. printf("user_prompt: %s\n", user_prompt.c_str());
  146. } else {
  147. // llava-1.5 native mode
  148. system_prompt = "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:";
  149. user_prompt = prompt + "\nASSISTANT:";
  150. }
  151. eval_string(ctx_llava->ctx_llama, system_prompt.c_str(), params->n_batch, &n_past, add_bos);
  152. llava_eval_image_embed(ctx_llava->ctx_llama, image_embed, params->n_batch, &n_past);
  153. eval_string(ctx_llava->ctx_llama, user_prompt.c_str(), params->n_batch, &n_past, false);
  154. // generate the response
  155. fprintf(stderr, "\n");
  156. struct llama_sampling_context * ctx_sampling = llama_sampling_init(params->sparams);
  157. for (int i = 0; i < max_tgt_len; i++) {
  158. const char * tmp = sample(ctx_sampling, ctx_llava->ctx_llama, &n_past);
  159. if (strcmp(tmp, "</s>") == 0) break;
  160. if (strstr(tmp, "###")) break; // Yi-VL behavior
  161. printf("%s", tmp);
  162. fflush(stdout);
  163. }
  164. llama_sampling_free(ctx_sampling);
  165. printf("\n");
  166. }
  167. static struct llava_context * llava_init(gpt_params * params) {
  168. const char * clip_path = params->mmproj.c_str();
  169. auto prompt = params->prompt;
  170. if (prompt.empty()) {
  171. prompt = "describe the image in detail.";
  172. }
  173. auto ctx_clip = clip_model_load(clip_path, /*verbosity=*/ 1);
  174. llama_backend_init(params->numa);
  175. llama_model_params model_params = llama_model_params_from_gpt_params(*params);
  176. llama_model * model = llama_load_model_from_file(params->model.c_str(), model_params);
  177. if (model == NULL) {
  178. fprintf(stderr , "%s: error: unable to load model\n" , __func__);
  179. return NULL;
  180. }
  181. llama_context_params ctx_params = llama_context_params_from_gpt_params(*params);
  182. ctx_params.n_ctx = params->n_ctx < 2048 ? 2048 : params->n_ctx; // we need a longer context size to process image embeddings
  183. llama_context * ctx_llama = llama_new_context_with_model(model, ctx_params);
  184. if (ctx_llama == NULL) {
  185. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  186. return NULL;
  187. }
  188. auto ctx_llava = (struct llava_context *)malloc(sizeof(llava_context));
  189. ctx_llava->ctx_llama = ctx_llama;
  190. ctx_llava->ctx_clip = ctx_clip;
  191. ctx_llava->model = model;
  192. return ctx_llava;
  193. }
  194. static void llava_free(struct llava_context * ctx_llava) {
  195. if (ctx_llava->ctx_clip) {
  196. clip_free(ctx_llava->ctx_clip);
  197. ctx_llava->ctx_clip = NULL;
  198. }
  199. llama_free(ctx_llava->ctx_llama);
  200. llama_free_model(ctx_llava->model);
  201. llama_backend_free();
  202. }
  203. int main(int argc, char ** argv) {
  204. ggml_time_init();
  205. gpt_params params;
  206. if (!gpt_params_parse(argc, argv, params)) {
  207. show_additional_info(argc, argv);
  208. return 1;
  209. }
  210. if (params.mmproj.empty() || (params.image.empty() && !prompt_contains_image(params.prompt))) {
  211. gpt_print_usage(argc, argv, params);
  212. show_additional_info(argc, argv);
  213. return 1;
  214. }
  215. auto ctx_llava = llava_init(&params);
  216. if (ctx_llava == NULL) {
  217. fprintf(stderr, "%s: error: failed to init llava\n", __func__);
  218. return 1;
  219. }
  220. auto image_embed = load_image(ctx_llava, &params);
  221. if (!image_embed) {
  222. return 1;
  223. }
  224. // process the prompt
  225. process_prompt(ctx_llava, image_embed, &params, params.prompt);
  226. llama_print_timings(ctx_llava->ctx_llama);
  227. llava_image_embed_free(image_embed);
  228. llava_free(ctx_llava);
  229. return 0;
  230. }