llava-cli.cpp 12 KB

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