save-load-state.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <vector>
  4. #include <cstdio>
  5. #include <chrono>
  6. int main(int argc, char ** argv) {
  7. gpt_params params;
  8. params.prompt = "The quick brown fox";
  9. if (!gpt_params_parse(argc, argv, params)) {
  10. gpt_params_print_usage(argc, argv, params);
  11. return 1;
  12. }
  13. print_build_info();
  14. if (params.n_predict < 0) {
  15. params.n_predict = 16;
  16. }
  17. auto n_past = 0;
  18. std::string result0;
  19. std::string result1;
  20. std::string result2;
  21. // init
  22. llama_init_result llama_init = llama_init_from_gpt_params(params);
  23. llama_model * model = llama_init.model;
  24. llama_context * ctx = llama_init.context;
  25. if (model == nullptr || ctx == nullptr) {
  26. fprintf(stderr, "%s : failed to init\n", __func__);
  27. return 1;
  28. }
  29. // tokenize prompt
  30. auto tokens = llama_tokenize(ctx, params.prompt, true);
  31. // evaluate prompt
  32. llama_decode(ctx, llama_batch_get_one(tokens.data(), tokens.size(), n_past, 0));
  33. n_past += tokens.size();
  34. // save state (rng, logits, embedding and kv_cache) to file
  35. {
  36. std::vector<uint8_t> state_mem(llama_state_get_size(ctx));
  37. const size_t written = llama_state_get_data(ctx, state_mem.data(), state_mem.size());
  38. FILE *fp_write = fopen("dump_state.bin", "wb");
  39. fwrite(state_mem.data(), 1, written, fp_write);
  40. fclose(fp_write);
  41. fprintf(stderr, "%s : serialized state into %zd out of a maximum of %zd bytes\n", __func__, written, state_mem.size());
  42. }
  43. // save state (last tokens)
  44. const auto n_past_saved = n_past;
  45. // first run
  46. printf("\nfirst run: %s", params.prompt.c_str());
  47. for (auto i = 0; i < params.n_predict; i++) {
  48. auto * logits = llama_get_logits(ctx);
  49. auto n_vocab = llama_n_vocab(model);
  50. std::vector<llama_token_data> candidates;
  51. candidates.reserve(n_vocab);
  52. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  53. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  54. }
  55. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  56. auto next_token = llama_sample_token(ctx, &candidates_p);
  57. auto next_token_str = llama_token_to_piece(ctx, next_token);
  58. printf("%s", next_token_str.c_str());
  59. result0 += next_token_str;
  60. if (llama_decode(ctx, llama_batch_get_one(&next_token, 1, n_past, 0))) {
  61. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  62. llama_free(ctx);
  63. llama_free_model(model);
  64. return 1;
  65. }
  66. n_past += 1;
  67. }
  68. printf("\n\n");
  69. // free old context
  70. llama_free(ctx);
  71. // make new context
  72. auto * ctx2 = llama_new_context_with_model(model, llama_context_params_from_gpt_params(params));
  73. printf("\nsecond run: %s", params.prompt.c_str());
  74. // load state (rng, logits, embedding and kv_cache) from file
  75. {
  76. std::vector<uint8_t> state_mem;
  77. FILE * fp_read = fopen("dump_state.bin", "rb");
  78. fseek(fp_read, 0, SEEK_END);
  79. state_mem.resize(ftell(fp_read));
  80. fseek(fp_read, 0, SEEK_SET);
  81. const size_t read = fread(state_mem.data(), 1, state_mem.size(), fp_read);
  82. fclose(fp_read);
  83. if (read != llama_state_set_data(ctx2, state_mem.data(), state_mem.size())) {
  84. fprintf(stderr, "\n%s : failed to read state\n", __func__);
  85. llama_free(ctx2);
  86. llama_free_model(model);
  87. return 1;
  88. }
  89. fprintf(stderr, "%s : deserialized state from %zd out of a maximum of %zd bytes\n", __func__, read, state_mem.size());
  90. }
  91. // restore state (last tokens)
  92. n_past = n_past_saved;
  93. // second run
  94. for (auto i = 0; i < params.n_predict; i++) {
  95. auto * logits = llama_get_logits(ctx2);
  96. auto n_vocab = llama_n_vocab(model);
  97. std::vector<llama_token_data> candidates;
  98. candidates.reserve(n_vocab);
  99. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  100. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  101. }
  102. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  103. auto next_token = llama_sample_token(ctx2, &candidates_p);
  104. auto next_token_str = llama_token_to_piece(ctx2, next_token);
  105. printf("%s", next_token_str.c_str());
  106. result1 += next_token_str;
  107. if (llama_decode(ctx2, llama_batch_get_one(&next_token, 1, n_past, 0))) {
  108. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  109. llama_free(ctx2);
  110. llama_free_model(model);
  111. return 1;
  112. }
  113. n_past += 1;
  114. }
  115. printf("\n\n");
  116. llama_free(ctx2);
  117. if (result0 != result1) {
  118. fprintf(stderr, "\n%s : error : the 2 generations are different\n", __func__);
  119. return 1;
  120. }
  121. // make new context
  122. auto* ctx3 = llama_new_context_with_model(model, llama_context_params_from_gpt_params(params));
  123. printf("\nsingle seq run: %s", params.prompt.c_str());
  124. // load state (rng, logits, embedding and kv_cache) from file
  125. {
  126. std::vector<uint8_t> state_mem;
  127. FILE * fp_read = fopen("dump_state.bin", "rb");
  128. fseek(fp_read, 0, SEEK_END);
  129. state_mem.resize(ftell(fp_read));
  130. fseek(fp_read, 0, SEEK_SET);
  131. const size_t read = fread(state_mem.data(), 1, state_mem.size(), fp_read);
  132. fclose(fp_read);
  133. if (read != llama_state_set_data(ctx3, state_mem.data(), state_mem.size())) {
  134. fprintf(stderr, "\n%s : failed to read state\n", __func__);
  135. llama_free(ctx3);
  136. llama_free_model(model);
  137. return 1;
  138. }
  139. fprintf(stderr, "%s : deserialized state from %zd out of a maximum of %zd bytes\n", __func__, read, state_mem.size());
  140. }
  141. // restore state (last tokens)
  142. n_past = n_past_saved;
  143. // save seq 0 and load into seq 1
  144. {
  145. // save kv of seq 0
  146. std::vector<uint8_t> seq_store(llama_state_seq_get_size(ctx3, 0));
  147. const size_t ncopy = llama_state_seq_get_data(ctx3, seq_store.data(), seq_store.size(), 0);
  148. if (ncopy != seq_store.size()) {
  149. fprintf(stderr, "\n%s : seq copy data length %zd does not match expected length %zd\n", __func__, ncopy, seq_store.size());
  150. llama_free(ctx3);
  151. llama_free_model(model);
  152. return 1;
  153. }
  154. fprintf(stderr, "%s : seq 0 copied, %zd bytes\n", __func__, ncopy);
  155. // erase whole kv
  156. llama_kv_cache_clear(ctx3);
  157. fprintf(stderr, "%s : kv cache cleared\n", __func__);
  158. // restore kv into seq 1
  159. const size_t nset = llama_state_seq_set_data(ctx3, seq_store.data(), seq_store.size(), 1);
  160. if (nset != seq_store.size()) {
  161. fprintf(stderr, "\n%s : seq set data length %zd does not match expected length %zd\n", __func__, nset, seq_store.size());
  162. llama_free(ctx3);
  163. llama_free_model(model);
  164. return 1;
  165. }
  166. fprintf(stderr, "%s : seq 1 restored, %zd bytes\n", __func__, nset);
  167. }
  168. // third run with seq 1 instead of 0
  169. for (auto i = 0; i < params.n_predict; i++) {
  170. auto * logits = llama_get_logits(ctx3);
  171. auto n_vocab = llama_n_vocab(model);
  172. std::vector<llama_token_data> candidates;
  173. candidates.reserve(n_vocab);
  174. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  175. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  176. }
  177. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  178. auto next_token = llama_sample_token(ctx3, &candidates_p);
  179. auto next_token_str = llama_token_to_piece(ctx3, next_token);
  180. printf("%s", next_token_str.c_str());
  181. result2 += next_token_str;
  182. if (llama_decode(ctx3, llama_batch_get_one(&next_token, 1, n_past, 1))) {
  183. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  184. llama_free(ctx3);
  185. llama_free_model(model);
  186. return 1;
  187. }
  188. n_past += 1;
  189. }
  190. printf("\n");
  191. llama_free(ctx3);
  192. llama_free_model(model);
  193. if (result0 != result2) {
  194. fprintf(stderr, "\n%s : error : the seq restore generation is different\n", __func__);
  195. return 1;
  196. }
  197. fprintf(stderr, "\n%s : success\n", __func__);
  198. return 0;
  199. }