1
0

mtmd-cli.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 (!llama_model_chat_template(model, nullptr) && params.chat_template.empty()) {
  82. LOG_ERR("Model does not have chat template.\n");
  83. LOG_ERR(" For old llava models, you may need to use '--chat-template vicuna'\n");
  84. LOG_ERR(" For MobileVLM models, use '--chat-template deepseek'\n");
  85. LOG_ERR(" For Mistral Small 3.1, use '--chat-template mistral-v7'\n");
  86. exit(1);
  87. }
  88. tmpls = common_chat_templates_init(model, params.chat_template);
  89. LOG_INF("%s: chat template example:\n%s\n", __func__, common_chat_format_example(tmpls.get(), params.use_jinja).c_str());
  90. init_vision_context(params);
  91. // load antiprompt tokens for legacy templates
  92. if (params.chat_template == "vicuna") {
  93. antiprompt_tokens = common_tokenize(lctx, "ASSISTANT:", false, true);
  94. } else if (params.chat_template == "deepseek") {
  95. antiprompt_tokens = common_tokenize(lctx, "###", false, true);
  96. }
  97. }
  98. void init_vision_context(common_params & params) {
  99. const char * clip_path = params.mmproj.path.c_str();
  100. mtmd_context_params mparams = mtmd_context_params_default();
  101. mparams.use_gpu = params.mmproj_use_gpu;
  102. mparams.print_timings = true;
  103. mparams.n_threads = params.cpuparams.n_threads;
  104. mparams.verbosity = params.verbosity > 0 ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_INFO;
  105. ctx_vision.reset(mtmd_init_from_file(clip_path, model, mparams));
  106. if (!ctx_vision.get()) {
  107. LOG_ERR("Failed to load vision model from %s\n", clip_path);
  108. exit(1);
  109. }
  110. }
  111. bool check_antiprompt(const llama_tokens & generated_tokens) {
  112. if (antiprompt_tokens.empty() || generated_tokens.size() < antiprompt_tokens.size()) {
  113. return false;
  114. }
  115. return std::equal(
  116. generated_tokens.end() - antiprompt_tokens.size(),
  117. generated_tokens.end(),
  118. antiprompt_tokens.begin()
  119. );
  120. }
  121. bool load_image(const std::string & fname) {
  122. mtmd::bitmap bmp(mtmd_helper_bitmap_init_from_file(fname.c_str()));
  123. if (!bmp.ptr) {
  124. return false;
  125. }
  126. bitmaps.entries.push_back(std::move(bmp));
  127. return true;
  128. }
  129. };
  130. static int generate_response(mtmd_cli_context & ctx, common_sampler * smpl, int n_predict) {
  131. llama_tokens generated_tokens;
  132. for (int i = 0; i < n_predict; i++) {
  133. if (i > n_predict || !g_is_generating || g_is_interrupted) {
  134. LOG("\n");
  135. break;
  136. }
  137. llama_token token_id = common_sampler_sample(smpl, ctx.lctx, -1);
  138. generated_tokens.push_back(token_id);
  139. common_sampler_accept(smpl, token_id, true);
  140. if (llama_vocab_is_eog(ctx.vocab, token_id) || ctx.check_antiprompt(generated_tokens)) {
  141. LOG("\n");
  142. break; // end of generation
  143. }
  144. LOG("%s", common_token_to_piece(ctx.lctx, token_id).c_str());
  145. fflush(stdout);
  146. if (g_is_interrupted) {
  147. LOG("\n");
  148. break;
  149. }
  150. // eval the token
  151. common_batch_clear(ctx.batch);
  152. common_batch_add(ctx.batch, token_id, ctx.n_past++, {0}, true);
  153. if (llama_decode(ctx.lctx, ctx.batch)) {
  154. LOG_ERR("failed to decode token\n");
  155. return 1;
  156. }
  157. }
  158. return 0;
  159. }
  160. static int eval_message(mtmd_cli_context & ctx, common_chat_msg & msg, bool add_bos = false) {
  161. common_chat_templates_inputs tmpl_inputs;
  162. tmpl_inputs.messages = {msg};
  163. tmpl_inputs.add_generation_prompt = true;
  164. tmpl_inputs.use_jinja = false; // jinja is buggy here
  165. auto formatted_chat = common_chat_templates_apply(ctx.tmpls.get(), tmpl_inputs);
  166. LOG_DBG("formatted_chat.prompt: %s\n", formatted_chat.prompt.c_str());
  167. mtmd_input_text text;
  168. text.text = formatted_chat.prompt.c_str();
  169. text.add_special = add_bos;
  170. text.parse_special = true;
  171. if (g_is_interrupted) return 0;
  172. mtmd::input_chunks chunks(mtmd_input_chunks_init());
  173. auto bitmaps_c_ptr = ctx.bitmaps.c_ptr();
  174. int32_t res = mtmd_tokenize(ctx.ctx_vision.get(),
  175. chunks.ptr.get(), // output
  176. &text, // text
  177. bitmaps_c_ptr.data(),
  178. bitmaps_c_ptr.size());
  179. if (res != 0) {
  180. LOG_ERR("Unable to tokenize prompt, res = %d\n", res);
  181. return 1;
  182. }
  183. ctx.bitmaps.entries.clear();
  184. llama_pos new_n_past;
  185. if (mtmd_helper_eval_chunks(ctx.ctx_vision.get(),
  186. ctx.lctx, // lctx
  187. chunks.ptr.get(), // chunks
  188. ctx.n_past, // n_past
  189. 0, // seq_id
  190. ctx.n_batch, // n_batch
  191. true, // logits_last
  192. &new_n_past)) {
  193. LOG_ERR("Unable to eval prompt\n");
  194. return 1;
  195. }
  196. ctx.n_past = new_n_past;
  197. LOG("\n");
  198. return 0;
  199. }
  200. int main(int argc, char ** argv) {
  201. ggml_time_init();
  202. common_params params;
  203. params.sampling.temp = 0.2; // lower temp by default for better quality
  204. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  205. return 1;
  206. }
  207. common_init();
  208. if (params.mmproj.path.empty()) {
  209. show_additional_info(argc, argv);
  210. LOG_ERR("ERR: Missing --mmproj argument\n");
  211. return 1;
  212. }
  213. mtmd_cli_context ctx(params);
  214. LOG("%s: loading model: %s\n", __func__, params.model.path.c_str());
  215. bool is_single_turn = !params.prompt.empty() && !params.image.empty();
  216. struct common_sampler * smpl = common_sampler_init(ctx.model, params.sampling);
  217. int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
  218. // Ctrl+C handling
  219. {
  220. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  221. struct sigaction sigint_action;
  222. sigint_action.sa_handler = sigint_handler;
  223. sigemptyset (&sigint_action.sa_mask);
  224. sigint_action.sa_flags = 0;
  225. sigaction(SIGINT, &sigint_action, NULL);
  226. #elif defined (_WIN32)
  227. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  228. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  229. };
  230. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  231. #endif
  232. }
  233. if (g_is_interrupted) return 130;
  234. if (is_single_turn) {
  235. g_is_generating = true;
  236. if (params.prompt.find("<__image__>") == std::string::npos) {
  237. params.prompt += " <__image__>";
  238. }
  239. common_chat_msg msg;
  240. msg.role = "user";
  241. msg.content = params.prompt;
  242. for (const auto & image : params.image) {
  243. if (!ctx.load_image(image)) {
  244. return 1; // error is already printed by libmtmd
  245. }
  246. }
  247. if (eval_message(ctx, msg, true)) {
  248. return 1;
  249. }
  250. if (!g_is_interrupted && generate_response(ctx, smpl, n_predict)) {
  251. return 1;
  252. }
  253. } else {
  254. LOG("\n Running in chat mode, available commands:");
  255. LOG("\n /image <path> load an image");
  256. LOG("\n /clear clear the chat history");
  257. LOG("\n /quit or /exit exit the program");
  258. LOG("\n");
  259. bool is_first_msg = true;
  260. std::string content;
  261. while (!g_is_interrupted) {
  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. if (g_is_interrupted) break;
  268. console::set_display(console::reset);
  269. line = string_strip(line);
  270. if (line.empty()) {
  271. continue;
  272. }
  273. if (line == "/quit" || line == "/exit") {
  274. break;
  275. }
  276. if (line == "/clear") {
  277. ctx.n_past = 0;
  278. llama_kv_self_seq_rm(ctx.lctx, 0, 1, -1); // keep BOS
  279. LOG("Chat history cleared\n\n");
  280. continue;
  281. }
  282. g_is_generating = true;
  283. if (line == "/image" || line.find("/image ") == 0) {
  284. if (line.size() < 8) {
  285. LOG_ERR("ERR: Missing image filename\n");
  286. continue;
  287. }
  288. std::string image = line.substr(7);
  289. if (ctx.load_image(image)) {
  290. LOG("Image %s loaded\n", image.c_str());
  291. content += "<__image__>";
  292. }
  293. // else, error is already printed by libmtmd
  294. continue;
  295. } else {
  296. content += line;
  297. }
  298. common_chat_msg msg;
  299. msg.role = "user";
  300. msg.content = content;
  301. int ret = eval_message(ctx, msg, is_first_msg);
  302. if (ret) {
  303. return 1;
  304. }
  305. if (g_is_interrupted) break;
  306. if (generate_response(ctx, smpl, n_predict)) {
  307. return 1;
  308. }
  309. content.clear();
  310. is_first_msg = false;
  311. }
  312. }
  313. if (g_is_interrupted) LOG("\nInterrupted by user\n");
  314. LOG("\n\n");
  315. llama_perf_context_print(ctx.lctx);
  316. return g_is_interrupted ? 130 : 0;
  317. }