1
0

mtmd-cli.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. struct decode_embd_batch {
  121. std::vector<llama_pos> pos;
  122. std::vector<int32_t> n_seq_id;
  123. std::vector<llama_seq_id> seq_id_0;
  124. std::vector<llama_seq_id *> seq_ids;
  125. std::vector<int8_t> logits;
  126. llama_batch batch;
  127. decode_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  128. pos .resize(n_tokens);
  129. n_seq_id.resize(n_tokens);
  130. seq_ids .resize(n_tokens + 1);
  131. logits .resize(n_tokens);
  132. seq_id_0.resize(1);
  133. seq_id_0[0] = seq_id;
  134. seq_ids [n_tokens] = nullptr;
  135. batch = {
  136. /*n_tokens =*/ n_tokens,
  137. /*tokens =*/ nullptr,
  138. /*embd =*/ embd,
  139. /*pos =*/ pos.data(),
  140. /*n_seq_id =*/ n_seq_id.data(),
  141. /*seq_id =*/ seq_ids.data(),
  142. /*logits =*/ logits.data(),
  143. };
  144. for (int i = 0; i < n_tokens; i++) {
  145. batch.pos [i] = pos_0 + i;
  146. batch.n_seq_id[i] = 1;
  147. batch.seq_id [i] = seq_id_0.data();
  148. batch.logits [i] = false;
  149. }
  150. }
  151. };
  152. static int generate_response(mtmd_cli_context & ctx, common_sampler * smpl, int n_predict) {
  153. llama_tokens generated_tokens;
  154. for (int i = 0; i < n_predict; i++) {
  155. if (i > n_predict || !g_is_generating || g_is_interrupted) {
  156. printf("\n");
  157. break;
  158. }
  159. llama_token token_id = common_sampler_sample(smpl, ctx.lctx, -1);
  160. generated_tokens.push_back(token_id);
  161. common_sampler_accept(smpl, token_id, true);
  162. if (llama_vocab_is_eog(ctx.vocab, token_id) || ctx.check_antiprompt(generated_tokens)) {
  163. printf("\n");
  164. break; // end of generation
  165. }
  166. printf("%s", common_token_to_piece(ctx.lctx, token_id).c_str());
  167. fflush(stdout);
  168. if (g_is_interrupted) {
  169. printf("\n");
  170. break;
  171. }
  172. // eval the token
  173. common_batch_clear(ctx.batch);
  174. common_batch_add(ctx.batch, token_id, ctx.n_past++, {0}, true);
  175. if (llama_decode(ctx.lctx, ctx.batch)) {
  176. LOG_ERR("failed to decode token\n");
  177. return 1;
  178. }
  179. }
  180. return 0;
  181. }
  182. static int eval_message(mtmd_cli_context & ctx, common_chat_msg & msg, std::vector<std::string> & images_fname, bool add_bos = false) {
  183. std::vector<mtmd_bitmap> bitmaps;
  184. common_chat_templates_inputs tmpl_inputs;
  185. tmpl_inputs.messages = {msg};
  186. tmpl_inputs.add_generation_prompt = true;
  187. tmpl_inputs.use_jinja = false; // jinja is buggy here
  188. auto formatted_chat = common_chat_templates_apply(ctx.tmpls.get(), tmpl_inputs);
  189. LOG_DBG("formatted_chat.prompt: %s\n", formatted_chat.prompt.c_str());
  190. for (auto & fname : images_fname) {
  191. mtmd_bitmap bitmap;
  192. if (mtmd_helper_bitmap_init_from_file(fname.c_str(), bitmap)) {
  193. LOG_ERR("Unable to load image %s\n", fname.c_str());
  194. return 2; // image not found
  195. }
  196. bitmaps.push_back(std::move(bitmap));
  197. }
  198. mtmd_input_text text;
  199. text.text = formatted_chat.prompt;
  200. text.add_special = add_bos;
  201. text.parse_special = true;
  202. mtmd_input_chunks chunks;
  203. if (g_is_interrupted) return 0;
  204. int32_t res = mtmd_tokenize(ctx.ctx_vision.get(), chunks, text, bitmaps);
  205. if (res != 0) {
  206. LOG_ERR("Unable to tokenize prompt, res = %d\n", res);
  207. return 1;
  208. }
  209. if (mtmd_helper_eval(ctx.ctx_vision.get(), ctx.lctx, chunks, ctx.n_past, 0, ctx.n_batch)) {
  210. LOG_ERR("Unable to eval prompt\n");
  211. return 1;
  212. }
  213. ctx.n_past += mtmd_helper_get_n_tokens(chunks);
  214. return 0;
  215. }
  216. int main(int argc, char ** argv) {
  217. ggml_time_init();
  218. common_params params;
  219. params.sampling.temp = 0.2; // lower temp by default for better quality
  220. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  221. return 1;
  222. }
  223. common_init();
  224. if (params.mmproj.path.empty()) {
  225. show_additional_info(argc, argv);
  226. LOG_ERR("ERR: Missing --mmproj argument\n");
  227. return 1;
  228. }
  229. mtmd_cli_context ctx(params);
  230. printf("%s: %s\n", __func__, params.model.path.c_str());
  231. bool is_single_turn = !params.prompt.empty() && !params.image.empty();
  232. struct common_sampler * smpl = common_sampler_init(ctx.model, params.sampling);
  233. int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
  234. // ctrl+C handling
  235. {
  236. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  237. struct sigaction sigint_action;
  238. sigint_action.sa_handler = sigint_handler;
  239. sigemptyset (&sigint_action.sa_mask);
  240. sigint_action.sa_flags = 0;
  241. sigaction(SIGINT, &sigint_action, NULL);
  242. #elif defined (_WIN32)
  243. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  244. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  245. };
  246. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  247. #endif
  248. }
  249. if (g_is_interrupted) return 130;
  250. if (is_single_turn) {
  251. g_is_generating = true;
  252. if (params.prompt.find("<__image__>") == std::string::npos) {
  253. params.prompt += " <__image__>";
  254. }
  255. common_chat_msg msg;
  256. msg.role = "user";
  257. msg.content = params.prompt;
  258. if (eval_message(ctx, msg, params.image, true)) {
  259. return 1;
  260. }
  261. if (!g_is_interrupted && generate_response(ctx, smpl, n_predict)) {
  262. return 1;
  263. }
  264. } else {
  265. LOG("\n Running in chat mode, available commands:");
  266. LOG("\n /image <path> load an image");
  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::vector<std::string> images_fname;
  272. std::string content;
  273. while (!g_is_interrupted) {
  274. g_is_generating = false;
  275. LOG("\n> ");
  276. console::set_display(console::user_input);
  277. std::string line;
  278. console::readline(line, false);
  279. if (g_is_interrupted) break;
  280. console::set_display(console::reset);
  281. line = string_strip(line);
  282. if (line.empty()) {
  283. continue;
  284. }
  285. if (line == "/quit" || line == "/exit") {
  286. break;
  287. }
  288. if (line == "/clear") {
  289. ctx.n_past = 0;
  290. llama_kv_self_seq_rm(ctx.lctx, 0, 1, -1); // keep BOS
  291. LOG("Chat history cleared\n\n");
  292. continue;
  293. }
  294. g_is_generating = true;
  295. if (line.find("/image") == 0) {
  296. std::string image = line.substr(7);
  297. images_fname.push_back(string_strip(image));
  298. content += "<__image__>";
  299. continue;
  300. } else {
  301. content += line;
  302. }
  303. common_chat_msg msg;
  304. msg.role = "user";
  305. msg.content = content;
  306. int ret = eval_message(ctx, msg, images_fname, is_first_msg);
  307. if (g_is_interrupted) break;
  308. if (ret == 2) {
  309. // non-fatal error
  310. images_fname.clear();
  311. content.clear();
  312. continue;
  313. }
  314. if (ret) {
  315. return 1;
  316. }
  317. if (generate_response(ctx, smpl, n_predict)) {
  318. return 1;
  319. }
  320. images_fname.clear();
  321. content.clear();
  322. is_first_msg = false;
  323. }
  324. }
  325. if (g_is_interrupted) LOG("\nInterrupted by user\n");
  326. llama_perf_context_print(ctx.lctx);
  327. return g_is_interrupted ? 130 : 0;
  328. }