1
0

save-load-state.cpp 7.9 KB

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