qwen2vl-cli.cpp 23 KB

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