minicpmv-cli.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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.path.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.path.c_str();
  69. auto prompt = params->prompt;
  70. if (prompt.empty()) {
  71. prompt = "describe the image in detail.";
  72. }
  73. struct clip_context_params clip_params = {
  74. /* use_gpu */ params->n_gpu_layers != 0,
  75. /* verbosity */ params->verbosity,
  76. };
  77. auto * ctx_clip = clip_init(clip_path, clip_params);
  78. return ctx_clip;
  79. }
  80. static bool eval_tokens(struct llama_context * ctx_llama, std::vector<llama_token> tokens, int n_batch, int * n_past) {
  81. int N = (int) tokens.size();
  82. for (int i = 0; i < N; i += n_batch) {
  83. int n_eval = (int) tokens.size() - i;
  84. if (n_eval > n_batch) {
  85. n_eval = n_batch;
  86. }
  87. if (llama_decode(ctx_llama, llama_batch_get_one(&tokens[i], n_eval))) {
  88. LOG_ERR("%s : failed to eval. token %d/%d (batch size %d, n_past %d)\n", __func__, i, N, n_batch, *n_past);
  89. return false;
  90. }
  91. *n_past += n_eval;
  92. }
  93. return true;
  94. }
  95. static bool eval_id(struct llama_context * ctx_llama, int id, int * n_past) {
  96. std::vector<llama_token> tokens;
  97. tokens.push_back(id);
  98. return eval_tokens(ctx_llama, tokens, 1, n_past);
  99. }
  100. static bool eval_string(struct llama_context * ctx_llama, const char* str, int n_batch, int * n_past, bool add_bos){
  101. std::string str2 = str;
  102. std::vector<llama_token> embd_inp = common_tokenize(ctx_llama, str2, add_bos, true);
  103. return eval_tokens(ctx_llama, embd_inp, n_batch, n_past);
  104. }
  105. 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) {
  106. float * image_embed = (float *)malloc(clip_embd_nbytes(ctx_llava->ctx_clip));
  107. 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));
  108. auto * slice_embed = (llava_image_embed*)malloc(sizeof(llava_image_embed));
  109. slice_embed->embed = image_embed;
  110. slice_embed->n_image_pos = clip_n_patches(ctx_llava->ctx_clip);
  111. llava_eval_image_embed(ctx_llava->ctx_llama, slice_embed, n_batch, n_past);
  112. llava_image_embed_free(slice_embed);
  113. }
  114. static void process_image(struct llava_context * ctx_llava, struct llava_image_embed * embeds, common_params * params, int &n_past) {
  115. std::string system_prompt;
  116. int idx = 0;
  117. int num_image_embeds = embeds->n_image_pos / clip_n_patches(ctx_llava->ctx_clip);
  118. int has_minicpmv_projector = clip_is_minicpmv(ctx_llava->ctx_clip);
  119. if (has_minicpmv_projector == 2) {
  120. system_prompt = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n";
  121. }
  122. else if (has_minicpmv_projector == 3) {
  123. system_prompt = "<|im_start|>user\n";
  124. }
  125. else if (has_minicpmv_projector == 4) {
  126. system_prompt = "<|im_start|>user\n";
  127. }
  128. LOG_INF("%s: image token past: %d\n", __func__, n_past);
  129. eval_string(ctx_llava->ctx_llama, (system_prompt+"<image>").c_str(), params->n_batch, &n_past, false);
  130. process_eval_image_embed(ctx_llava, embeds, params->n_batch, &n_past, idx++);
  131. eval_string(ctx_llava->ctx_llama, std::string("</image>").c_str(), params->n_batch, &n_past, false);
  132. if (num_image_embeds > 1) {
  133. if (has_minicpmv_projector == 2) {
  134. size_t num_image_embeds_col = clip_uhd_num_image_embeds_col(ctx_llava->ctx_clip);
  135. eval_string(ctx_llava->ctx_llama, std::string("<slice>").c_str(), params->n_batch, &n_past, false);
  136. for (size_t i = 0; i < (num_image_embeds-1)/num_image_embeds_col; ++i) {
  137. for (size_t j = 0; j < num_image_embeds_col; ++j) {
  138. eval_string(ctx_llava->ctx_llama, std::string("<image>").c_str(), params->n_batch, &n_past, false);
  139. process_eval_image_embed(ctx_llava, embeds, params->n_batch, &n_past, idx++);
  140. eval_string(ctx_llava->ctx_llama, std::string("</image>").c_str(), params->n_batch, &n_past, false);
  141. if (j == num_image_embeds_col - 1) {
  142. eval_string(ctx_llava->ctx_llama, std::string("\n").c_str(), params->n_batch, &n_past, false);
  143. }
  144. }
  145. }
  146. eval_string(ctx_llava->ctx_llama, std::string("</slice>").c_str(), params->n_batch, &n_past, false);
  147. }
  148. else if (has_minicpmv_projector == 3 || has_minicpmv_projector == 4) {
  149. size_t num_image_embeds_col = clip_uhd_num_image_embeds_col(ctx_llava->ctx_clip);
  150. for (size_t i = 0; i < (num_image_embeds-1)/num_image_embeds_col; ++i) {
  151. for (size_t j = 0; j < num_image_embeds_col; ++j) {
  152. eval_string(ctx_llava->ctx_llama, std::string("<slice>").c_str(), params->n_batch, &n_past, false);
  153. process_eval_image_embed(ctx_llava, embeds, params->n_batch, &n_past, idx++);
  154. eval_string(ctx_llava->ctx_llama, std::string("</slice>").c_str(), params->n_batch, &n_past, false);
  155. if (j == num_image_embeds_col - 1) {
  156. eval_string(ctx_llava->ctx_llama, std::string("\n").c_str(), params->n_batch, &n_past, false);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. LOG_INF("%s: image token past: %d\n", __func__, n_past);
  163. }
  164. static const char * sample(struct common_sampler * smpl,
  165. struct llama_context * ctx_llama,
  166. int * n_past) {
  167. const llama_token id = common_sampler_sample(smpl, ctx_llama, -1);
  168. common_sampler_accept(smpl, id, true);
  169. const llama_model * model = llama_get_model(ctx_llama);
  170. const llama_vocab * vocab = llama_model_get_vocab(model);
  171. static std::string ret;
  172. if (llama_vocab_is_eog(vocab, id)) {
  173. ret = "</s>";
  174. } else {
  175. ret = common_token_to_piece(ctx_llama, id);
  176. }
  177. eval_id(ctx_llama, id, n_past);
  178. return ret.c_str();
  179. }
  180. static struct llava_context * minicpmv_init(common_params * params, const std::string & fname, int &n_past){
  181. auto * ctx_clip = clip_init_context(params);
  182. auto * embeds = llava_image_embed_make_with_filename(ctx_clip, params->cpuparams.n_threads, fname.c_str());
  183. if (!embeds) {
  184. LOG_ERR("failed to load image %s. Terminating\n\n", fname.c_str());
  185. return NULL;
  186. }
  187. // process the prompt
  188. if (params->prompt.empty() && params->interactive == false) {
  189. LOG_ERR("prompt should be given or interactive mode should be on");
  190. return NULL;
  191. }
  192. auto * model = llava_init(params);
  193. if (model == NULL) {
  194. fprintf(stderr, "%s: error: failed to init minicpmv model\n", __func__);
  195. return NULL;
  196. }
  197. const int64_t t_llava_init_start_us = ggml_time_us();
  198. auto * ctx_llava = llava_init_context(params, model);
  199. ctx_llava->ctx_clip = ctx_clip;
  200. const int64_t t_llava_init_end_us = ggml_time_us();
  201. float t_llava_init_ms = (t_llava_init_end_us - t_llava_init_start_us) / 1000.0;
  202. LOG_INF("%s: llava init in %8.2f ms.\n", __func__, t_llava_init_ms);
  203. const int64_t t_process_image_start_us = ggml_time_us();
  204. process_image(ctx_llava, embeds, params, n_past);
  205. const int64_t t_process_image_end_us = ggml_time_us();
  206. float t_process_image_ms = (t_process_image_end_us - t_process_image_start_us) / 1000.0;
  207. LOG_INF("%s: llama process image in %8.2f ms.\n", __func__, t_process_image_ms);
  208. llava_image_embed_free(embeds);
  209. return ctx_llava;
  210. }
  211. 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){
  212. std::string user_prompt = prompt;
  213. int has_minicpmv_projector = clip_is_minicpmv(ctx_llava->ctx_clip);
  214. if (!is_first) {
  215. if (has_minicpmv_projector == 2) {
  216. user_prompt = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" + prompt;
  217. }
  218. else if (has_minicpmv_projector == 3) {
  219. user_prompt = "<|im_start|>user\n" + prompt;
  220. }
  221. else if (has_minicpmv_projector == 4) {
  222. user_prompt = "<|im_start|>user\n" + prompt;
  223. }
  224. }
  225. eval_string(ctx_llava->ctx_llama, user_prompt.c_str(), params->n_batch, &n_past, false);
  226. if (has_minicpmv_projector == 2) {
  227. eval_string(ctx_llava->ctx_llama, "<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n", params->n_batch, &n_past, false);
  228. }
  229. else if (has_minicpmv_projector == 3) {
  230. eval_string(ctx_llava->ctx_llama, "<|im_end|><|im_start|>assistant\n", params->n_batch, &n_past, false);
  231. }
  232. else if (has_minicpmv_projector == 4) {
  233. eval_string(ctx_llava->ctx_llama, "<|im_end|><|im_start|>assistant\n", params->n_batch, &n_past, false);
  234. }
  235. // generate the response
  236. LOG_INF("\n");
  237. struct common_sampler * smpl = common_sampler_init(ctx_llava->model, params->sampling);
  238. return smpl;
  239. }
  240. static const char * llama_loop(struct llava_context * ctx_llava,struct common_sampler * smpl, int &n_past){
  241. const char * tmp = sample(smpl, ctx_llava->ctx_llama, &n_past);
  242. return tmp;
  243. }
  244. int main(int argc, char ** argv) {
  245. ggml_time_init();
  246. common_params params;
  247. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  248. return 1;
  249. }
  250. common_init();
  251. if (params.mmproj.path.empty() || (params.image.empty())) {
  252. show_additional_info(argc, argv);
  253. return 1;
  254. }
  255. for (auto & image : params.image) {
  256. int n_past = 0;
  257. auto * ctx_llava = minicpmv_init(&params, image, n_past);
  258. if (!params.prompt.empty()) {
  259. LOG("<user>%s\n", params.prompt.c_str());
  260. LOG("<assistant>");
  261. auto * smpl = llama_init(ctx_llava, &params, params.prompt, n_past, true);
  262. const int max_tgt_len = params.n_predict < 0 ? 256 : params.n_predict;
  263. std::string response;
  264. bool have_tmp = false;
  265. for (int i = 0; i < max_tgt_len; i++) {
  266. const auto * tmp = llama_loop(ctx_llava, smpl, n_past);
  267. response += tmp;
  268. if (strcmp(tmp, "</s>") == 0){
  269. if (!have_tmp) {
  270. continue;
  271. }
  272. break;
  273. }
  274. if (strstr(tmp, "###")) break; // Yi-VL behavior
  275. have_tmp = true;
  276. printf("%s", tmp);
  277. if (strstr(response.c_str(), "<user>")) break; // minicpm-v
  278. fflush(stdout);
  279. }
  280. common_sampler_free(smpl);
  281. }else {
  282. while (true) {
  283. LOG("<user>");
  284. std::string prompt;
  285. std::getline(std::cin, prompt);
  286. LOG("<assistant>");
  287. auto * smpl = llama_init(ctx_llava, &params, prompt, n_past, true);
  288. const int max_tgt_len = params.n_predict < 0 ? 256 : params.n_predict;
  289. std::string response;
  290. for (int i = 0; i < max_tgt_len; i++) {
  291. const auto * tmp = llama_loop(ctx_llava, smpl, n_past);
  292. response += tmp;
  293. if (strcmp(tmp, "</s>") == 0) break;
  294. printf("%s", tmp);// mistral llava-1.6
  295. if (strstr(response.c_str(), "<user>")) break; // minicpm-v
  296. fflush(stdout);
  297. }
  298. common_sampler_free(smpl);
  299. }
  300. }
  301. printf("\n");
  302. llama_perf_context_print(ctx_llava->ctx_llama);
  303. ctx_llava->model = NULL;
  304. llava_free(ctx_llava);
  305. }
  306. return 0;
  307. }