mtmd-cli.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #include "arg.h"
  2. #include "log.h"
  3. #include "common.h"
  4. #include "sampling.h"
  5. #include "llama.h"
  6. #include "ggml.h"
  7. #include "console.h"
  8. #include "chat.h"
  9. #include "mtmd.h"
  10. #include <vector>
  11. #include <limits.h>
  12. #include <cinttypes>
  13. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  14. #include <signal.h>
  15. #include <unistd.h>
  16. #elif defined (_WIN32)
  17. #define WIN32_LEAN_AND_MEAN
  18. #ifndef NOMINMAX
  19. #define NOMINMAX
  20. #endif
  21. #include <windows.h>
  22. #include <signal.h>
  23. #endif
  24. static bool g_is_generating = false;
  25. /**
  26. * Please note that this is NOT a production-ready stuff.
  27. * It is a playground for trying multimodal support in llama.cpp.
  28. * For contributors: please keep this code simple and easy to understand.
  29. */
  30. static void show_additional_info(int /*argc*/, char ** argv) {
  31. LOG(
  32. "Experimental CLI for multimodal\n\n"
  33. "Usage: %s [options] -m <model> --mmproj <mmproj> --image <image> -p <prompt>\n\n"
  34. " -m and --mmproj are required\n"
  35. " -hf user/repo can replace both -m and --mmproj in most cases\n"
  36. " --image and -p are optional, if NOT provided, the CLI will run in chat mode\n",
  37. argv[0]
  38. );
  39. }
  40. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  41. static void sigint_handler(int signo) {
  42. if (signo == SIGINT) {
  43. if (g_is_generating) {
  44. g_is_generating = false;
  45. } else {
  46. console::cleanup();
  47. LOG("\nInterrupted by user\n");
  48. _exit(130);
  49. }
  50. }
  51. }
  52. #endif
  53. struct mtmd_cli_context {
  54. mtmd_context_ptr ctx_vision;
  55. common_init_result llama_init;
  56. llama_model * model;
  57. llama_context * lctx;
  58. const llama_vocab * vocab;
  59. llama_batch batch;
  60. int n_batch;
  61. // note: we know that gemma3 template is "linear", meaning each turn is completely separated to another
  62. // so here we don't need to keep track of chat history
  63. common_chat_templates_ptr tmpls;
  64. // support for legacy templates (models not having EOT token)
  65. llama_tokens antiprompt_tokens;
  66. int n_threads = 1;
  67. llama_pos n_past = 0;
  68. mtmd_cli_context(common_params & params) : llama_init(common_init_from_params(params)) {
  69. model = llama_init.model.get();
  70. lctx = llama_init.context.get();
  71. vocab = llama_model_get_vocab(model);
  72. n_threads = params.cpuparams.n_threads;
  73. batch = llama_batch_init(params.n_batch, 0, 1);
  74. n_batch = params.n_batch;
  75. if (!llama_model_chat_template(model, nullptr) && params.chat_template.empty()) {
  76. LOG_ERR("Model does not have chat template.\n");
  77. LOG_ERR(" For old llava models, you may need to use '--chat-template vicuna'\n");
  78. LOG_ERR(" For MobileVLM models, use '--chat-template deepseek'\n");
  79. exit(1);
  80. }
  81. tmpls = common_chat_templates_init(model, params.chat_template);
  82. LOG_INF("%s: chat template example:\n%s\n", __func__, common_chat_format_example(tmpls.get(), params.use_jinja).c_str());
  83. init_vision_context(params);
  84. // load antiprompt tokens for legacy templates
  85. if (params.chat_template == "vicuna") {
  86. antiprompt_tokens = common_tokenize(lctx, "ASSISTANT:", false, true);
  87. } else if (params.chat_template == "deepseek") {
  88. antiprompt_tokens = common_tokenize(lctx, "###", false, true);
  89. }
  90. }
  91. void init_vision_context(common_params & params) {
  92. const char * clip_path = params.mmproj.path.c_str();
  93. ctx_vision.reset(mtmd_init_from_file(clip_path, model, mtmd_context_params{
  94. /* use_gpu */ true,
  95. /* timings */ true,
  96. /* n_threads */ params.cpuparams.n_threads,
  97. /* verbosity */ GGML_LOG_LEVEL_INFO,
  98. }));
  99. if (!ctx_vision.get()) {
  100. LOG_ERR("Failed to load vision model from %s\n", clip_path);
  101. exit(1);
  102. }
  103. }
  104. bool check_antiprompt(const llama_tokens & generated_tokens) {
  105. if (antiprompt_tokens.empty() || generated_tokens.size() < antiprompt_tokens.size()) {
  106. return false;
  107. }
  108. return std::equal(
  109. generated_tokens.end() - antiprompt_tokens.size(),
  110. generated_tokens.end(),
  111. antiprompt_tokens.begin()
  112. );
  113. }
  114. };
  115. struct decode_embd_batch {
  116. std::vector<llama_pos> pos;
  117. std::vector<int32_t> n_seq_id;
  118. std::vector<llama_seq_id> seq_id_0;
  119. std::vector<llama_seq_id *> seq_ids;
  120. std::vector<int8_t> logits;
  121. llama_batch batch;
  122. decode_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  123. pos .resize(n_tokens);
  124. n_seq_id.resize(n_tokens);
  125. seq_ids .resize(n_tokens + 1);
  126. logits .resize(n_tokens);
  127. seq_id_0.resize(1);
  128. seq_id_0[0] = seq_id;
  129. seq_ids [n_tokens] = nullptr;
  130. batch = {
  131. /*n_tokens =*/ n_tokens,
  132. /*tokens =*/ nullptr,
  133. /*embd =*/ embd,
  134. /*pos =*/ pos.data(),
  135. /*n_seq_id =*/ n_seq_id.data(),
  136. /*seq_id =*/ seq_ids.data(),
  137. /*logits =*/ logits.data(),
  138. };
  139. for (int i = 0; i < n_tokens; i++) {
  140. batch.pos [i] = pos_0 + i;
  141. batch.n_seq_id[i] = 1;
  142. batch.seq_id [i] = seq_id_0.data();
  143. batch.logits [i] = false;
  144. }
  145. }
  146. };
  147. static int generate_response(mtmd_cli_context & ctx, common_sampler * smpl, int n_predict) {
  148. llama_tokens generated_tokens;
  149. for (int i = 0; i < n_predict; i++) {
  150. if (i > n_predict || !g_is_generating) {
  151. printf("\n");
  152. break;
  153. }
  154. llama_token token_id = common_sampler_sample(smpl, ctx.lctx, -1);
  155. generated_tokens.push_back(token_id);
  156. common_sampler_accept(smpl, token_id, true);
  157. if (llama_vocab_is_eog(ctx.vocab, token_id) || ctx.check_antiprompt(generated_tokens)) {
  158. printf("\n");
  159. break; // end of generation
  160. }
  161. printf("%s", common_token_to_piece(ctx.lctx, token_id).c_str());
  162. fflush(stdout);
  163. // eval the token
  164. common_batch_clear(ctx.batch);
  165. common_batch_add(ctx.batch, token_id, ctx.n_past++, {0}, true);
  166. if (llama_decode(ctx.lctx, ctx.batch)) {
  167. LOG_ERR("failed to decode token\n");
  168. return 1;
  169. }
  170. }
  171. return 0;
  172. }
  173. static int eval_message(mtmd_cli_context & ctx, common_chat_msg & msg, std::vector<std::string> & images_fname, bool add_bos = false) {
  174. std::vector<mtmd_bitmap> bitmaps;
  175. common_chat_templates_inputs tmpl_inputs;
  176. tmpl_inputs.messages = {msg};
  177. tmpl_inputs.add_generation_prompt = true;
  178. tmpl_inputs.use_jinja = false; // jinja is buggy here
  179. auto formatted_chat = common_chat_templates_apply(ctx.tmpls.get(), tmpl_inputs);
  180. LOG_DBG("formatted_chat.prompt: %s\n", formatted_chat.prompt.c_str());
  181. for (auto & fname : images_fname) {
  182. mtmd_bitmap bitmap;
  183. if (mtmd_helper_bitmap_init_from_file(fname.c_str(), bitmap)) {
  184. LOG_ERR("Unable to load image %s\n", fname.c_str());
  185. return 2; // image not found
  186. }
  187. bitmaps.push_back(std::move(bitmap));
  188. }
  189. mtmd_input_text text;
  190. text.text = formatted_chat.prompt;
  191. text.add_special = add_bos;
  192. text.parse_special = true;
  193. mtmd_input_chunks chunks;
  194. int32_t res = mtmd_tokenize(ctx.ctx_vision.get(), chunks, text, bitmaps);
  195. if (res != 0) {
  196. LOG_ERR("Unable to tokenize prompt, res = %d\n", res);
  197. return 1;
  198. }
  199. if (mtmd_helper_eval(ctx.ctx_vision.get(), ctx.lctx, chunks, ctx.n_past, 0, ctx.n_batch)) {
  200. LOG_ERR("Unable to eval prompt\n");
  201. return 1;
  202. }
  203. ctx.n_past += mtmd_helper_get_n_tokens(chunks);
  204. return 0;
  205. }
  206. int main(int argc, char ** argv) {
  207. ggml_time_init();
  208. common_params params;
  209. params.sampling.temp = 0.2; // lower temp by default for better quality
  210. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  211. return 1;
  212. }
  213. common_init();
  214. if (params.mmproj.path.empty()) {
  215. show_additional_info(argc, argv);
  216. return 1;
  217. }
  218. mtmd_cli_context ctx(params);
  219. printf("%s: %s\n", __func__, params.model.path.c_str());
  220. bool is_single_turn = !params.prompt.empty() && !params.image.empty();
  221. struct common_sampler * smpl = common_sampler_init(ctx.model, params.sampling);
  222. int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
  223. // ctrl+C handling
  224. {
  225. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  226. struct sigaction sigint_action;
  227. sigint_action.sa_handler = sigint_handler;
  228. sigemptyset (&sigint_action.sa_mask);
  229. sigint_action.sa_flags = 0;
  230. sigaction(SIGINT, &sigint_action, NULL);
  231. #elif defined (_WIN32)
  232. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  233. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  234. };
  235. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  236. #endif
  237. }
  238. if (is_single_turn) {
  239. g_is_generating = true;
  240. if (params.prompt.find("<__image__>") == std::string::npos) {
  241. params.prompt += " <__image__>";
  242. }
  243. common_chat_msg msg;
  244. msg.role = "user";
  245. msg.content = params.prompt;
  246. if (eval_message(ctx, msg, params.image, true)) {
  247. return 1;
  248. }
  249. if (generate_response(ctx, smpl, n_predict)) {
  250. return 1;
  251. }
  252. } else {
  253. LOG("\n Running in chat mode, available commands:");
  254. LOG("\n /image <path> load an image");
  255. LOG("\n /clear clear the chat history");
  256. LOG("\n /quit or /exit exit the program");
  257. LOG("\n");
  258. bool is_first_msg = true;
  259. std::vector<std::string> images_fname;
  260. std::string content;
  261. while (true) {
  262. g_is_generating = false;
  263. LOG("\n> ");
  264. console::set_display(console::user_input);
  265. std::string line;
  266. console::readline(line, false);
  267. console::set_display(console::reset);
  268. line = string_strip(line);
  269. if (line.empty()) {
  270. continue;
  271. }
  272. if (line == "/quit" || line == "/exit") {
  273. break;
  274. }
  275. if (line == "/clear") {
  276. ctx.n_past = 0;
  277. llama_kv_self_seq_rm(ctx.lctx, 0, 1, -1); // keep BOS
  278. LOG("Chat history cleared\n\n");
  279. continue;
  280. }
  281. g_is_generating = true;
  282. if (line.find("/image") == 0) {
  283. std::string image = line.substr(7);
  284. images_fname.push_back(string_strip(image));
  285. content += "<__image__>";
  286. continue;
  287. } else {
  288. content += line;
  289. }
  290. common_chat_msg msg;
  291. msg.role = "user";
  292. msg.content = content;
  293. int ret = eval_message(ctx, msg, images_fname, is_first_msg);
  294. if (ret == 2) {
  295. // non-fatal error
  296. images_fname.clear();
  297. content.clear();
  298. continue;
  299. }
  300. if (ret) {
  301. return 1;
  302. }
  303. if (generate_response(ctx, smpl, n_predict)) {
  304. return 1;
  305. }
  306. images_fname.clear();
  307. content.clear();
  308. is_first_msg = false;
  309. }
  310. }
  311. llama_perf_context_print(ctx.lctx);
  312. return 0;
  313. }