minicpmv-cli.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #include "arg.h"
  2. #include "log.h"
  3. #include "common.h"
  4. #include "sampling.h"
  5. #include "clip.h"
  6. #include "llava.h"
  7. #include "llama.h"
  8. #include "ggml.h"
  9. #include <algorithm>
  10. #include <cstdio>
  11. #include <cstdlib>
  12. #include <cstring>
  13. #include <vector>
  14. #include <iostream> // TODO: remove me
  15. struct llava_context {
  16. struct clip_ctx * ctx_clip = NULL;
  17. struct llama_context * ctx_llama = NULL;
  18. struct llama_model * model = NULL;
  19. };
  20. static void show_additional_info(int /*argc*/, char ** argv) {
  21. LOG("\nexample usage:\n\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]);
  22. LOG("\nnote: a lower temperature value like 0.1 is recommended for better quality.\n");
  23. }
  24. static struct llama_model * llava_init(common_params * params) {
  25. llama_backend_init();
  26. llama_numa_init(params->numa);
  27. llama_model_params model_params = common_model_params_to_llama(*params);
  28. llama_model * model = llama_model_load_from_file(params->model.c_str(), model_params);
  29. if (model == NULL) {
  30. LOG_ERR("%s: unable to load model\n" , __func__);
  31. return NULL;
  32. }
  33. return model;
  34. }
  35. static struct llava_context * llava_init_context(common_params * params, llama_model * model) {
  36. auto prompt = params->prompt;
  37. if (prompt.empty()) {
  38. prompt = "describe the image in detail.";
  39. }
  40. llama_context_params ctx_params = common_context_params_to_llama(*params);
  41. if (params->n_ctx < 2048) {
  42. // warn user here, "Image processing requires at least 2048 context, setting context to 2048"
  43. LOG_WRN("%s: Image processing requires at least 2048 context, setting context to 2048\n" , __func__);
  44. ctx_params.n_ctx = 2048;
  45. } else {
  46. ctx_params.n_ctx = params->n_ctx;
  47. }
  48. llama_context * ctx_llama = llama_init_from_model(model, ctx_params);
  49. if (ctx_llama == NULL) {
  50. LOG_ERR("%s: failed to create the llama_context\n" , __func__);
  51. return NULL;
  52. }
  53. auto * ctx_llava = (struct llava_context *)malloc(sizeof(llava_context));
  54. ctx_llava->ctx_llama = ctx_llama;
  55. ctx_llava->model = model;
  56. return ctx_llava;
  57. }
  58. static void llava_free(struct llava_context * ctx_llava) {
  59. if (ctx_llava->ctx_clip) {
  60. clip_free(ctx_llava->ctx_clip);
  61. ctx_llava->ctx_clip = NULL;
  62. }
  63. llama_free(ctx_llava->ctx_llama);
  64. llama_model_free(ctx_llava->model);
  65. llama_backend_free();
  66. }
  67. static struct clip_ctx * clip_init_context(common_params * params) {
  68. const char * clip_path = params->mmproj.c_str();
  69. auto prompt = params->prompt;
  70. if (prompt.empty()) {
  71. prompt = "describe the image in detail.";
  72. }
  73. auto * ctx_clip = clip_model_load(clip_path, /*verbosity=*/ 1);
  74. return ctx_clip;
  75. }
  76. static bool eval_tokens(struct llama_context * ctx_llama, std::vector<llama_token> tokens, int n_batch, int * n_past) {
  77. int N = (int) tokens.size();
  78. for (int i = 0; i < N; i += n_batch) {
  79. int n_eval = (int) tokens.size() - i;
  80. if (n_eval > n_batch) {
  81. n_eval = n_batch;
  82. }
  83. if (llama_decode(ctx_llama, llama_batch_get_one(&tokens[i], n_eval))) {
  84. LOG_ERR("%s : failed to eval. token %d/%d (batch size %d, n_past %d)\n", __func__, i, N, n_batch, *n_past);
  85. return false;
  86. }
  87. *n_past += n_eval;
  88. }
  89. return true;
  90. }
  91. static bool eval_id(struct llama_context * ctx_llama, int id, int * n_past) {
  92. std::vector<llama_token> tokens;
  93. tokens.push_back(id);
  94. return eval_tokens(ctx_llama, tokens, 1, n_past);
  95. }
  96. static bool eval_string(struct llama_context * ctx_llama, const char* str, int n_batch, int * n_past, bool add_bos){
  97. std::string str2 = str;
  98. std::vector<llama_token> embd_inp = common_tokenize(ctx_llama, str2, add_bos, true);
  99. return eval_tokens(ctx_llama, embd_inp, n_batch, n_past);
  100. }
  101. static void process_eval_image_embed(struct llava_context * ctx_llava, const struct llava_image_embed * embeds, int n_batch, int * n_past, int idx) {
  102. float * image_embed = (float *)malloc(clip_embd_nbytes(ctx_llava->ctx_clip));
  103. std::memcpy(image_embed, embeds->embed + idx * clip_n_patches(ctx_llava->ctx_clip) * clip_n_mmproj_embd(ctx_llava->ctx_clip), clip_embd_nbytes(ctx_llava->ctx_clip));
  104. auto * slice_embed = (llava_image_embed*)malloc(sizeof(llava_image_embed));
  105. slice_embed->embed = image_embed;
  106. slice_embed->n_image_pos = clip_n_patches(ctx_llava->ctx_clip);
  107. llava_eval_image_embed(ctx_llava->ctx_llama, slice_embed, n_batch, n_past);
  108. llava_image_embed_free(slice_embed);
  109. }
  110. static void process_image(struct llava_context * ctx_llava, struct llava_image_embed * embeds, common_params * params, int &n_past) {
  111. std::string system_prompt;
  112. int idx = 0;
  113. int num_image_embeds = embeds->n_image_pos / clip_n_patches(ctx_llava->ctx_clip);
  114. int has_minicpmv_projector = clip_is_minicpmv(ctx_llava->ctx_clip);
  115. if (has_minicpmv_projector == 2) {
  116. system_prompt = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n";
  117. }
  118. else if (has_minicpmv_projector == 3) {
  119. system_prompt = "<|im_start|>user\n";
  120. }
  121. else if (has_minicpmv_projector == 4) {
  122. system_prompt = "<|im_start|>user\n";
  123. }
  124. LOG_INF("%s: image token past: %d\n", __func__, n_past);
  125. eval_string(ctx_llava->ctx_llama, (system_prompt+"<image>").c_str(), params->n_batch, &n_past, false);
  126. process_eval_image_embed(ctx_llava, embeds, params->n_batch, &n_past, idx++);
  127. eval_string(ctx_llava->ctx_llama, std::string("</image>").c_str(), params->n_batch, &n_past, false);
  128. if (num_image_embeds > 1) {
  129. size_t num_image_embeds_col = clip_uhd_num_image_embeds_col(ctx_llava->ctx_clip);
  130. eval_string(ctx_llava->ctx_llama, std::string("<slice>").c_str(), params->n_batch, &n_past, false);
  131. for (size_t i = 0; i < (num_image_embeds-1)/num_image_embeds_col; ++i) {
  132. for (size_t j = 0; j < num_image_embeds_col; ++j) {
  133. eval_string(ctx_llava->ctx_llama, std::string("<image>").c_str(), params->n_batch, &n_past, false);
  134. process_eval_image_embed(ctx_llava, embeds, params->n_batch, &n_past, idx++);
  135. eval_string(ctx_llava->ctx_llama, std::string("</image>").c_str(), params->n_batch, &n_past, false);
  136. if (j == num_image_embeds_col - 1) {
  137. eval_string(ctx_llava->ctx_llama, std::string("\n").c_str(), params->n_batch, &n_past, false);
  138. }
  139. }
  140. }
  141. eval_string(ctx_llava->ctx_llama, std::string("</slice>").c_str(), params->n_batch, &n_past, false);
  142. }
  143. LOG_INF("%s: image token past: %d\n", __func__, n_past);
  144. }
  145. static const char * sample(struct common_sampler * smpl,
  146. struct llama_context * ctx_llama,
  147. int * n_past) {
  148. const llama_token id = common_sampler_sample(smpl, ctx_llama, -1);
  149. common_sampler_accept(smpl, id, true);
  150. const llama_model * model = llama_get_model(ctx_llama);
  151. const llama_vocab * vocab = llama_model_get_vocab(model);
  152. static std::string ret;
  153. if (llama_vocab_is_eog(vocab, id)) {
  154. ret = "</s>";
  155. } else {
  156. ret = common_token_to_piece(ctx_llama, id);
  157. }
  158. eval_id(ctx_llama, id, n_past);
  159. return ret.c_str();
  160. }
  161. static struct llava_context * minicpmv_init(common_params * params, const std::string & fname, int &n_past){
  162. auto * ctx_clip = clip_init_context(params);
  163. auto * embeds = llava_image_embed_make_with_filename(ctx_clip, params->cpuparams.n_threads, fname.c_str());
  164. if (!embeds) {
  165. LOG_ERR("failed to load image %s. Terminating\n\n", fname.c_str());
  166. return NULL;
  167. }
  168. // process the prompt
  169. if (params->prompt.empty() && params->interactive == false) {
  170. LOG_ERR("prompt should be given or interactive mode should be on");
  171. return NULL;
  172. }
  173. auto * model = llava_init(params);
  174. if (model == NULL) {
  175. fprintf(stderr, "%s: error: failed to init minicpmv model\n", __func__);
  176. return NULL;
  177. }
  178. const int64_t t_llava_init_start_us = ggml_time_us();
  179. auto * ctx_llava = llava_init_context(params, model);
  180. ctx_llava->ctx_clip = ctx_clip;
  181. const int64_t t_llava_init_end_us = ggml_time_us();
  182. float t_llava_init_ms = (t_llava_init_end_us - t_llava_init_start_us) / 1000.0;
  183. LOG_INF("%s: llava init in %8.2f ms.\n", __func__, t_llava_init_ms);
  184. const int64_t t_process_image_start_us = ggml_time_us();
  185. process_image(ctx_llava, embeds, params, n_past);
  186. const int64_t t_process_image_end_us = ggml_time_us();
  187. float t_process_image_ms = (t_process_image_end_us - t_process_image_start_us) / 1000.0;
  188. LOG_INF("%s: llama process image in %8.2f ms.\n", __func__, t_process_image_ms);
  189. llava_image_embed_free(embeds);
  190. return ctx_llava;
  191. }
  192. static struct common_sampler * llama_init(struct llava_context * ctx_llava, common_params * params, const std::string & prompt, int & n_past, bool is_first = false){
  193. std::string user_prompt = prompt;
  194. int has_minicpmv_projector = clip_is_minicpmv(ctx_llava->ctx_clip);
  195. if (!is_first) {
  196. if (has_minicpmv_projector == 2) {
  197. user_prompt = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" + prompt;
  198. }
  199. else if (has_minicpmv_projector == 3) {
  200. user_prompt = "<|im_start|>user\n" + prompt;
  201. }
  202. else if (has_minicpmv_projector == 4) {
  203. user_prompt = "<|im_start|>user\n" + prompt;
  204. }
  205. }
  206. eval_string(ctx_llava->ctx_llama, user_prompt.c_str(), params->n_batch, &n_past, false);
  207. if (has_minicpmv_projector == 2) {
  208. eval_string(ctx_llava->ctx_llama, "<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n", params->n_batch, &n_past, false);
  209. }
  210. else if (has_minicpmv_projector == 3) {
  211. eval_string(ctx_llava->ctx_llama, "<|im_end|><|im_start|>assistant\n", params->n_batch, &n_past, false);
  212. }
  213. else if (has_minicpmv_projector == 4) {
  214. eval_string(ctx_llava->ctx_llama, "<|im_end|><|im_start|>assistant\n", params->n_batch, &n_past, false);
  215. }
  216. // generate the response
  217. LOG_INF("\n");
  218. struct common_sampler * smpl = common_sampler_init(ctx_llava->model, params->sampling);
  219. return smpl;
  220. }
  221. static const char * llama_loop(struct llava_context * ctx_llava,struct common_sampler * smpl, int &n_past){
  222. const char * tmp = sample(smpl, ctx_llava->ctx_llama, &n_past);
  223. return tmp;
  224. }
  225. int main(int argc, char ** argv) {
  226. ggml_time_init();
  227. common_params params;
  228. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  229. return 1;
  230. }
  231. common_init();
  232. if (params.mmproj.empty() || (params.image.empty())) {
  233. show_additional_info(argc, argv);
  234. return 1;
  235. }
  236. for (auto & image : params.image) {
  237. int n_past = 0;
  238. auto * ctx_llava = minicpmv_init(&params, image, n_past);
  239. if (!params.prompt.empty()) {
  240. LOG("<user>%s\n", params.prompt.c_str());
  241. LOG("<assistant>");
  242. auto * smpl = llama_init(ctx_llava, &params, params.prompt, n_past, true);
  243. const int max_tgt_len = params.n_predict < 0 ? 256 : params.n_predict;
  244. std::string response;
  245. bool have_tmp = false;
  246. for (int i = 0; i < max_tgt_len; i++) {
  247. const auto * tmp = llama_loop(ctx_llava, smpl, n_past);
  248. response += tmp;
  249. if (strcmp(tmp, "</s>") == 0){
  250. if (!have_tmp) {
  251. continue;
  252. }
  253. break;
  254. }
  255. if (strstr(tmp, "###")) break; // Yi-VL behavior
  256. have_tmp = true;
  257. printf("%s", tmp);
  258. if (strstr(response.c_str(), "<user>")) break; // minicpm-v
  259. fflush(stdout);
  260. }
  261. common_sampler_free(smpl);
  262. }else {
  263. while (true) {
  264. LOG("<user>");
  265. std::string prompt;
  266. std::getline(std::cin, prompt);
  267. LOG("<assistant>");
  268. auto * smpl = llama_init(ctx_llava, &params, prompt, n_past, true);
  269. const int max_tgt_len = params.n_predict < 0 ? 256 : params.n_predict;
  270. std::string response;
  271. for (int i = 0; i < max_tgt_len; i++) {
  272. const auto * tmp = llama_loop(ctx_llava, smpl, n_past);
  273. response += tmp;
  274. if (strcmp(tmp, "</s>") == 0) break;
  275. printf("%s", tmp);// mistral llava-1.6
  276. if (strstr(response.c_str(), "<user>")) break; // minicpm-v
  277. fflush(stdout);
  278. }
  279. common_sampler_free(smpl);
  280. }
  281. }
  282. printf("\n");
  283. llama_perf_context_print(ctx_llava->ctx_llama);
  284. ctx_llava->model = NULL;
  285. llava_free(ctx_llava);
  286. }
  287. return 0;
  288. }