save-load-state.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "llama.h"
  4. #include <vector>
  5. #include <cstdio>
  6. int main(int argc, char ** argv) {
  7. common_params params;
  8. params.prompt = "The quick brown fox";
  9. params.sampling.seed = 1234;
  10. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) {
  11. return 1;
  12. }
  13. common_init();
  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. common_init_result llama_init = common_init_from_params(params);
  23. llama_model * model = llama_init.model.get();
  24. llama_context * ctx = llama_init.context.get();
  25. if (model == nullptr || ctx == nullptr) {
  26. fprintf(stderr, "%s : failed to init\n", __func__);
  27. return 1;
  28. }
  29. auto sparams = llama_sampler_chain_default_params();
  30. llama_sampler * smpl = llama_sampler_chain_init(sparams);
  31. llama_sampler_chain_add(smpl, llama_sampler_init_dist(params.sampling.seed));
  32. // tokenize prompt
  33. auto tokens = common_tokenize(ctx, params.prompt, true);
  34. // prepare the batch
  35. llama_batch batch = llama_batch_init(tokens.size(), 0, 1);
  36. for (size_t i = 0; i < tokens.size(); i++) {
  37. common_batch_add(batch, tokens[i], i, {0}, false);
  38. }
  39. batch.logits[batch.n_tokens - 1] = true; // generate next token
  40. // evaluate prompt
  41. llama_decode(ctx, batch);
  42. n_past += batch.n_tokens;
  43. // save state (rng, logits, embedding and kv_cache) to file
  44. {
  45. std::vector<uint8_t> state_mem(llama_state_get_size(ctx));
  46. const size_t written = llama_state_get_data(ctx, state_mem.data(), state_mem.size());
  47. FILE *fp_write = fopen("dump_state.bin", "wb");
  48. fwrite(state_mem.data(), 1, written, fp_write);
  49. fclose(fp_write);
  50. fprintf(stderr, "%s : serialized state into %zd out of a maximum of %zd bytes\n", __func__, written, state_mem.size());
  51. }
  52. // save state (last tokens)
  53. const auto n_past_saved = n_past;
  54. // first run
  55. printf("\nfirst run: %s", params.prompt.c_str());
  56. for (auto i = 0; i < params.n_predict; i++) {
  57. auto next_token = llama_sampler_sample(smpl, ctx, -1);
  58. auto next_token_str = common_token_to_piece(ctx, next_token);
  59. printf("%s", next_token_str.c_str());
  60. result0 += next_token_str;
  61. common_batch_clear(batch);
  62. common_batch_add(batch, next_token, n_past, {0}, true);
  63. if (llama_decode(ctx, batch)) {
  64. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  65. llama_batch_free(batch);
  66. return 1;
  67. }
  68. n_past += 1;
  69. }
  70. printf("\n\n");
  71. // make new context
  72. llama_context * ctx2 = llama_init_from_model(model, common_context_params_to_llama(params));
  73. llama_sampler * smpl2 = llama_sampler_chain_init(sparams);
  74. llama_sampler_chain_add(smpl2, llama_sampler_init_dist(params.sampling.seed));
  75. printf("\nsecond run: %s", params.prompt.c_str());
  76. // load state (rng, logits, embedding and kv_cache) from file
  77. {
  78. std::vector<uint8_t> state_mem;
  79. FILE * fp_read = fopen("dump_state.bin", "rb");
  80. fseek(fp_read, 0, SEEK_END);
  81. state_mem.resize(ftell(fp_read));
  82. fseek(fp_read, 0, SEEK_SET);
  83. const size_t read = fread(state_mem.data(), 1, state_mem.size(), fp_read);
  84. fclose(fp_read);
  85. if (read != llama_state_set_data(ctx2, state_mem.data(), state_mem.size())) {
  86. fprintf(stderr, "\n%s : failed to read state\n", __func__);
  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 next_token = llama_sampler_sample(smpl2, ctx2, -1);
  96. auto next_token_str = common_token_to_piece(ctx2, next_token);
  97. printf("%s", next_token_str.c_str());
  98. result1 += next_token_str;
  99. common_batch_clear(batch);
  100. common_batch_add(batch, next_token, n_past, {0}, true);
  101. if (llama_decode(ctx2, batch)) {
  102. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  103. llama_batch_free(batch);
  104. return 1;
  105. }
  106. n_past += 1;
  107. }
  108. printf("\n\n");
  109. if (result0 != result1) {
  110. fprintf(stderr, "\n%s : error : the 2 generations are different\n", __func__);
  111. return 1;
  112. }
  113. // make new context
  114. llama_context * ctx3 = llama_init_from_model(model, common_context_params_to_llama(params));
  115. llama_sampler * smpl3 = llama_sampler_chain_init(sparams);
  116. llama_sampler_chain_add(smpl3, llama_sampler_init_dist(params.sampling.seed));
  117. printf("\nsingle seq run: %s", params.prompt.c_str());
  118. // load state (rng, logits, embedding and kv_cache) from file
  119. {
  120. std::vector<uint8_t> state_mem;
  121. FILE * fp_read = fopen("dump_state.bin", "rb");
  122. fseek(fp_read, 0, SEEK_END);
  123. state_mem.resize(ftell(fp_read));
  124. fseek(fp_read, 0, SEEK_SET);
  125. const size_t read = fread(state_mem.data(), 1, state_mem.size(), fp_read);
  126. fclose(fp_read);
  127. if (read != llama_state_set_data(ctx3, state_mem.data(), state_mem.size())) {
  128. fprintf(stderr, "\n%s : failed to read state\n", __func__);
  129. return 1;
  130. }
  131. fprintf(stderr, "%s : deserialized state from %zd out of a maximum of %zd bytes\n", __func__, read, state_mem.size());
  132. }
  133. // restore state (last tokens)
  134. n_past = n_past_saved;
  135. // save seq 0 and load into seq 1
  136. {
  137. // save kv of seq 0
  138. std::vector<uint8_t> seq_store(llama_state_seq_get_size(ctx3, 0));
  139. const size_t ncopy = llama_state_seq_get_data(ctx3, seq_store.data(), seq_store.size(), 0);
  140. if (ncopy != seq_store.size()) {
  141. fprintf(stderr, "\n%s : seq copy data length %zd does not match expected length %zd\n", __func__, ncopy, seq_store.size());
  142. return 1;
  143. }
  144. fprintf(stderr, "%s : seq 0 copied, %zd bytes\n", __func__, ncopy);
  145. // erase whole kv
  146. llama_kv_self_clear(ctx3);
  147. fprintf(stderr, "%s : kv cache cleared\n", __func__);
  148. // restore kv into seq 1
  149. const size_t nset = llama_state_seq_set_data(ctx3, seq_store.data(), seq_store.size(), 1);
  150. if (nset != seq_store.size()) {
  151. fprintf(stderr, "\n%s : seq set data length %zd does not match expected length %zd\n", __func__, nset, seq_store.size());
  152. return 1;
  153. }
  154. fprintf(stderr, "%s : seq 1 restored, %zd bytes\n", __func__, nset);
  155. }
  156. // third run with seq 1 instead of 0
  157. for (auto i = 0; i < params.n_predict; i++) {
  158. auto next_token = llama_sampler_sample(smpl3, ctx3, -1);
  159. auto next_token_str = common_token_to_piece(ctx3, next_token);
  160. printf("%s", next_token_str.c_str());
  161. result2 += next_token_str;
  162. common_batch_clear(batch);
  163. common_batch_add(batch, next_token, n_past, {1}, true);
  164. if (llama_decode(ctx3, batch)) {
  165. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  166. llama_batch_free(batch);
  167. return 1;
  168. }
  169. n_past += 1;
  170. }
  171. printf("\n");
  172. llama_sampler_free(smpl);
  173. llama_sampler_free(smpl2);
  174. llama_sampler_free(smpl3);
  175. llama_batch_free(batch);
  176. if (result0 != result2) {
  177. fprintf(stderr, "\n%s : error : the seq restore generation is different\n", __func__);
  178. return 1;
  179. }
  180. fprintf(stderr, "\n%s : success\n", __func__);
  181. return 0;
  182. }