qwen2vl-cli.cpp 22 KB

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