mtmd-cli.cpp 12 KB

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