qwen2vl-test.cpp 22 KB

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