1
0

mtmd-cli.cpp 12 KB

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