save-load-state.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. 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. common_init_result llama_init = common_init_from_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. 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. llama_free(ctx);
  67. llama_free_model(model);
  68. return 1;
  69. }
  70. n_past += 1;
  71. }
  72. printf("\n\n");
  73. // free old context
  74. llama_free(ctx);
  75. // make new context
  76. auto * ctx2 = llama_new_context_with_model(model, common_context_params_to_llama(params));
  77. llama_sampler * smpl2 = llama_sampler_chain_init(sparams);
  78. llama_sampler_chain_add(smpl2, llama_sampler_init_dist(params.sampling.seed));
  79. printf("\nsecond run: %s", params.prompt.c_str());
  80. // load state (rng, logits, embedding and kv_cache) from file
  81. {
  82. std::vector<uint8_t> state_mem;
  83. FILE * fp_read = fopen("dump_state.bin", "rb");
  84. fseek(fp_read, 0, SEEK_END);
  85. state_mem.resize(ftell(fp_read));
  86. fseek(fp_read, 0, SEEK_SET);
  87. const size_t read = fread(state_mem.data(), 1, state_mem.size(), fp_read);
  88. fclose(fp_read);
  89. if (read != llama_state_set_data(ctx2, state_mem.data(), state_mem.size())) {
  90. fprintf(stderr, "\n%s : failed to read state\n", __func__);
  91. llama_free(ctx2);
  92. llama_free_model(model);
  93. return 1;
  94. }
  95. fprintf(stderr, "%s : deserialized state from %zd out of a maximum of %zd bytes\n", __func__, read, state_mem.size());
  96. }
  97. // restore state (last tokens)
  98. n_past = n_past_saved;
  99. // second run
  100. for (auto i = 0; i < params.n_predict; i++) {
  101. auto next_token = llama_sampler_sample(smpl2, ctx2, -1);
  102. auto next_token_str = common_token_to_piece(ctx2, next_token);
  103. printf("%s", next_token_str.c_str());
  104. result1 += next_token_str;
  105. common_batch_clear(batch);
  106. common_batch_add(batch, next_token, n_past, {0}, true);
  107. if (llama_decode(ctx2, batch)) {
  108. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  109. llama_batch_free(batch);
  110. llama_free(ctx2);
  111. llama_free_model(model);
  112. return 1;
  113. }
  114. n_past += 1;
  115. }
  116. printf("\n\n");
  117. llama_free(ctx2);
  118. if (result0 != result1) {
  119. fprintf(stderr, "\n%s : error : the 2 generations are different\n", __func__);
  120. return 1;
  121. }
  122. // make new context
  123. auto * ctx3 = llama_new_context_with_model(model, common_context_params_to_llama(params));
  124. llama_sampler * smpl3 = llama_sampler_chain_init(sparams);
  125. llama_sampler_chain_add(smpl3, llama_sampler_init_dist(params.sampling.seed));
  126. printf("\nsingle seq run: %s", params.prompt.c_str());
  127. // load state (rng, logits, embedding and kv_cache) from file
  128. {
  129. std::vector<uint8_t> state_mem;
  130. FILE * fp_read = fopen("dump_state.bin", "rb");
  131. fseek(fp_read, 0, SEEK_END);
  132. state_mem.resize(ftell(fp_read));
  133. fseek(fp_read, 0, SEEK_SET);
  134. const size_t read = fread(state_mem.data(), 1, state_mem.size(), fp_read);
  135. fclose(fp_read);
  136. if (read != llama_state_set_data(ctx3, state_mem.data(), state_mem.size())) {
  137. fprintf(stderr, "\n%s : failed to read state\n", __func__);
  138. llama_free(ctx3);
  139. llama_free_model(model);
  140. return 1;
  141. }
  142. fprintf(stderr, "%s : deserialized state from %zd out of a maximum of %zd bytes\n", __func__, read, state_mem.size());
  143. }
  144. // restore state (last tokens)
  145. n_past = n_past_saved;
  146. // save seq 0 and load into seq 1
  147. {
  148. // save kv of seq 0
  149. std::vector<uint8_t> seq_store(llama_state_seq_get_size(ctx3, 0));
  150. const size_t ncopy = llama_state_seq_get_data(ctx3, seq_store.data(), seq_store.size(), 0);
  151. if (ncopy != seq_store.size()) {
  152. fprintf(stderr, "\n%s : seq copy data length %zd does not match expected length %zd\n", __func__, ncopy, seq_store.size());
  153. llama_free(ctx3);
  154. llama_free_model(model);
  155. return 1;
  156. }
  157. fprintf(stderr, "%s : seq 0 copied, %zd bytes\n", __func__, ncopy);
  158. // erase whole kv
  159. llama_kv_cache_clear(ctx3);
  160. fprintf(stderr, "%s : kv cache cleared\n", __func__);
  161. // restore kv into seq 1
  162. const size_t nset = llama_state_seq_set_data(ctx3, seq_store.data(), seq_store.size(), 1);
  163. if (nset != seq_store.size()) {
  164. fprintf(stderr, "\n%s : seq set data length %zd does not match expected length %zd\n", __func__, nset, seq_store.size());
  165. llama_free(ctx3);
  166. llama_free_model(model);
  167. return 1;
  168. }
  169. fprintf(stderr, "%s : seq 1 restored, %zd bytes\n", __func__, nset);
  170. }
  171. // third run with seq 1 instead of 0
  172. for (auto i = 0; i < params.n_predict; i++) {
  173. auto next_token = llama_sampler_sample(smpl3, ctx3, -1);
  174. auto next_token_str = common_token_to_piece(ctx3, next_token);
  175. printf("%s", next_token_str.c_str());
  176. result2 += next_token_str;
  177. common_batch_clear(batch);
  178. common_batch_add(batch, next_token, n_past, {1}, true);
  179. if (llama_decode(ctx3, batch)) {
  180. fprintf(stderr, "\n%s : failed to evaluate\n", __func__);
  181. llama_batch_free(batch);
  182. llama_free(ctx3);
  183. llama_free_model(model);
  184. return 1;
  185. }
  186. n_past += 1;
  187. }
  188. printf("\n");
  189. llama_sampler_free(smpl);
  190. llama_sampler_free(smpl2);
  191. llama_sampler_free(smpl3);
  192. llama_batch_free(batch);
  193. llama_free(ctx3);
  194. llama_free_model(model);
  195. if (result0 != result2) {
  196. fprintf(stderr, "\n%s : error : the seq restore generation is different\n", __func__);
  197. return 1;
  198. }
  199. fprintf(stderr, "\n%s : success\n", __func__);
  200. return 0;
  201. }