llava-cli.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 argc, char ** argv, const gpt_params & params) {
  99. gpt_params_print_usage(argc, argv, params);
  100. LOG_TEE("\n example usage:\n");
  101. 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]);
  102. LOG_TEE("\n note: a lower temperature value like 0.1 is recommended for better quality.\n");
  103. }
  104. static struct llava_image_embed * load_image(llava_context * ctx_llava, gpt_params * params, const std::string & fname) {
  105. // load and preprocess the image
  106. llava_image_embed * embed = NULL;
  107. auto prompt = params->prompt;
  108. if (prompt_contains_image(prompt)) {
  109. if (!params->image.empty()) {
  110. LOG_TEE("using base64 encoded image instead of command line image path\n");
  111. }
  112. embed = llava_image_embed_make_with_prompt_base64(ctx_llava->ctx_clip, params->cpuparams.n_threads, prompt);
  113. if (!embed) {
  114. LOG_TEE("%s: can't load image from prompt\n", __func__);
  115. return NULL;
  116. }
  117. params->prompt = remove_image_from_prompt(prompt);
  118. } else {
  119. embed = llava_image_embed_make_with_filename(ctx_llava->ctx_clip, params->cpuparams.n_threads, fname.c_str());
  120. if (!embed) {
  121. fprintf(stderr, "%s: is %s really an image file?\n", __func__, fname.c_str());
  122. return NULL;
  123. }
  124. }
  125. return embed;
  126. }
  127. static void process_prompt(struct llava_context * ctx_llava, struct llava_image_embed * image_embed, gpt_params * params, const std::string & prompt) {
  128. int n_past = 0;
  129. const int max_tgt_len = params->n_predict < 0 ? 256 : params->n_predict;
  130. std::string system_prompt, user_prompt;
  131. size_t image_pos = prompt.find("<image>");
  132. if (image_pos != std::string::npos) {
  133. // new templating mode: Provide the full prompt including system message and use <image> as a placeholder for the image
  134. system_prompt = prompt.substr(0, image_pos);
  135. user_prompt = prompt.substr(image_pos + std::string("<image>").length());
  136. LOG_TEE("system_prompt: %s\n", system_prompt.c_str());
  137. if (params->verbose_prompt) {
  138. auto tmp = ::llama_tokenize(ctx_llava->ctx_llama, system_prompt, true, true);
  139. for (int i = 0; i < (int) tmp.size(); i++) {
  140. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  141. }
  142. }
  143. LOG_TEE("user_prompt: %s\n", user_prompt.c_str());
  144. if (params->verbose_prompt) {
  145. auto tmp = ::llama_tokenize(ctx_llava->ctx_llama, user_prompt, true, true);
  146. for (int i = 0; i < (int) tmp.size(); i++) {
  147. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  148. }
  149. }
  150. } else {
  151. // llava-1.5 native mode
  152. 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:";
  153. user_prompt = prompt + "\nASSISTANT:";
  154. if (params->verbose_prompt) {
  155. auto tmp = ::llama_tokenize(ctx_llava->ctx_llama, user_prompt, true, true);
  156. for (int i = 0; i < (int) tmp.size(); i++) {
  157. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  158. }
  159. }
  160. }
  161. eval_string(ctx_llava->ctx_llama, system_prompt.c_str(), params->n_batch, &n_past, true);
  162. llava_eval_image_embed(ctx_llava->ctx_llama, image_embed, params->n_batch, &n_past);
  163. eval_string(ctx_llava->ctx_llama, user_prompt.c_str(), params->n_batch, &n_past, false);
  164. // generate the response
  165. LOG_TEE("\n");
  166. struct gpt_sampler * smpl = gpt_sampler_init(ctx_llava->model, params->sparams);
  167. if (!smpl) {
  168. fprintf(stderr, "%s: failed to initialize sampling subsystem\n", __func__);
  169. exit(1);
  170. }
  171. std::string response = "";
  172. for (int i = 0; i < max_tgt_len; i++) {
  173. const char * tmp = sample(smpl, ctx_llava->ctx_llama, &n_past);
  174. response += tmp;
  175. if (strcmp(tmp, "</s>") == 0) break;
  176. if (strstr(tmp, "###")) break; // Yi-VL behavior
  177. printf("%s", tmp);
  178. 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)
  179. if (strstr(response.c_str(), "<|im_start|>")) break; // Yi-34B llava-1.6
  180. if (strstr(response.c_str(), "USER:")) break; // mistral llava-1.6
  181. fflush(stdout);
  182. }
  183. gpt_sampler_free(smpl);
  184. printf("\n");
  185. }
  186. static struct llama_model * llava_init(gpt_params * params) {
  187. llama_backend_init();
  188. llama_numa_init(params->numa);
  189. llama_model_params model_params = llama_model_params_from_gpt_params(*params);
  190. llama_model * model = llama_load_model_from_file(params->model.c_str(), model_params);
  191. if (model == NULL) {
  192. LOG_TEE("%s: error: unable to load model\n" , __func__);
  193. return NULL;
  194. }
  195. return model;
  196. }
  197. static struct llava_context * llava_init_context(gpt_params * params, llama_model * model) {
  198. const char * clip_path = params->mmproj.c_str();
  199. auto prompt = params->prompt;
  200. if (prompt.empty()) {
  201. prompt = "describe the image in detail.";
  202. }
  203. auto ctx_clip = clip_model_load(clip_path, /*verbosity=*/ 1);
  204. llama_context_params ctx_params = llama_context_params_from_gpt_params(*params);
  205. ctx_params.n_ctx = params->n_ctx < 2048 ? 2048 : params->n_ctx; // we need a longer context size to process image embeddings
  206. llama_context * ctx_llama = llama_new_context_with_model(model, ctx_params);
  207. if (ctx_llama == NULL) {
  208. LOG_TEE("%s: error: failed to create the llama_context\n" , __func__);
  209. return NULL;
  210. }
  211. auto ctx_llava = (struct llava_context *)malloc(sizeof(llava_context));
  212. ctx_llava->ctx_llama = ctx_llama;
  213. ctx_llava->ctx_clip = ctx_clip;
  214. ctx_llava->model = model;
  215. return ctx_llava;
  216. }
  217. static void llava_free(struct llava_context * ctx_llava) {
  218. if (ctx_llava->ctx_clip) {
  219. clip_free(ctx_llava->ctx_clip);
  220. ctx_llava->ctx_clip = NULL;
  221. }
  222. llama_free(ctx_llava->ctx_llama);
  223. llama_free_model(ctx_llava->model);
  224. llama_backend_free();
  225. }
  226. static void llama_log_callback_logTee(ggml_log_level level, const char * text, void * user_data) {
  227. (void) level;
  228. (void) user_data;
  229. LOG_TEE("%s", text);
  230. }
  231. int main(int argc, char ** argv) {
  232. ggml_time_init();
  233. gpt_params params;
  234. if (!gpt_params_parse(argc, argv, params)) {
  235. print_usage(argc, argv, params);
  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_print(ctx_llava->ctx_llama, LLAMA_PERF_TYPE_CONTEXT);
  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_print(ctx_llava->ctx_llama, LLAMA_PERF_TYPE_CONTEXT);
  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. }