gemma3-cli.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 chunks;
  166. int32_t res = mtmd_tokenize(ctx.ctx_vision.get(), chunks, text, bitmaps);
  167. if (res != 0) {
  168. LOG_ERR("Unable to tokenize prompt, res = %d\n", res);
  169. return 1;
  170. }
  171. if (mtmd_helper_eval(ctx.ctx_vision.get(), ctx.lctx, chunks, ctx.n_past, 0, ctx.n_batch)) {
  172. LOG_ERR("Unable to eval prompt\n");
  173. return 1;
  174. }
  175. ctx.n_past += mtmd_helper_get_n_tokens(chunks);
  176. return 0;
  177. }
  178. int main(int argc, char ** argv) {
  179. ggml_time_init();
  180. common_params params;
  181. params.sampling.temp = 0.2; // lower temp by default for better quality
  182. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  183. return 1;
  184. }
  185. common_init();
  186. if (params.mmproj.path.empty()) {
  187. show_additional_info(argc, argv);
  188. return 1;
  189. }
  190. gemma3_context ctx(params);
  191. printf("%s: %s\n", __func__, params.model.path.c_str());
  192. bool is_single_turn = !params.prompt.empty() && !params.image.empty();
  193. struct common_sampler * smpl = common_sampler_init(ctx.model, params.sampling);
  194. int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
  195. // ctrl+C handling
  196. {
  197. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  198. struct sigaction sigint_action;
  199. sigint_action.sa_handler = sigint_handler;
  200. sigemptyset (&sigint_action.sa_mask);
  201. sigint_action.sa_flags = 0;
  202. sigaction(SIGINT, &sigint_action, NULL);
  203. #elif defined (_WIN32)
  204. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  205. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  206. };
  207. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  208. #endif
  209. }
  210. if (is_single_turn) {
  211. g_is_generating = true;
  212. if (params.prompt.find("<__image__>") == std::string::npos) {
  213. params.prompt += " <__image__>";
  214. }
  215. common_chat_msg msg;
  216. msg.role = "user";
  217. msg.content = params.prompt;
  218. if (eval_message(ctx, msg, params.image, true)) {
  219. return 1;
  220. }
  221. if (generate_response(ctx, smpl, n_predict)) {
  222. return 1;
  223. }
  224. } else {
  225. LOG("\n Running in chat mode, available commands:");
  226. LOG("\n /image <path> load an image");
  227. LOG("\n /clear clear the chat history");
  228. LOG("\n /quit or /exit exit the program");
  229. LOG("\n");
  230. bool is_first_msg = true;
  231. std::vector<std::string> images_fname;
  232. std::string content;
  233. while (true) {
  234. g_is_generating = false;
  235. LOG("\n> ");
  236. console::set_display(console::user_input);
  237. std::string line;
  238. console::readline(line, false);
  239. console::set_display(console::reset);
  240. line = string_strip(line);
  241. if (line.empty()) {
  242. continue;
  243. }
  244. if (line == "/quit" || line == "/exit") {
  245. break;
  246. }
  247. if (line == "/clear") {
  248. ctx.n_past = 0;
  249. llama_kv_self_seq_rm(ctx.lctx, 0, 1, -1); // keep BOS
  250. LOG("Chat history cleared\n\n");
  251. continue;
  252. }
  253. g_is_generating = true;
  254. if (line.find("/image") == 0) {
  255. std::string image = line.substr(7);
  256. images_fname.push_back(string_strip(image));
  257. content += "<__image__>";
  258. continue;
  259. } else {
  260. content += line;
  261. }
  262. common_chat_msg msg;
  263. msg.role = "user";
  264. msg.content = content;
  265. int ret = eval_message(ctx, msg, images_fname, is_first_msg);
  266. if (ret == 2) {
  267. // non-fatal error
  268. images_fname.clear();
  269. content.clear();
  270. continue;
  271. }
  272. if (ret) {
  273. return 1;
  274. }
  275. if (generate_response(ctx, smpl, n_predict)) {
  276. return 1;
  277. }
  278. images_fname.clear();
  279. content.clear();
  280. is_first_msg = false;
  281. }
  282. }
  283. llama_perf_context_print(ctx.lctx);
  284. return 0;
  285. }