qwen2vl-cli.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. #ifdef GGML_USE_CUDA
  11. #include "ggml-cuda.h"
  12. #endif
  13. #ifdef NDEBUG
  14. #include "ggml-alloc.h"
  15. #include "ggml-backend.h"
  16. #endif
  17. #include <cstdio>
  18. #include <cstdlib>
  19. #include <cstring>
  20. #include <vector>
  21. #include <algorithm>
  22. #include <iostream>
  23. #include <fstream>
  24. static bool qwen2vl_eval_image_embed(llama_context * ctx_llama, const struct llava_image_embed * image_embed,
  25. int n_batch, int * n_past, int * st_pos_id, struct clip_image_size * image_size) {
  26. int n_embd = llama_n_embd(llama_get_model(ctx_llama));
  27. const int patch_size = 14 * 2;
  28. const int ph = image_size->height / patch_size + (image_size->height % patch_size > 0);
  29. const int pw = image_size->width / patch_size + (image_size->width % patch_size > 0);
  30. auto img_tokens = image_embed->n_image_pos;
  31. // llama_pos mrope_pos[img_tokens * 4];
  32. std::vector<llama_pos> mrope_pos;
  33. mrope_pos.resize(img_tokens * 4);
  34. for (int y = 0; y < ph; y++)
  35. {
  36. for (int x = 0; x < pw; x++)
  37. {
  38. int i = y * pw + x;
  39. mrope_pos[i] = *st_pos_id;
  40. mrope_pos[i + img_tokens] = *st_pos_id + y;
  41. mrope_pos[i + img_tokens * 2] = *st_pos_id + x;
  42. mrope_pos[i + img_tokens * 3] = 0;
  43. }
  44. }
  45. *st_pos_id += std::max(pw, ph);
  46. int processed = 0;
  47. std::vector<llama_pos> batch_mrope_pos;
  48. batch_mrope_pos.resize(img_tokens * 4);
  49. for (int i = 0; i < img_tokens; i += n_batch) {
  50. int n_eval = img_tokens - i;
  51. if (n_eval > n_batch) {
  52. n_eval = n_batch;
  53. }
  54. // llama_pos batch_mrope_pos[n_eval * 4];
  55. std::fill(batch_mrope_pos.begin(), batch_mrope_pos.end(), 0);
  56. memcpy(batch_mrope_pos.data(), &mrope_pos[processed], n_eval * sizeof(llama_pos));
  57. memcpy(&batch_mrope_pos[n_eval * 1], &mrope_pos[img_tokens * 1 + processed], n_eval * sizeof(llama_pos));
  58. memcpy(&batch_mrope_pos[n_eval * 2], &mrope_pos[img_tokens * 2 + processed], n_eval * sizeof(llama_pos));
  59. memcpy(&batch_mrope_pos[n_eval * 3], &mrope_pos[img_tokens * 3 + processed], n_eval * sizeof(llama_pos));
  60. llama_batch batch = {
  61. int32_t(n_eval), // n_tokens
  62. nullptr, // token
  63. (image_embed->embed+i*n_embd), // embed
  64. batch_mrope_pos.data(), // pos
  65. nullptr, // n_seq_id
  66. nullptr, // seq_id
  67. nullptr, // logits
  68. };
  69. if (llama_decode(ctx_llama, batch)) {
  70. LOG_ERR("%s : failed to eval\n", __func__);
  71. return false;
  72. }
  73. *n_past += n_eval;
  74. processed += n_eval;
  75. }
  76. return true;
  77. }
  78. static bool eval_tokens(struct llama_context * ctx_llama, std::vector<llama_token> tokens, int n_batch, int * n_past, int * st_pos_id) {
  79. int N = (int) tokens.size();
  80. std::vector<llama_pos> pos;
  81. for (int i = 0; i < N; i += n_batch) {
  82. int n_eval = (int) tokens.size() - i;
  83. if (n_eval > n_batch) {
  84. n_eval = n_batch;
  85. }
  86. auto batch = llama_batch_get_one(&tokens[i], n_eval);
  87. // TODO: add mrope pos ids somewhere else
  88. pos.resize(batch.n_tokens * 4);
  89. std::fill(pos.begin(), pos.end(), 0);
  90. for (int j = 0; j < batch.n_tokens * 3; j ++) {
  91. pos[j] = *st_pos_id + (j % batch.n_tokens);
  92. }
  93. batch.pos = pos.data();
  94. if (llama_decode(ctx_llama, batch)) {
  95. LOG_ERR("%s : failed to eval. token %d/%d (batch size %d, n_past %d)\n", __func__, i, N, n_batch, *n_past);
  96. return false;
  97. }
  98. *n_past += n_eval;
  99. *st_pos_id += n_eval;
  100. }
  101. return true;
  102. }
  103. static bool eval_id(struct llama_context * ctx_llama, int id, int * n_past, int * st_pos_id) {
  104. std::vector<llama_token> tokens;
  105. tokens.push_back(id);
  106. return eval_tokens(ctx_llama, tokens, 1, n_past, st_pos_id);
  107. }
  108. static bool eval_string(struct llama_context * ctx_llama, const char* str, int n_batch, int * n_past, int * st_pos_id, bool add_bos){
  109. std::string str2 = str;
  110. std::vector<llama_token> embd_inp = common_tokenize(ctx_llama, str2, add_bos, true);
  111. eval_tokens(ctx_llama, embd_inp, n_batch, n_past, st_pos_id);
  112. return true;
  113. }
  114. static const char * sample(struct common_sampler * smpl,
  115. struct llama_context * ctx_llama,
  116. int * n_past, int * st_pos_id) {
  117. const llama_token id = common_sampler_sample(smpl, ctx_llama, -1);
  118. common_sampler_accept(smpl, id, true);
  119. static std::string ret;
  120. if (llama_token_is_eog(llama_get_model(ctx_llama), id)) {
  121. ret = "</s>";
  122. } else {
  123. ret = common_token_to_piece(ctx_llama, id);
  124. }
  125. eval_id(ctx_llama, id, n_past, st_pos_id);
  126. return ret.c_str();
  127. }
  128. static const char* IMG_BASE64_TAG_BEGIN = "<img src=\"data:image/jpeg;base64,";
  129. static const char* IMG_BASE64_TAG_END = "\">";
  130. static void find_image_tag_in_prompt(const std::string& prompt, size_t& begin_out, size_t& end_out) {
  131. begin_out = prompt.find(IMG_BASE64_TAG_BEGIN);
  132. end_out = prompt.find(IMG_BASE64_TAG_END, (begin_out == std::string::npos) ? 0UL : begin_out);
  133. }
  134. static bool prompt_contains_image(const std::string& prompt) {
  135. size_t begin, end;
  136. find_image_tag_in_prompt(prompt, begin, end);
  137. return (begin != std::string::npos);
  138. }
  139. // replaces the base64 image tag in the prompt with `replacement`
  140. static llava_image_embed * llava_image_embed_make_with_prompt_base64(struct clip_ctx * ctx_clip, int n_threads, const std::string& prompt) {
  141. size_t img_base64_str_start, img_base64_str_end;
  142. find_image_tag_in_prompt(prompt, img_base64_str_start, img_base64_str_end);
  143. if (img_base64_str_start == std::string::npos || img_base64_str_end == std::string::npos) {
  144. LOG_ERR("%s: invalid base64 image tag. must be %s<base64 byte string>%s\n", __func__, IMG_BASE64_TAG_BEGIN, IMG_BASE64_TAG_END);
  145. return NULL;
  146. }
  147. auto base64_bytes_start = img_base64_str_start + strlen(IMG_BASE64_TAG_BEGIN);
  148. auto base64_bytes_count = img_base64_str_end - base64_bytes_start;
  149. auto base64_str = prompt.substr(base64_bytes_start, base64_bytes_count );
  150. auto required_bytes = base64::required_encode_size(base64_str.size());
  151. auto img_bytes = std::vector<unsigned char>(required_bytes);
  152. base64::decode(base64_str.begin(), base64_str.end(), img_bytes.begin());
  153. auto embed = llava_image_embed_make_with_bytes(ctx_clip, n_threads, img_bytes.data(), img_bytes.size());
  154. if (!embed) {
  155. LOG_ERR("%s: could not load image from base64 string.\n", __func__);
  156. return NULL;
  157. }
  158. return embed;
  159. }
  160. static std::string remove_image_from_prompt(const std::string& prompt, const char * replacement = "") {
  161. size_t begin, end;
  162. find_image_tag_in_prompt(prompt, begin, end);
  163. if (begin == std::string::npos || end == std::string::npos) {
  164. return prompt;
  165. }
  166. auto pre = prompt.substr(0, begin);
  167. auto post = prompt.substr(end + strlen(IMG_BASE64_TAG_END));
  168. return pre + replacement + post;
  169. }
  170. struct llava_context {
  171. struct clip_ctx * ctx_clip = NULL;
  172. struct llama_context * ctx_llama = NULL;
  173. struct llama_model * model = NULL;
  174. };
  175. static void print_usage(int, char ** argv) {
  176. LOG("\n example usage:\n");
  177. LOG("\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]);
  178. LOG("\n note: a lower temperature value like 0.1 is recommended for better quality.\n");
  179. }
  180. static struct llava_image_embed * load_image(llava_context * ctx_llava, common_params * params, const std::string & fname) {
  181. // load and preprocess the image
  182. llava_image_embed * embed = NULL;
  183. auto prompt = params->prompt;
  184. if (prompt_contains_image(prompt)) {
  185. if (!params->image.empty()) {
  186. LOG_INF("using base64 encoded image instead of command line image path\n");
  187. }
  188. embed = llava_image_embed_make_with_prompt_base64(ctx_llava->ctx_clip, params->cpuparams.n_threads, prompt);
  189. if (!embed) {
  190. LOG_ERR("%s: can't load image from prompt\n", __func__);
  191. return NULL;
  192. }
  193. params->prompt = remove_image_from_prompt(prompt);
  194. } else {
  195. embed = llava_image_embed_make_with_filename(ctx_llava->ctx_clip, params->cpuparams.n_threads, fname.c_str());
  196. if (!embed) {
  197. fprintf(stderr, "%s: is %s really an image file?\n", __func__, fname.c_str());
  198. return NULL;
  199. }
  200. }
  201. return embed;
  202. }
  203. static void process_prompt(struct llava_context * ctx_llava, struct llava_image_embed * image_embed, common_params * params, const std::string & prompt) {
  204. int n_past = 0;
  205. int cur_pos_id = 0;
  206. const int max_tgt_len = params->n_predict < 0 ? 256 : params->n_predict;
  207. std::string system_prompt, user_prompt;
  208. size_t image_pos = prompt.find("<|vision_start|>");
  209. if (image_pos != std::string::npos) {
  210. // new templating mode: Provide the full prompt including system message and use <image> as a placeholder for the image
  211. system_prompt = prompt.substr(0, image_pos);
  212. user_prompt = prompt.substr(image_pos + std::string("<|vision_pad|>").length());
  213. LOG_INF("system_prompt: %s\n", system_prompt.c_str());
  214. if (params->verbose_prompt) {
  215. auto tmp = common_tokenize(ctx_llava->ctx_llama, system_prompt, true, true);
  216. for (int i = 0; i < (int) tmp.size(); i++) {
  217. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  218. }
  219. }
  220. LOG_INF("user_prompt: %s\n", user_prompt.c_str());
  221. if (params->verbose_prompt) {
  222. auto tmp = common_tokenize(ctx_llava->ctx_llama, user_prompt, true, true);
  223. for (int i = 0; i < (int) tmp.size(); i++) {
  224. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  225. }
  226. }
  227. } else {
  228. // llava-1.5 native mode
  229. system_prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|>";
  230. user_prompt = "<|vision_end|>" + prompt + "<|im_end|>\n<|im_start|>assistant\n";
  231. if (params->verbose_prompt) {
  232. auto tmp = common_tokenize(ctx_llava->ctx_llama, user_prompt, true, true);
  233. for (int i = 0; i < (int) tmp.size(); i++) {
  234. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx_llava->ctx_llama, tmp[i]).c_str());
  235. }
  236. }
  237. }
  238. eval_string(ctx_llava->ctx_llama, system_prompt.c_str(), params->n_batch, &n_past, &cur_pos_id, true);
  239. if (image_embed != nullptr) {
  240. auto image_size = clip_get_load_image_size(ctx_llava->ctx_clip);
  241. qwen2vl_eval_image_embed(ctx_llava->ctx_llama, image_embed, params->n_batch, &n_past, &cur_pos_id, image_size);
  242. }
  243. eval_string(ctx_llava->ctx_llama, user_prompt.c_str(), params->n_batch, &n_past, &cur_pos_id, false);
  244. // generate the response
  245. LOG("\n");
  246. struct common_sampler * smpl = common_sampler_init(ctx_llava->model, params->sampling);
  247. if (!smpl) {
  248. LOG_ERR("%s: failed to initialize sampling subsystem\n", __func__);
  249. exit(1);
  250. }
  251. std::string response = "";
  252. for (int i = 0; i < max_tgt_len; i++) {
  253. const char * tmp = sample(smpl, ctx_llava->ctx_llama, &n_past, &cur_pos_id);
  254. response += tmp;
  255. if (strcmp(tmp, "</s>") == 0) break;
  256. if (strstr(tmp, "###")) break; // Yi-VL behavior
  257. LOG("%s", tmp);
  258. 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)
  259. if (strstr(response.c_str(), "<|im_start|>")) break; // Yi-34B llava-1.6
  260. if (strstr(response.c_str(), "USER:")) break; // mistral llava-1.6
  261. fflush(stdout);
  262. }
  263. common_sampler_free(smpl);
  264. LOG("\n");
  265. }
  266. static struct llama_model * llava_init(common_params * params) {
  267. llama_backend_init();
  268. llama_numa_init(params->numa);
  269. llama_model_params model_params = common_model_params_to_llama(*params);
  270. llama_model * model = llama_load_model_from_file(params->model.c_str(), model_params);
  271. if (model == NULL) {
  272. LOG_ERR("%s: unable to load model\n" , __func__);
  273. return NULL;
  274. }
  275. return model;
  276. }
  277. static struct llava_context * llava_init_context(common_params * params, llama_model * model) {
  278. const char * clip_path = params->mmproj.c_str();
  279. auto prompt = params->prompt;
  280. if (prompt.empty()) {
  281. prompt = "describe the image in detail.";
  282. }
  283. auto ctx_clip = clip_model_load(clip_path, /*verbosity=*/ 1);
  284. llama_context_params ctx_params = common_context_params_to_llama(*params);
  285. ctx_params.n_ctx = params->n_ctx < 2048 ? 2048 : params->n_ctx; // we need a longer context size to process image embeddings
  286. llama_context * ctx_llama = llama_new_context_with_model(model, ctx_params);
  287. if (ctx_llama == NULL) {
  288. LOG_ERR("%s: failed to create the llama_context\n" , __func__);
  289. return NULL;
  290. }
  291. auto * ctx_llava = (struct llava_context *)malloc(sizeof(llava_context));
  292. ctx_llava->ctx_llama = ctx_llama;
  293. ctx_llava->ctx_clip = ctx_clip;
  294. ctx_llava->model = model;
  295. return ctx_llava;
  296. }
  297. static void llava_free(struct llava_context * ctx_llava) {
  298. if (ctx_llava->ctx_clip) {
  299. clip_free(ctx_llava->ctx_clip);
  300. ctx_llava->ctx_clip = NULL;
  301. }
  302. llama_free(ctx_llava->ctx_llama);
  303. llama_free_model(ctx_llava->model);
  304. llama_backend_free();
  305. }
  306. #ifndef NDEBUG
  307. static void debug_test_mrope_2d() {
  308. // 1. Initialize backend
  309. ggml_backend_t backend = NULL;
  310. std::string backend_name = "";
  311. #ifdef GGML_USE_CUDA
  312. fprintf(stderr, "%s: using CUDA backend\n", __func__);
  313. backend = ggml_backend_cuda_init(0); // init device 0
  314. backend_name = "cuda";
  315. if (!backend) {
  316. fprintf(stderr, "%s: ggml_backend_cuda_init() failed\n", __func__);
  317. }
  318. #endif
  319. // if there aren't GPU Backends fallback to CPU backend
  320. if (!backend) {
  321. backend = ggml_backend_cpu_init();
  322. backend_name = "cpu";
  323. }
  324. // Calculate the size needed to allocate
  325. size_t ctx_size = 0;
  326. ctx_size += 2 * ggml_tensor_overhead(); // tensors
  327. // no need to allocate anything else!
  328. // 2. Allocate `ggml_context` to store tensor data
  329. struct ggml_init_params params = {
  330. /*.mem_size =*/ ctx_size,
  331. /*.mem_buffer =*/ NULL,
  332. /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_backend_alloc_ctx_tensors()
  333. };
  334. struct ggml_context * ctx = ggml_init(params);
  335. struct ggml_tensor * inp_raw = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 128, 12, 30);
  336. ggml_set_name(inp_raw, "inp_raw");
  337. ggml_set_input(inp_raw);
  338. struct ggml_tensor * pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 30 * 4);
  339. ggml_set_name(pos, "pos");
  340. ggml_set_input(pos);
  341. std::vector<float> dummy_q;
  342. dummy_q.resize(128 * 12 * 30);
  343. std::fill(dummy_q.begin(), dummy_q.end(), 0.1);
  344. // memcpy(inp_raw->data, dummy_q.data(), 128 * 12 * 30 * ggml_element_size(inp_raw));
  345. std::vector<int> pos_id;
  346. pos_id.resize(30 * 4);
  347. for (int i = 0; i < 30; i ++) {
  348. pos_id[i] = i;
  349. pos_id[i + 30] = i + 10;
  350. pos_id[i + 60] = i + 20;
  351. pos_id[i + 90] = i + 30;
  352. }
  353. int sections[4] = {32, 32, 0, 0};
  354. // 4. Allocate a `ggml_backend_buffer` to store all tensors
  355. ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);
  356. // 5. Copy tensor data from main memory (RAM) to backend buffer
  357. ggml_backend_tensor_set(inp_raw, dummy_q.data(), 0, ggml_nbytes(inp_raw));
  358. ggml_backend_tensor_set(pos, pos_id.data(), 0, ggml_nbytes(pos));
  359. // 6. Create a `ggml_cgraph` for mul_mat operation
  360. struct ggml_cgraph * gf = NULL;
  361. struct ggml_context * ctx_cgraph = NULL;
  362. // create a temporally context to build the graph
  363. struct ggml_init_params params0 = {
  364. /*.mem_size =*/ ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead(),
  365. /*.mem_buffer =*/ NULL,
  366. /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_gallocr_alloc_graph()
  367. };
  368. ctx_cgraph = ggml_init(params0);
  369. gf = ggml_new_graph(ctx_cgraph);
  370. struct ggml_tensor * result0 = ggml_rope_multi(
  371. ctx_cgraph, inp_raw, pos, nullptr,
  372. 128/2, sections, LLAMA_ROPE_TYPE_VISION, 32768, 1000000, 1,
  373. 0, 1, 32, 1);
  374. // Add "result" tensor and all of its dependencies to the cgraph
  375. ggml_build_forward_expand(gf, result0);
  376. // 7. Create a `ggml_gallocr` for cgraph computation
  377. ggml_gallocr_t allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend));
  378. ggml_gallocr_alloc_graph(allocr, gf);
  379. // 9. Run the computation
  380. int n_threads = 1; // Optional: number of threads to perform some operations with multi-threading
  381. if (ggml_backend_is_cpu(backend)) {
  382. ggml_backend_cpu_set_n_threads(backend, n_threads);
  383. }
  384. ggml_backend_graph_compute(backend, gf);
  385. // 10. Retrieve results (output tensors)
  386. // in this example, output tensor is always the last tensor in the graph
  387. struct ggml_tensor * result = result0;
  388. // struct ggml_tensor * result = gf->nodes[gf->n_nodes - 1];
  389. float * result_data = (float *)malloc(ggml_nbytes(result));
  390. // because the tensor data is stored in device buffer, we need to copy it back to RAM
  391. ggml_backend_tensor_get(result, result_data, 0, ggml_nbytes(result));
  392. const std::string bin_file = "mrope_2d_" + backend_name +".bin";
  393. std::ofstream outFile(bin_file, std::ios::binary);
  394. if (outFile.is_open()) {
  395. outFile.write(reinterpret_cast<const char*>(result_data), ggml_nbytes(result));
  396. outFile.close();
  397. std::cout << "Data successfully written to " + bin_file << std::endl;
  398. } else {
  399. std::cerr << "Error opening file!" << std::endl;
  400. }
  401. free(result_data);
  402. // 11. Free memory and exit
  403. ggml_free(ctx_cgraph);
  404. ggml_gallocr_free(allocr);
  405. ggml_free(ctx);
  406. ggml_backend_buffer_free(buffer);
  407. ggml_backend_free(backend);
  408. }
  409. static void debug_dump_img_embed(struct llava_context * ctx_llava) {
  410. int n_embd = llama_n_embd(llama_get_model(ctx_llava->ctx_llama));
  411. int ne = n_embd * 4;
  412. float vals[56 * 56 * 3];
  413. // float embd[ne];
  414. std::vector<float> embd;
  415. embd.resize(ne);
  416. for (int i = 0; i < 56*56; i++)
  417. {
  418. for (int c = 0; c < 3; c++)
  419. vals[i * 3 + c] = (float)(i % (56 * 56)) / (56*56);
  420. }
  421. clip_encode_float_image(ctx_llava->ctx_clip, 16, vals, 56, 56, embd.data());
  422. std::ofstream outFile("img_embed.bin", std::ios::binary);
  423. if (outFile.is_open()) {
  424. outFile.write(reinterpret_cast<const char*>(embd.data()), ne * sizeof(float));
  425. outFile.close();
  426. std::cout << "Data successfully written to mrope.bin" << std::endl;
  427. } else {
  428. std::cerr << "Error opening file!" << std::endl;
  429. }
  430. }
  431. #endif
  432. int main(int argc, char ** argv) {
  433. ggml_time_init();
  434. common_params params;
  435. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, print_usage)) {
  436. return 1;
  437. }
  438. common_init();
  439. if (params.mmproj.empty() || (params.image.empty() && !prompt_contains_image(params.prompt))) {
  440. print_usage(argc, argv);
  441. return 1;
  442. }
  443. auto * model = llava_init(&params);
  444. if (model == NULL) {
  445. fprintf(stderr, "%s: error: failed to init llava model\n", __func__);
  446. return 1;
  447. }
  448. if (prompt_contains_image(params.prompt)) {
  449. auto * ctx_llava = llava_init_context(&params, model);
  450. auto * image_embed = load_image(ctx_llava, &params, "");
  451. // process the prompt
  452. process_prompt(ctx_llava, image_embed, &params, params.prompt);
  453. llama_perf_context_print(ctx_llava->ctx_llama);
  454. llava_image_embed_free(image_embed);
  455. ctx_llava->model = NULL;
  456. llava_free(ctx_llava);
  457. #ifndef NDEBUG
  458. } else if (params.image[0].empty()) {
  459. auto ctx_llava = llava_init_context(&params, model);
  460. debug_test_mrope_2d();
  461. debug_dump_img_embed(ctx_llava);
  462. llama_perf_context_print(ctx_llava->ctx_llama);
  463. ctx_llava->model = NULL;
  464. llava_free(ctx_llava);
  465. #endif
  466. } else {
  467. for (auto & image : params.image) {
  468. auto * ctx_llava = llava_init_context(&params, model);
  469. auto * image_embed = load_image(ctx_llava, &params, image);
  470. if (!image_embed) {
  471. LOG_ERR("%s: failed to load image %s. Terminating\n\n", __func__, image.c_str());
  472. return 1;
  473. }
  474. // process the prompt
  475. process_prompt(ctx_llava, image_embed, &params, params.prompt);
  476. llama_perf_context_print(ctx_llava->ctx_llama);
  477. llava_image_embed_free(image_embed);
  478. ctx_llava->model = NULL;
  479. llava_free(ctx_llava);
  480. }
  481. }
  482. llama_free_model(model);
  483. return 0;
  484. }