llava-cli.cpp 13 KB

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