1
0

llava-cli.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #include "arg.h"
  2. #include "base64.hpp"
  3. #include "log.h"
  4. #include "common.h"
  5. #include "sampling.h"
  6. #include "clip.h"
  7. #include "llava.h"
  8. #include "llama.h"
  9. #include "ggml.h"
  10. #include <cstdio>
  11. #include <cstdlib>
  12. #include <cstring>
  13. #include <vector>
  14. static bool eval_tokens(struct llama_context * ctx_llama, std::vector<llama_token> tokens, int n_batch, int * n_past) {
  15. int N = (int) tokens.size();
  16. for (int i = 0; i < N; i += n_batch) {
  17. int n_eval = (int) tokens.size() - i;
  18. if (n_eval > n_batch) {
  19. n_eval = n_batch;
  20. }
  21. if (llama_decode(ctx_llama, llama_batch_get_one(&tokens[i], n_eval))) {
  22. LOG_ERR("%s : failed to eval. token %d/%d (batch size %d, n_past %d)\n", __func__, i, N, n_batch, *n_past);
  23. return false;
  24. }
  25. *n_past += n_eval;
  26. }
  27. return true;
  28. }
  29. static bool eval_id(struct llama_context * ctx_llama, int id, int * n_past) {
  30. std::vector<llama_token> tokens;
  31. tokens.push_back(id);
  32. return eval_tokens(ctx_llama, tokens, 1, n_past);
  33. }
  34. static bool eval_string(struct llama_context * ctx_llama, const char* str, int n_batch, int * n_past, bool add_bos){
  35. std::string str2 = str;
  36. std::vector<llama_token> embd_inp = common_tokenize(ctx_llama, str2, add_bos, true);
  37. eval_tokens(ctx_llama, embd_inp, n_batch, n_past);
  38. return true;
  39. }
  40. static const char * sample(struct common_sampler * smpl,
  41. struct llama_context * ctx_llama,
  42. int * n_past) {
  43. const llama_token id = common_sampler_sample(smpl, ctx_llama, -1);
  44. common_sampler_accept(smpl, id, true);
  45. static std::string ret;
  46. if (llama_token_is_eog(llama_get_model(ctx_llama), id)) {
  47. ret = "</s>";
  48. } else {
  49. ret = common_token_to_piece(ctx_llama, id);
  50. }
  51. eval_id(ctx_llama, id, n_past);
  52. return ret.c_str();
  53. }
  54. static const char* IMG_BASE64_TAG_BEGIN = "<img src=\"data:image/jpeg;base64,";
  55. static const char* IMG_BASE64_TAG_END = "\">";
  56. static void find_image_tag_in_prompt(const std::string& prompt, size_t& begin_out, size_t& end_out) {
  57. begin_out = prompt.find(IMG_BASE64_TAG_BEGIN);
  58. end_out = prompt.find(IMG_BASE64_TAG_END, (begin_out == std::string::npos) ? 0UL : begin_out);
  59. }
  60. static bool prompt_contains_image(const std::string& prompt) {
  61. size_t begin, end;
  62. find_image_tag_in_prompt(prompt, begin, end);
  63. return (begin != std::string::npos);
  64. }
  65. // replaces the base64 image tag in the prompt with `replacement`
  66. static llava_image_embed * llava_image_embed_make_with_prompt_base64(struct clip_ctx * ctx_clip, int n_threads, const std::string& prompt) {
  67. size_t img_base64_str_start, img_base64_str_end;
  68. find_image_tag_in_prompt(prompt, img_base64_str_start, img_base64_str_end);
  69. if (img_base64_str_start == std::string::npos || img_base64_str_end == std::string::npos) {
  70. LOG_ERR("%s: invalid base64 image tag. must be %s<base64 byte string>%s\n", __func__, IMG_BASE64_TAG_BEGIN, IMG_BASE64_TAG_END);
  71. return NULL;
  72. }
  73. auto base64_bytes_start = img_base64_str_start + strlen(IMG_BASE64_TAG_BEGIN);
  74. auto base64_bytes_count = img_base64_str_end - base64_bytes_start;
  75. auto base64_str = prompt.substr(base64_bytes_start, base64_bytes_count );
  76. auto required_bytes = base64::required_encode_size(base64_str.size());
  77. auto img_bytes = std::vector<unsigned char>(required_bytes);
  78. base64::decode(base64_str.begin(), base64_str.end(), img_bytes.begin());
  79. auto embed = llava_image_embed_make_with_bytes(ctx_clip, n_threads, img_bytes.data(), img_bytes.size());
  80. if (!embed) {
  81. LOG_ERR("%s: could not load image from base64 string.\n", __func__);
  82. return NULL;
  83. }
  84. return embed;
  85. }
  86. static std::string remove_image_from_prompt(const std::string& prompt, const char * replacement = "") {
  87. size_t begin, end;
  88. find_image_tag_in_prompt(prompt, begin, end);
  89. if (begin == std::string::npos || end == std::string::npos) {
  90. return prompt;
  91. }
  92. auto pre = prompt.substr(0, begin);
  93. auto post = prompt.substr(end + strlen(IMG_BASE64_TAG_END));
  94. return pre + replacement + post;
  95. }
  96. struct llava_context {
  97. struct clip_ctx * ctx_clip = NULL;
  98. struct llama_context * ctx_llama = NULL;
  99. struct llama_model * model = NULL;
  100. };
  101. static void print_usage(int, char ** argv) {
  102. LOG("\n example usage:\n");
  103. LOG("\n %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> --image <path/to/another/image.jpg> [--temp 0.1] [-p \"describe the image in detail.\"]\n", argv[0]);
  104. LOG("\n note: a lower temperature value like 0.1 is recommended for better quality.\n");
  105. }
  106. static struct llava_image_embed * load_image(llava_context * ctx_llava, common_params * params, const std::string & fname) {
  107. // load and preprocess the image
  108. llava_image_embed * embed = NULL;
  109. auto prompt = params->prompt;
  110. if (prompt_contains_image(prompt)) {
  111. if (!params->image.empty()) {
  112. LOG_INF("using base64 encoded image instead of command line image path\n");
  113. }
  114. embed = llava_image_embed_make_with_prompt_base64(ctx_llava->ctx_clip, params->cpuparams.n_threads, prompt);
  115. if (!embed) {
  116. LOG_ERR("%s: can't load image from prompt\n", __func__);
  117. return NULL;
  118. }
  119. params->prompt = remove_image_from_prompt(prompt);
  120. } else {
  121. embed = llava_image_embed_make_with_filename(ctx_llava->ctx_clip, params->cpuparams.n_threads, fname.c_str());
  122. if (!embed) {
  123. fprintf(stderr, "%s: is %s really an image file?\n", __func__, fname.c_str());
  124. return NULL;
  125. }
  126. }
  127. return embed;
  128. }
  129. static void process_prompt(struct llava_context * ctx_llava, struct llava_image_embed * image_embed, common_params * params, const std::string & prompt) {
  130. int n_past = 0;
  131. const int max_tgt_len = params->n_predict < 0 ? 256 : params->n_predict;
  132. std::string system_prompt, user_prompt;
  133. size_t image_pos = prompt.find("<image>");
  134. if (image_pos != std::string::npos) {
  135. // new templating mode: Provide the full prompt including system message and use <image> as a placeholder for the image
  136. system_prompt = prompt.substr(0, image_pos);
  137. user_prompt = prompt.substr(image_pos + std::string("<image>").length());
  138. LOG_INF("system_prompt: %s\n", system_prompt.c_str());
  139. if (params->verbose_prompt) {
  140. auto tmp = common_tokenize(ctx_llava->ctx_llama, system_prompt, true, true);
  141. for (int i = 0; i < (int) tmp.size(); i++) {
  142. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  143. }
  144. }
  145. LOG_INF("user_prompt: %s\n", user_prompt.c_str());
  146. if (params->verbose_prompt) {
  147. auto tmp = common_tokenize(ctx_llava->ctx_llama, user_prompt, true, true);
  148. for (int i = 0; i < (int) tmp.size(); i++) {
  149. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  150. }
  151. }
  152. } else {
  153. // llava-1.5 native mode
  154. 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:";
  155. user_prompt = prompt + "\nASSISTANT:";
  156. if (params->verbose_prompt) {
  157. auto tmp = common_tokenize(ctx_llava->ctx_llama, user_prompt, true, true);
  158. for (int i = 0; i < (int) tmp.size(); i++) {
  159. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  160. }
  161. }
  162. }
  163. eval_string(ctx_llava->ctx_llama, system_prompt.c_str(), params->n_batch, &n_past, true);
  164. llava_eval_image_embed(ctx_llava->ctx_llama, image_embed, params->n_batch, &n_past);
  165. eval_string(ctx_llava->ctx_llama, user_prompt.c_str(), params->n_batch, &n_past, false);
  166. // generate the response
  167. LOG("\n");
  168. struct common_sampler * smpl = common_sampler_init(ctx_llava->model, params->sampling);
  169. if (!smpl) {
  170. LOG_ERR("%s: failed to initialize sampling subsystem\n", __func__);
  171. exit(1);
  172. }
  173. std::string response = "";
  174. for (int i = 0; i < max_tgt_len; i++) {
  175. const char * tmp = sample(smpl, ctx_llava->ctx_llama, &n_past);
  176. response += tmp;
  177. if (strcmp(tmp, "</s>") == 0) break;
  178. if (strstr(tmp, "###")) break; // Yi-VL behavior
  179. LOG("%s", tmp);
  180. if (strstr(response.c_str(), "<|im_end|>")) break; // Yi-34B llava-1.6 - for some reason those decode not as the correct token (tokenizer works)
  181. if (strstr(response.c_str(), "<|im_start|>")) break; // Yi-34B llava-1.6
  182. if (strstr(response.c_str(), "USER:")) break; // mistral llava-1.6
  183. fflush(stdout);
  184. }
  185. common_sampler_free(smpl);
  186. LOG("\n");
  187. }
  188. static struct llama_model * llava_init(common_params * params) {
  189. llama_backend_init();
  190. llama_numa_init(params->numa);
  191. llama_model_params model_params = common_model_params_to_llama(*params);
  192. llama_model * model = llama_load_model_from_file(params->model.c_str(), model_params);
  193. if (model == NULL) {
  194. LOG_ERR("%s: unable to load model\n" , __func__);
  195. return NULL;
  196. }
  197. return model;
  198. }
  199. static struct llava_context * llava_init_context(common_params * params, llama_model * model) {
  200. const char * clip_path = params->mmproj.c_str();
  201. auto prompt = params->prompt;
  202. if (prompt.empty()) {
  203. prompt = "describe the image in detail.";
  204. }
  205. auto ctx_clip = clip_model_load(clip_path, /*verbosity=*/ 1);
  206. llama_context_params ctx_params = common_context_params_to_llama(*params);
  207. ctx_params.n_ctx = params->n_ctx < 2048 ? 2048 : params->n_ctx; // we need a longer context size to process image embeddings
  208. llama_context * ctx_llama = llama_new_context_with_model(model, ctx_params);
  209. if (ctx_llama == NULL) {
  210. LOG_ERR("%s: failed to create the llama_context\n" , __func__);
  211. return NULL;
  212. }
  213. auto * ctx_llava = (struct llava_context *)malloc(sizeof(llava_context));
  214. ctx_llava->ctx_llama = ctx_llama;
  215. ctx_llava->ctx_clip = ctx_clip;
  216. ctx_llava->model = model;
  217. return ctx_llava;
  218. }
  219. static void llava_free(struct llava_context * ctx_llava) {
  220. if (ctx_llava->ctx_clip) {
  221. clip_free(ctx_llava->ctx_clip);
  222. ctx_llava->ctx_clip = NULL;
  223. }
  224. llama_free(ctx_llava->ctx_llama);
  225. llama_free_model(ctx_llava->model);
  226. llama_backend_free();
  227. }
  228. int main(int argc, char ** argv) {
  229. ggml_time_init();
  230. common_params params;
  231. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, print_usage)) {
  232. return 1;
  233. }
  234. common_init();
  235. if (params.mmproj.empty() || (params.image.empty() && !prompt_contains_image(params.prompt))) {
  236. print_usage(argc, argv);
  237. return 1;
  238. }
  239. auto * model = llava_init(&params);
  240. if (model == NULL) {
  241. fprintf(stderr, "%s: error: failed to init llava model\n", __func__);
  242. return 1;
  243. }
  244. if (prompt_contains_image(params.prompt)) {
  245. auto * ctx_llava = llava_init_context(&params, model);
  246. auto * image_embed = load_image(ctx_llava, &params, "");
  247. // process the prompt
  248. process_prompt(ctx_llava, image_embed, &params, params.prompt);
  249. llama_perf_context_print(ctx_llava->ctx_llama);
  250. llava_image_embed_free(image_embed);
  251. ctx_llava->model = NULL;
  252. llava_free(ctx_llava);
  253. } else {
  254. for (auto & image : params.image) {
  255. auto * ctx_llava = llava_init_context(&params, model);
  256. auto * image_embed = load_image(ctx_llava, &params, image);
  257. if (!image_embed) {
  258. LOG_ERR("%s: failed to load image %s. Terminating\n\n", __func__, image.c_str());
  259. return 1;
  260. }
  261. // process the prompt
  262. process_prompt(ctx_llava, image_embed, &params, params.prompt);
  263. llama_perf_context_print(ctx_llava->ctx_llama);
  264. llava_image_embed_free(image_embed);
  265. ctx_llava->model = NULL;
  266. llava_free(ctx_llava);
  267. }
  268. }
  269. llama_free_model(model);
  270. return 0;
  271. }