main.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #include "ggml/ggml.h"
  2. #include "common.h"
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <ctime>
  7. #include <fstream>
  8. #include <string>
  9. #include <vector>
  10. #include <algorithm>
  11. #if defined(_MSC_VER)
  12. #pragma warning(disable: 4244 4267) // possible loss of data
  13. #endif
  14. // default hparams
  15. struct mnist_hparams {
  16. int32_t n_input = 784;
  17. int32_t n_hidden = 500;
  18. int32_t n_classes = 10;
  19. };
  20. struct mnist_model {
  21. mnist_hparams hparams;
  22. struct ggml_tensor * fc1_weight;
  23. struct ggml_tensor * fc1_bias;
  24. struct ggml_tensor * fc2_weight;
  25. struct ggml_tensor * fc2_bias;
  26. struct ggml_context * ctx;
  27. };
  28. // load the model's weights from a file
  29. bool mnist_model_load(const std::string & fname, mnist_model & model) {
  30. printf("%s: loading model from '%s'\n", __func__, fname.c_str());
  31. auto fin = std::ifstream(fname, std::ios::binary);
  32. if (!fin) {
  33. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  34. return false;
  35. }
  36. // verify magic
  37. {
  38. uint32_t magic;
  39. fin.read((char *) &magic, sizeof(magic));
  40. if (magic != GGML_FILE_MAGIC) {
  41. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  42. return false;
  43. }
  44. }
  45. auto & ctx = model.ctx;
  46. size_t ctx_size = 0;
  47. {
  48. const auto & hparams = model.hparams;
  49. const int n_input = hparams.n_input;
  50. const int n_hidden = hparams.n_hidden;
  51. const int n_classes = hparams.n_classes;
  52. ctx_size += n_input * n_hidden * ggml_type_sizef(GGML_TYPE_F32); // fc1 weight
  53. ctx_size += n_hidden * ggml_type_sizef(GGML_TYPE_F32); // fc1 bias
  54. ctx_size += n_hidden * n_classes * ggml_type_sizef(GGML_TYPE_F32); // fc2 weight
  55. ctx_size += n_classes * ggml_type_sizef(GGML_TYPE_F32); // fc2 bias
  56. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  57. }
  58. // create the ggml context
  59. {
  60. struct ggml_init_params params = {
  61. /*.mem_size =*/ ctx_size + 1024*1024,
  62. /*.mem_buffer =*/ NULL,
  63. /*.no_alloc =*/ false,
  64. };
  65. model.ctx = ggml_init(params);
  66. if (!model.ctx) {
  67. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  68. return false;
  69. }
  70. }
  71. // Read FC1 layer 1
  72. {
  73. // Read dimensions
  74. int32_t n_dims;
  75. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  76. {
  77. int32_t ne_weight[2] = { 1, 1 };
  78. for (int i = 0; i < n_dims; ++i) {
  79. fin.read(reinterpret_cast<char *>(&ne_weight[i]), sizeof(ne_weight[i]));
  80. }
  81. // FC1 dimensions taken from file, eg. 768x500
  82. model.hparams.n_input = ne_weight[0];
  83. model.hparams.n_hidden = ne_weight[1];
  84. model.fc1_weight = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, model.hparams.n_input, model.hparams.n_hidden);
  85. fin.read(reinterpret_cast<char *>(model.fc1_weight->data), ggml_nbytes(model.fc1_weight));
  86. ggml_set_name(model.fc1_weight, "fc1_weight");
  87. }
  88. {
  89. int32_t ne_bias[2] = { 1, 1 };
  90. for (int i = 0; i < n_dims; ++i) {
  91. fin.read(reinterpret_cast<char *>(&ne_bias[i]), sizeof(ne_bias[i]));
  92. }
  93. model.fc1_bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_hidden);
  94. fin.read(reinterpret_cast<char *>(model.fc1_bias->data), ggml_nbytes(model.fc1_bias));
  95. ggml_set_name(model.fc1_bias, "fc1_bias");
  96. // just for testing purposes, set some parameters to non-zero
  97. model.fc1_bias->op_params[0] = 0xdeadbeef;
  98. }
  99. }
  100. // Read FC2 layer 2
  101. {
  102. // Read dimensions
  103. int32_t n_dims;
  104. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  105. {
  106. int32_t ne_weight[2] = { 1, 1 };
  107. for (int i = 0; i < n_dims; ++i) {
  108. fin.read(reinterpret_cast<char *>(&ne_weight[i]), sizeof(ne_weight[i]));
  109. }
  110. // FC1 dimensions taken from file, eg. 10x500
  111. model.hparams.n_classes = ne_weight[1];
  112. model.fc2_weight = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, model.hparams.n_hidden, model.hparams.n_classes);
  113. fin.read(reinterpret_cast<char *>(model.fc2_weight->data), ggml_nbytes(model.fc2_weight));
  114. ggml_set_name(model.fc2_weight, "fc2_weight");
  115. }
  116. {
  117. int32_t ne_bias[2] = { 1, 1 };
  118. for (int i = 0; i < n_dims; ++i) {
  119. fin.read(reinterpret_cast<char *>(&ne_bias[i]), sizeof(ne_bias[i]));
  120. }
  121. model.fc2_bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_classes);
  122. fin.read(reinterpret_cast<char *>(model.fc2_bias->data), ggml_nbytes(model.fc2_bias));
  123. ggml_set_name(model.fc2_bias, "fc2_bias");
  124. }
  125. }
  126. fin.close();
  127. return true;
  128. }
  129. // evaluate the model
  130. //
  131. // - model: the model
  132. // - n_threads: number of threads to use
  133. // - digit: 784 pixel values
  134. //
  135. // returns 0 - 9 prediction
  136. int mnist_eval(
  137. const mnist_model & model,
  138. const int n_threads,
  139. std::vector<float> digit,
  140. const char * fname_cgraph
  141. ) {
  142. const auto & hparams = model.hparams;
  143. static size_t buf_size = hparams.n_input * sizeof(float) * 4;
  144. static void * buf = malloc(buf_size);
  145. struct ggml_init_params params = {
  146. /*.mem_size =*/ buf_size,
  147. /*.mem_buffer =*/ buf,
  148. /*.no_alloc =*/ false,
  149. };
  150. struct ggml_context * ctx0 = ggml_init(params);
  151. struct ggml_cgraph gf = {};
  152. struct ggml_tensor * input = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, hparams.n_input);
  153. memcpy(input->data, digit.data(), ggml_nbytes(input));
  154. ggml_set_name(input, "input");
  155. // fc1 MLP = Ax + b
  156. ggml_tensor * fc1 = ggml_add(ctx0, ggml_mul_mat(ctx0, model.fc1_weight, input), model.fc1_bias);
  157. ggml_tensor * fc2 = ggml_add(ctx0, ggml_mul_mat(ctx0, model.fc2_weight, ggml_relu(ctx0, fc1)), model.fc2_bias);
  158. // soft max
  159. ggml_tensor * probs = ggml_soft_max(ctx0, fc2);
  160. ggml_set_name(probs, "probs");
  161. // build / export / run the computation graph
  162. ggml_build_forward_expand(&gf, probs);
  163. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  164. //ggml_graph_print (&gf);
  165. ggml_graph_dump_dot(&gf, NULL, "mnist.dot");
  166. if (fname_cgraph) {
  167. // export the compute graph for later use
  168. // see the "mnist-cpu" example
  169. ggml_graph_export(&gf, "mnist.ggml");
  170. fprintf(stderr, "%s: exported compute graph to '%s'\n", __func__, fname_cgraph);
  171. }
  172. const float * probs_data = ggml_get_data_f32(probs);
  173. const int prediction = std::max_element(probs_data, probs_data + 10) - probs_data;
  174. ggml_free(ctx0);
  175. return prediction;
  176. }
  177. #ifdef __cplusplus
  178. extern "C" {
  179. #endif
  180. int wasm_eval(uint8_t * digitPtr) {
  181. mnist_model model;
  182. if (!mnist_model_load("models/mnist/ggml-model-f32.bin", model)) {
  183. fprintf(stderr, "error loading model\n");
  184. return -1;
  185. }
  186. std::vector<float> digit(digitPtr, digitPtr + 784);
  187. int result = mnist_eval(model, 1, digit, nullptr);
  188. ggml_free(model.ctx);
  189. return result;
  190. }
  191. int wasm_random_digit(char * digitPtr) {
  192. auto fin = std::ifstream("models/mnist/t10k-images.idx3-ubyte", std::ios::binary);
  193. if (!fin) {
  194. fprintf(stderr, "failed to open digits file\n");
  195. return 0;
  196. }
  197. srand(time(NULL));
  198. // Seek to a random digit: 16-byte header + 28*28 * (random 0 - 10000)
  199. fin.seekg(16 + 784 * (rand() % 10000));
  200. fin.read(digitPtr, 784);
  201. return 1;
  202. }
  203. #ifdef __cplusplus
  204. }
  205. #endif
  206. int main(int argc, char ** argv) {
  207. srand(time(NULL));
  208. ggml_time_init();
  209. if (argc != 3) {
  210. fprintf(stderr, "Usage: %s models/mnist/ggml-model-f32.bin models/mnist/t10k-images.idx3-ubyte\n", argv[0]);
  211. exit(0);
  212. }
  213. uint8_t buf[784];
  214. mnist_model model;
  215. std::vector<float> digit;
  216. // load the model
  217. {
  218. const int64_t t_start_us = ggml_time_us();
  219. if (!mnist_model_load(argv[1], model)) {
  220. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, "models/ggml-model-f32.bin");
  221. return 1;
  222. }
  223. const int64_t t_load_us = ggml_time_us() - t_start_us;
  224. fprintf(stdout, "%s: loaded model in %8.2f ms\n", __func__, t_load_us / 1000.0f);
  225. }
  226. // read a random digit from the test set
  227. {
  228. std::ifstream fin(argv[2], std::ios::binary);
  229. if (!fin) {
  230. fprintf(stderr, "%s: failed to open '%s'\n", __func__, argv[2]);
  231. return 1;
  232. }
  233. // seek to a random digit: 16-byte header + 28*28 * (random 0 - 10000)
  234. fin.seekg(16 + 784 * (rand() % 10000));
  235. fin.read((char *) &buf, sizeof(buf));
  236. }
  237. // render the digit in ASCII
  238. {
  239. digit.resize(sizeof(buf));
  240. for (int row = 0; row < 28; row++) {
  241. for (int col = 0; col < 28; col++) {
  242. fprintf(stderr, "%c ", (float)buf[row*28 + col] > 230 ? '*' : '_');
  243. digit[row*28 + col] = ((float)buf[row*28 + col]);
  244. }
  245. fprintf(stderr, "\n");
  246. }
  247. fprintf(stderr, "\n");
  248. }
  249. const int prediction = mnist_eval(model, 1, digit, "mnist.ggml");
  250. fprintf(stdout, "%s: predicted digit is %d\n", __func__, prediction);
  251. ggml_free(model.ctx);
  252. return 0;
  253. }