gemma3-cli.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #include "arg.h"
  2. #include "log.h"
  3. #include "common.h"
  4. #include "sampling.h"
  5. #include "clip.h"
  6. #include "stb_image.h"
  7. #include "llama.h"
  8. #include "ggml.h"
  9. #include "console.h"
  10. #include <vector>
  11. #include <limits.h>
  12. #include <inttypes.h>
  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. struct clip_ctx * ctx_clip = NULL;
  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_threads = 1;
  60. llama_pos n_past = 0;
  61. gemma3_context(common_params & params) : llama_init(common_init_from_params(params)) {
  62. model = llama_init.model.get();
  63. lctx = llama_init.context.get();
  64. vocab = llama_model_get_vocab(model);
  65. n_threads = params.cpuparams.n_threads;
  66. batch = llama_batch_init(params.n_batch, 0, 1);
  67. init_clip_model(params);
  68. }
  69. void init_clip_model(common_params & params) {
  70. const char * clip_path = params.mmproj.c_str();
  71. ctx_clip = clip_model_load(clip_path, params.verbosity > 1);
  72. }
  73. ~gemma3_context() {
  74. clip_free(ctx_clip);
  75. }
  76. };
  77. struct decode_embd_batch {
  78. std::vector<llama_pos> pos;
  79. std::vector<int32_t> n_seq_id;
  80. std::vector<llama_seq_id> seq_id_0;
  81. std::vector<llama_seq_id *> seq_ids;
  82. std::vector<int8_t> logits;
  83. llama_batch batch;
  84. decode_embd_batch(float * embd, int32_t n_tokens, llama_pos pos_0, llama_seq_id seq_id) {
  85. pos .resize(n_tokens);
  86. n_seq_id.resize(n_tokens);
  87. seq_ids .resize(n_tokens + 1);
  88. logits .resize(n_tokens);
  89. seq_id_0.resize(1);
  90. seq_id_0[0] = seq_id;
  91. seq_ids [n_tokens] = nullptr;
  92. batch = {
  93. /*n_tokens =*/ n_tokens,
  94. /*tokens =*/ nullptr,
  95. /*embd =*/ embd,
  96. /*pos =*/ pos.data(),
  97. /*n_seq_id =*/ n_seq_id.data(),
  98. /*seq_id =*/ seq_ids.data(),
  99. /*logits =*/ logits.data(),
  100. };
  101. for (int i = 0; i < n_tokens; i++) {
  102. batch.pos [i] = pos_0 + i;
  103. batch.n_seq_id[i] = 1;
  104. batch.seq_id [i] = seq_id_0.data();
  105. batch.logits [i] = false;
  106. }
  107. }
  108. };
  109. static int eval_text(gemma3_context & ctx, std::string input, bool logits_last = false) {
  110. llama_tokens tokens = common_tokenize(ctx.lctx, input, false, true);
  111. common_batch_clear(ctx.batch);
  112. for (llama_token & t : tokens) {
  113. common_batch_add(ctx.batch, t, ctx.n_past++, {0}, false);
  114. }
  115. if (logits_last) {
  116. ctx.batch.logits[ctx.batch.n_tokens - 1] = true;
  117. }
  118. // LOG("eval_text (n_tokens = %d): %s\n", (int)tokens.size(), input.c_str());
  119. if (llama_decode(ctx.lctx, ctx.batch)) {
  120. LOG_ERR("Failed to decode text\n");
  121. return 1;
  122. }
  123. return 0;
  124. }
  125. static int eval_image(gemma3_context & ctx, std::string & fname) {
  126. std::vector<float> image_embd_v;
  127. int n_embd = llama_model_n_embd(ctx.model);
  128. int n_tokens = 256;
  129. image_embd_v.resize(n_tokens * n_embd);
  130. bool ok;
  131. struct clip_image_u8 * img_u8 = clip_image_u8_init();
  132. ok = clip_image_load_from_file(fname.c_str(), img_u8);
  133. if (!ok) {
  134. LOG_ERR("Unable to load image %s\n", fname.c_str());
  135. clip_image_u8_free(img_u8);
  136. return 2; // non-fatal error
  137. }
  138. clip_image_f32_batch batch_f32;
  139. ok = clip_image_preprocess(ctx.ctx_clip, img_u8, &batch_f32);
  140. if (!ok) {
  141. LOG_ERR("Unable to preprocess image\n");
  142. clip_image_f32_batch_free(&batch_f32);
  143. clip_image_u8_free(img_u8);
  144. return 1;
  145. }
  146. int64_t t0 = ggml_time_ms();
  147. LOG("Encoding image %s\n", fname.c_str());
  148. ok = clip_image_batch_encode(ctx.ctx_clip, ctx.n_threads, &batch_f32, image_embd_v.data());
  149. if (!ok) {
  150. LOG_ERR("Unable to encode image\n");
  151. clip_image_f32_batch_free(&batch_f32);
  152. clip_image_u8_free(img_u8);
  153. return 1;
  154. }
  155. LOG("Image encoded in %" PRId64 " ms\n", ggml_time_ms() - t0);
  156. clip_image_f32_batch_free(&batch_f32);
  157. clip_image_u8_free(img_u8);
  158. // decode image embeddings
  159. int64_t t1 = ggml_time_ms();
  160. eval_text(ctx, "<start_of_image>");
  161. llama_set_causal_attn(ctx.lctx, false);
  162. decode_embd_batch batch_img(image_embd_v.data(), n_tokens, ctx.n_past, 0);
  163. if (llama_decode(ctx.lctx, batch_img.batch)) {
  164. LOG_ERR("failed to decode image\n");
  165. return 1;
  166. }
  167. ctx.n_past += n_tokens;
  168. llama_set_causal_attn(ctx.lctx, true);
  169. eval_text(ctx, "<end_of_image>");
  170. LOG("Image decoded in %" PRId64 " ms\n", ggml_time_ms() - t1);
  171. return 0;
  172. }
  173. static int generate_response(gemma3_context & ctx, common_sampler * smpl, int n_predict) {
  174. for (int i = 0; i < n_predict; i++) {
  175. if (i > n_predict || !g_is_generating) {
  176. printf("\n");
  177. break;
  178. }
  179. llama_token token_id = common_sampler_sample(smpl, ctx.lctx, -1);
  180. common_sampler_accept(smpl, token_id, true);
  181. if (llama_vocab_is_eog(ctx.vocab, token_id)) {
  182. printf("\n");
  183. break; // end of generation
  184. }
  185. printf("%s", common_token_to_piece(ctx.lctx, token_id).c_str());
  186. fflush(stdout);
  187. // eval the token
  188. common_batch_clear(ctx.batch);
  189. common_batch_add(ctx.batch, token_id, ctx.n_past++, {0}, true);
  190. if (llama_decode(ctx.lctx, ctx.batch)) {
  191. LOG_ERR("failed to decode token\n");
  192. return 1;
  193. }
  194. }
  195. return 0;
  196. }
  197. int main(int argc, char ** argv) {
  198. ggml_time_init();
  199. common_params params;
  200. params.sampling.temp = 0.2; // lower temp by default for better quality
  201. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_LLAVA, show_additional_info)) {
  202. return 1;
  203. }
  204. common_init();
  205. if (params.mmproj.empty()) {
  206. show_additional_info(argc, argv);
  207. return 1;
  208. }
  209. gemma3_context ctx(params);
  210. printf("%s: %s\n", __func__, params.model.c_str());
  211. bool is_single_turn = !params.prompt.empty() && !params.image.empty();
  212. struct common_sampler * smpl = common_sampler_init(ctx.model, params.sampling);
  213. int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
  214. // ctrl+C handling
  215. {
  216. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  217. struct sigaction sigint_action;
  218. sigint_action.sa_handler = sigint_handler;
  219. sigemptyset (&sigint_action.sa_mask);
  220. sigint_action.sa_flags = 0;
  221. sigaction(SIGINT, &sigint_action, NULL);
  222. #elif defined (_WIN32)
  223. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  224. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  225. };
  226. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  227. #endif
  228. }
  229. if (eval_text(ctx, "<bos>")) {
  230. return 1;
  231. }
  232. if (is_single_turn) {
  233. g_is_generating = true;
  234. if (eval_text(ctx, "<start_of_turn>user\n")) {
  235. return 1;
  236. }
  237. for (auto & fname : params.image) {
  238. if (eval_image(ctx, fname)) {
  239. return 1;
  240. }
  241. }
  242. if (eval_text(ctx, params.prompt + "<end_of_turn><start_of_turn>model\n", true)) {
  243. return 1;
  244. }
  245. if (generate_response(ctx, smpl, n_predict)) {
  246. return 1;
  247. }
  248. } else {
  249. LOG("\n Running in chat mode, available commands:");
  250. LOG("\n /image <path> load an image");
  251. LOG("\n /clear clear the chat history");
  252. LOG("\n /quit or /exit exit the program");
  253. LOG("\n");
  254. if (eval_text(ctx, "<start_of_turn>user\n")) {
  255. return 1;
  256. }
  257. while (true) {
  258. g_is_generating = false;
  259. LOG("\n> ");
  260. console::set_display(console::user_input);
  261. std::string line;
  262. console::readline(line, false);
  263. console::set_display(console::reset);
  264. line = string_strip(line);
  265. if (line.empty()) {
  266. continue;
  267. }
  268. if (line == "/quit" || line == "/exit") {
  269. break;
  270. }
  271. if (line == "/clear") {
  272. ctx.n_past = 0;
  273. llama_kv_cache_seq_rm(ctx.lctx, 0, 1, -1); // keep BOS
  274. LOG("Chat history cleared\n\n");
  275. continue;
  276. }
  277. g_is_generating = true;
  278. if (line.find("/image") == 0) {
  279. std::string image = line.substr(7);
  280. int res = eval_image(ctx, image);
  281. if (res == 2) {
  282. continue; // image not found
  283. }
  284. if (res) {
  285. return 1;
  286. }
  287. continue;
  288. }
  289. if (eval_text(ctx, line + "<end_of_turn><start_of_turn>model\n", true)) {
  290. return 1;
  291. }
  292. if (generate_response(ctx, smpl, n_predict)) {
  293. return 1;
  294. }
  295. if (eval_text(ctx, "<end_of_turn><start_of_turn>user\n")) {
  296. return 1;
  297. }
  298. }
  299. }
  300. return 0;
  301. }