gemma3-cli.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. static bool g_is_generating = false;
  25. /**
  26. * Please note that this is NOT a production-ready stuff.
  27. * It is a playground for trying Gemma 3 vision capabilities.
  28. * For contributors: please keep this code simple and easy to understand.
  29. */
  30. static void show_additional_info(int /*argc*/, char ** argv) {
  31. LOG(
  32. "Experimental CLI for using Gemma 3 vision model\n\n"
  33. "Usage: %s [options] -m <model> --mmproj <mmproj> --image <image> -p <prompt>\n\n"
  34. " -m and --mmproj are required\n"
  35. " --image and -p are optional, if NOT provided, the CLI will run in chat mode\n",
  36. argv[0]
  37. );
  38. }
  39. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  40. static void sigint_handler(int signo) {
  41. if (signo == SIGINT) {
  42. if (g_is_generating) {
  43. g_is_generating = false;
  44. } else {
  45. console::cleanup();
  46. LOG("\nInterrupted by user\n");
  47. _exit(130);
  48. }
  49. }
  50. }
  51. #endif
  52. struct gemma3_context {
  53. mtmd_context_ptr ctx_vision;
  54. common_init_result llama_init;
  55. llama_model * model;
  56. llama_context * lctx;
  57. const llama_vocab * vocab;
  58. llama_batch batch;
  59. int n_batch;
  60. // note: we know that gemma3 template is "linear", meaning each turn is completely separated to another
  61. // so here we don't need to keep track of chat history
  62. common_chat_templates_ptr tmpls;
  63. int n_threads = 1;
  64. llama_pos n_past = 0;
  65. gemma3_context(common_params & params) : llama_init(common_init_from_params(params)) {
  66. model = llama_init.model.get();
  67. lctx = llama_init.context.get();
  68. vocab = llama_model_get_vocab(model);
  69. n_threads = params.cpuparams.n_threads;
  70. batch = llama_batch_init(params.n_batch, 0, 1);
  71. n_batch = params.n_batch;
  72. tmpls = common_chat_templates_init(model, params.chat_template);
  73. init_vision_context(params);
  74. }
  75. void init_vision_context(common_params & params) {
  76. const char * clip_path = params.mmproj.path.c_str();
  77. ctx_vision.reset(mtmd_init_from_file(clip_path, model, mtmd_context_params{
  78. /* use_gpu */ true,
  79. /* timings */ true,
  80. /* n_threads */ params.cpuparams.n_threads,
  81. /* verbosity */ GGML_LOG_LEVEL_INFO,
  82. }));
  83. if (!ctx_vision.get()) {
  84. LOG_ERR("Failed to load vision model from %s\n", clip_path);
  85. exit(1);
  86. }
  87. }
  88. };
  89. struct decode_embd_batch {
  90. std::vector<llama_pos> pos;
  91. std::vector<int32_t> n_seq_id;
  92. std::vector<llama_seq_id> seq_id_0;
  93. std::vector<llama_seq_id *> seq_ids;
  94. std::vector<int8_t> logits;
  95. llama_batch batch;
  96. decode_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  97. pos .resize(n_tokens);
  98. n_seq_id.resize(n_tokens);
  99. seq_ids .resize(n_tokens + 1);
  100. logits .resize(n_tokens);
  101. seq_id_0.resize(1);
  102. seq_id_0[0] = seq_id;
  103. seq_ids [n_tokens] = nullptr;
  104. batch = {
  105. /*n_tokens =*/ n_tokens,
  106. /*tokens =*/ nullptr,
  107. /*embd =*/ embd,
  108. /*pos =*/ pos.data(),
  109. /*n_seq_id =*/ n_seq_id.data(),
  110. /*seq_id =*/ seq_ids.data(),
  111. /*logits =*/ logits.data(),
  112. };
  113. for (int i = 0; i < n_tokens; i++) {
  114. batch.pos [i] = pos_0 + i;
  115. batch.n_seq_id[i] = 1;
  116. batch.seq_id [i] = seq_id_0.data();
  117. batch.logits [i] = false;
  118. }
  119. }
  120. };
  121. static int generate_response(gemma3_context & ctx, common_sampler * smpl, int n_predict) {
  122. for (int i = 0; i < n_predict; i++) {
  123. if (i > n_predict || !g_is_generating) {
  124. printf("\n");
  125. break;
  126. }
  127. llama_token token_id = common_sampler_sample(smpl, ctx.lctx, -1);
  128. common_sampler_accept(smpl, token_id, true);
  129. if (llama_vocab_is_eog(ctx.vocab, token_id)) {
  130. printf("\n");
  131. break; // end of generation
  132. }
  133. printf("%s", common_token_to_piece(ctx.lctx, token_id).c_str());
  134. fflush(stdout);
  135. // eval the token
  136. common_batch_clear(ctx.batch);
  137. common_batch_add(ctx.batch, token_id, ctx.n_past++, {0}, true);
  138. if (llama_decode(ctx.lctx, ctx.batch)) {
  139. LOG_ERR("failed to decode token\n");
  140. return 1;
  141. }
  142. }
  143. return 0;
  144. }
  145. static int eval_message(gemma3_context & ctx, common_chat_msg & msg, std::vector<std::string> & images_fname, bool add_bos = false) {
  146. std::vector<mtmd_bitmap> bitmaps;
  147. common_chat_templates_inputs tmpl_inputs;
  148. tmpl_inputs.messages = {msg};
  149. tmpl_inputs.add_generation_prompt = true;
  150. tmpl_inputs.use_jinja = false; // jinja is buggy here
  151. auto formatted_chat = common_chat_templates_apply(ctx.tmpls.get(), tmpl_inputs);
  152. LOG_DBG("formatted_chat.prompt: %s\n", formatted_chat.prompt.c_str());
  153. for (auto & fname : images_fname) {
  154. mtmd_bitmap bitmap;
  155. if (mtmd_helper_bitmap_init_from_file(fname.c_str(), bitmap)) {
  156. LOG_ERR("Unable to load image %s\n", fname.c_str());
  157. return 2; // image not found
  158. }
  159. bitmaps.push_back(std::move(bitmap));
  160. }
  161. mtmd_input_text text;
  162. text.text = formatted_chat.prompt;
  163. text.add_special = add_bos;
  164. text.parse_special = true;
  165. mtmd_input_chunks_ptr chunks(mtmd_tokenize(ctx.ctx_vision.get(), text, bitmaps));
  166. if (chunks == nullptr) {
  167. LOG_ERR("Unable to tokenize prompt\n");
  168. return 1;
  169. }
  170. if (mtmd_helper_eval(ctx.ctx_vision.get(), ctx.lctx, chunks.get(), ctx.n_past, 0, ctx.n_batch)) {
  171. LOG_ERR("Unable to eval prompt\n");
  172. return 1;
  173. }
  174. ctx.n_past += mtmd_helper_get_n_tokens(chunks.get());
  175. return 0;
  176. }
  177. int main(int argc, char ** argv) {
  178. ggml_time_init();
  179. common_params params;
  180. params.sampling.temp = 0.2; // lower temp by default for better quality
  181. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  182. return 1;
  183. }
  184. common_init();
  185. if (params.mmproj.path.empty()) {
  186. show_additional_info(argc, argv);
  187. return 1;
  188. }
  189. gemma3_context ctx(params);
  190. printf("%s: %s\n", __func__, params.model.path.c_str());
  191. bool is_single_turn = !params.prompt.empty() && !params.image.empty();
  192. struct common_sampler * smpl = common_sampler_init(ctx.model, params.sampling);
  193. int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
  194. // ctrl+C handling
  195. {
  196. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  197. struct sigaction sigint_action;
  198. sigint_action.sa_handler = sigint_handler;
  199. sigemptyset (&sigint_action.sa_mask);
  200. sigint_action.sa_flags = 0;
  201. sigaction(SIGINT, &sigint_action, NULL);
  202. #elif defined (_WIN32)
  203. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  204. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  205. };
  206. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  207. #endif
  208. }
  209. if (is_single_turn) {
  210. g_is_generating = true;
  211. if (params.prompt.find("<__image__>") == std::string::npos) {
  212. params.prompt += " <__image__>";
  213. }
  214. common_chat_msg msg;
  215. msg.role = "user";
  216. msg.content = params.prompt;
  217. if (eval_message(ctx, msg, params.image, true)) {
  218. return 1;
  219. }
  220. if (generate_response(ctx, smpl, n_predict)) {
  221. return 1;
  222. }
  223. } else {
  224. LOG("\n Running in chat mode, available commands:");
  225. LOG("\n /image <path> load an image");
  226. LOG("\n /clear clear the chat history");
  227. LOG("\n /quit or /exit exit the program");
  228. LOG("\n");
  229. bool is_first_msg = true;
  230. std::vector<std::string> images_fname;
  231. std::string content;
  232. while (true) {
  233. g_is_generating = false;
  234. LOG("\n> ");
  235. console::set_display(console::user_input);
  236. std::string line;
  237. console::readline(line, false);
  238. console::set_display(console::reset);
  239. line = string_strip(line);
  240. if (line.empty()) {
  241. continue;
  242. }
  243. if (line == "/quit" || line == "/exit") {
  244. break;
  245. }
  246. if (line == "/clear") {
  247. ctx.n_past = 0;
  248. llama_kv_self_seq_rm(ctx.lctx, 0, 1, -1); // keep BOS
  249. LOG("Chat history cleared\n\n");
  250. continue;
  251. }
  252. g_is_generating = true;
  253. if (line.find("/image") == 0) {
  254. std::string image = line.substr(7);
  255. images_fname.push_back(string_strip(image));
  256. content += "<__image__>";
  257. continue;
  258. } else {
  259. content += line;
  260. }
  261. common_chat_msg msg;
  262. msg.role = "user";
  263. msg.content = content;
  264. int ret = eval_message(ctx, msg, images_fname, is_first_msg);
  265. if (ret == 2) {
  266. // non-fatal error
  267. images_fname.clear();
  268. content.clear();
  269. continue;
  270. }
  271. if (ret) {
  272. return 1;
  273. }
  274. if (generate_response(ctx, smpl, n_predict)) {
  275. return 1;
  276. }
  277. images_fname.clear();
  278. content.clear();
  279. is_first_msg = false;
  280. }
  281. }
  282. llama_perf_context_print(ctx.lctx);
  283. return 0;
  284. }