llava-cli.cpp 12 KB

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