mtmd-cli.cpp 14 KB

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