mtmd-cli.cpp 12 KB

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