mtmd-cli.cpp 11 KB

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