test-opt.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. #include "ggml.h"
  2. #include "ggml-alloc.h"
  3. #include "ggml-backend.h"
  4. #include "ggml-cpu.h"
  5. #include "ggml-opt.h"
  6. #include <cmath>
  7. #include <cinttypes>
  8. #include <random>
  9. #include <string>
  10. #include <thread>
  11. #include <vector>
  12. static bool almost_equal(const double a, const double b, const double atol) {
  13. return fabs(a - b) < atol;
  14. }
  15. constexpr int64_t ne_datapoint = 2;
  16. constexpr int64_t ne_label = 1;
  17. constexpr int64_t ndata = 6;
  18. struct helper_ctx_data {
  19. std::vector<ggml_opt_dataset_t> datasets_supervised;
  20. std::vector<struct ggml_tensor *> data_batch;
  21. std::vector<struct ggml_tensor *> labels_batch;
  22. ggml_opt_dataset_t dataset_unsupervised;
  23. struct ggml_context * ctx_static;
  24. struct ggml_context * ctx_compute;
  25. struct ggml_opt_params opt_params;
  26. ggml_opt_context_t opt_ctx;
  27. struct ggml_tensor * inputs;
  28. struct ggml_tensor * weights;
  29. struct ggml_tensor * outputs;
  30. ggml_backend_buffer_t buf;
  31. ggml_opt_result_t result;
  32. ggml_opt_result_t result2;
  33. };
  34. // These default values make it easier to check optimization results vs. expected values.
  35. static ggml_opt_optimizer_params helper_get_test_opt_pars(void * userdata) {
  36. ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(userdata);
  37. result.adamw.alpha = 1.0f;
  38. result.adamw.beta1 = 0.0f;
  39. result.adamw.beta2 = 0.0f;
  40. result.adamw.eps = 0.0f;
  41. return result;
  42. }
  43. static helper_ctx_data helper_get_ctx_data(
  44. ggml_backend_sched_t backend_sched,
  45. ggml_backend_t backend,
  46. const bool init_opt_ctx = true,
  47. const bool optimizer_defaults = true,
  48. int64_t nbatch_logical = 1,
  49. int64_t nbatch_physical = 1,
  50. enum ggml_opt_loss_type loss_type = GGML_OPT_LOSS_TYPE_SUM) {
  51. std::vector<ggml_opt_dataset_t> datasets(ndata);
  52. for (int64_t ndata_shard = 1; ndata_shard <= ndata; ++ndata_shard) {
  53. ggml_opt_dataset_t dataset = ggml_opt_dataset_init(ne_datapoint, ne_label, ndata, ndata_shard);
  54. float * data = ggml_get_data_f32(ggml_opt_dataset_data( dataset));
  55. float * labels = ggml_get_data_f32(ggml_opt_dataset_labels(dataset));
  56. for (int64_t idata = 0; idata < ndata; ++idata) {
  57. for (int64_t id = 0; id < ne_datapoint; ++id) {
  58. data[ idata*ne_datapoint + id] = 16*idata + id;
  59. }
  60. for (int64_t il = 0; il < ne_label; ++il) {
  61. labels[idata*ne_label + il] = 16*(16*idata + il);
  62. }
  63. }
  64. datasets[ndata_shard-1] = dataset;
  65. }
  66. ggml_opt_dataset_t dataset_unsupervised = ggml_opt_dataset_init(1, 0, ndata, /*ndata_shard =*/ 1);
  67. float * data = ggml_get_data_f32(ggml_opt_dataset_data(dataset_unsupervised));
  68. for (int64_t idata = 0; idata < ndata; ++idata) {
  69. data[idata] = idata;
  70. }
  71. struct ggml_context * ctx_static;
  72. struct ggml_context * ctx_compute;
  73. {
  74. struct ggml_init_params params = {
  75. /*.mem_size =*/ (2*ndata + 2)*ggml_tensor_overhead(),
  76. /*.mem_buffer =*/ nullptr,
  77. /*.no_alloc =*/ true,
  78. };
  79. ctx_static = ggml_init(params);
  80. }
  81. {
  82. struct ggml_init_params params = {
  83. /*.mem_size =*/ GGML_DEFAULT_GRAPH_SIZE*ggml_tensor_overhead() + 3*ggml_graph_overhead(),
  84. /*.mem_buffer =*/ nullptr,
  85. /*.no_alloc =*/ true,
  86. };
  87. ctx_compute = ggml_init(params);
  88. }
  89. std::vector<struct ggml_tensor *> data_batch(ndata);
  90. std::vector<struct ggml_tensor *> labels_batch(ndata);
  91. for (int64_t ndata_batch = 1; ndata_batch <= ndata; ++ndata_batch) {
  92. data_batch[ndata_batch-1] = ggml_new_tensor_1d(ctx_static, GGML_TYPE_F32, ndata_batch*ne_datapoint);
  93. labels_batch[ndata_batch-1] = ggml_new_tensor_1d(ctx_static, GGML_TYPE_F32, ndata_batch*ne_label);
  94. }
  95. struct ggml_tensor * inputs = ggml_new_tensor_1d(ctx_static, GGML_TYPE_F32, nbatch_physical);
  96. ggml_set_name(inputs, "inputs");
  97. struct ggml_tensor * weights = ggml_new_tensor_1d(ctx_static, GGML_TYPE_F32, 1);
  98. ggml_set_name(weights, "weights");
  99. ggml_set_param(ctx_static, weights);
  100. struct ggml_tensor * intermediary = ggml_add(ctx_compute, inputs, weights);
  101. struct ggml_tensor * outputs = ggml_scale(ctx_compute, intermediary, 1.0f);
  102. ggml_set_name(outputs, "outputs");
  103. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx_static, backend);
  104. const float w0 = float(ndata)/2;
  105. ggml_backend_tensor_set(weights, &w0, 0, sizeof(float));
  106. GGML_ASSERT(nbatch_logical % nbatch_physical == 0);
  107. const int32_t opt_period = nbatch_logical / nbatch_physical;
  108. struct ggml_opt_params opt_params = ggml_opt_default_params(backend_sched, ctx_compute, inputs, outputs, loss_type);
  109. opt_params.opt_period = opt_period;
  110. if (!optimizer_defaults) {
  111. opt_params.get_opt_pars = helper_get_test_opt_pars;
  112. }
  113. ggml_opt_context_t opt_ctx = init_opt_ctx ? ggml_opt_init(opt_params) : nullptr;
  114. ggml_opt_result_t result = ggml_opt_result_init();
  115. ggml_opt_result_t result2 = ggml_opt_result_init();
  116. return {datasets, data_batch, labels_batch, dataset_unsupervised, ctx_static, ctx_compute, opt_params, opt_ctx, inputs, weights, outputs, buf, result, result2};
  117. }
  118. static void helper_free_ctx_data(struct helper_ctx_data ctx_data) {
  119. ggml_opt_result_free(ctx_data.result);
  120. ggml_opt_result_free(ctx_data.result2);
  121. ggml_opt_free(ctx_data.opt_ctx);
  122. ggml_backend_buffer_free(ctx_data.buf);
  123. ggml_free(ctx_data.ctx_static);
  124. ggml_free(ctx_data.ctx_compute);
  125. for (ggml_opt_dataset_t dataset : ctx_data.datasets_supervised) {
  126. ggml_opt_dataset_free(dataset);
  127. }
  128. ggml_opt_dataset_free(ctx_data.dataset_unsupervised);
  129. }
  130. static void helper_after_test(
  131. const char * func, const bool high_level, const std::string options,
  132. const std::string subtest, const bool subtest_ok, int & ntest, int & npass) {
  133. printf(" %s(high_level=%s%s, subtest=%s): ",
  134. func, high_level ? "yes" : "no", options.c_str(), subtest.c_str());
  135. if (subtest_ok) {
  136. printf("\033[1;32mOK\033[0m\n");
  137. npass++;
  138. } else {
  139. printf("\033[1;31mFAIL\033[0m\n");
  140. }
  141. ntest++;
  142. }
  143. static std::pair<int, int> test_dataset(ggml_backend_sched_t backend_sched, ggml_backend_t backend, const bool shuffle) {
  144. int ntest = 0;
  145. int npass = 0;
  146. struct helper_ctx_data cd = helper_get_ctx_data(backend_sched, backend);
  147. for (int64_t ndata_shard = 1; ndata_shard <= ndata; ++ndata_shard) {
  148. ggml_opt_dataset_t dataset = cd.datasets_supervised[ndata_shard-1];
  149. if (shuffle) {
  150. ggml_opt_dataset_shuffle(cd.opt_ctx, dataset, -1);
  151. }
  152. for (int64_t ndata_batch = 1; ndata_batch <= ndata; ++ndata_batch) {
  153. if (ndata_batch % ndata_shard != 0) {
  154. continue;
  155. }
  156. bool subtest_ok = true;
  157. struct ggml_tensor * data_batch = cd.data_batch[ndata_batch-1];
  158. struct ggml_tensor * labels_batch = cd.labels_batch[ndata_batch-1];
  159. std::vector<float> data(ggml_nelements( data_batch));
  160. std::vector<float> labels(ggml_nelements(labels_batch));
  161. std::vector<int64_t> idata_shuffled;
  162. const int64_t nbatches = ndata / ndata_batch;
  163. for (int64_t ibatch = 0; ibatch < nbatches; ++ibatch) {
  164. ggml_opt_dataset_get_batch(dataset, data_batch, labels_batch, ibatch);
  165. ggml_backend_tensor_get( data_batch, data.data(), 0, ggml_nbytes( data_batch));
  166. ggml_backend_tensor_get(labels_batch, labels.data(), 0, ggml_nbytes(labels_batch));
  167. for (int64_t idata_batch = 0; idata_batch < ndata_batch; ++idata_batch) {
  168. const int64_t idata = ibatch*ndata_batch + idata_batch;
  169. const int64_t idata_found = data[idata_batch*ne_datapoint] / 16;
  170. subtest_ok = subtest_ok && (shuffle || idata_found == idata);
  171. idata_shuffled.push_back(idata_found);
  172. for (int64_t id = 0; id < ne_datapoint; ++id) {
  173. if (data[ idata_batch*ne_datapoint + id] != 16*idata_found + id) {
  174. subtest_ok = false;
  175. }
  176. }
  177. for (int64_t il = 0; il < ne_label; ++il) {
  178. if (labels[idata_batch*ne_label + il] != 16*(16*idata_found + il)) {
  179. subtest_ok = false;
  180. }
  181. }
  182. }
  183. }
  184. if (!shuffle || ndata % ndata_batch == 0) {
  185. const int ndata_max = (ndata / ndata_batch) * ndata_batch;
  186. for (int64_t idata = 0; subtest_ok && idata < ndata_max; ++idata) {
  187. int ninstances = 0;
  188. for (int64_t id : idata_shuffled) {
  189. ninstances += id == idata;
  190. }
  191. if (ninstances != 1) {
  192. subtest_ok = false;
  193. }
  194. }
  195. }
  196. printf(" %s(shuffle=%s, ndata_shard=%" PRId64 ", ndata_batch=%" PRId64 "): ",
  197. __func__, shuffle ? "yes" : "no", ndata_shard, ndata_batch);
  198. if (subtest_ok) {
  199. printf("\033[1;32mOK\033[0m\n");
  200. npass++;
  201. } else {
  202. printf("\033[1;31mFAIL\033[0m\n");
  203. }
  204. ntest++;
  205. }
  206. }
  207. helper_free_ctx_data(cd);
  208. return std::make_pair(npass, ntest);
  209. }
  210. static std::pair<int, int> test_grad(ggml_backend_sched_t backend_sched, ggml_backend_t backend) {
  211. int ntest = 0;
  212. int npass = 0;
  213. struct helper_ctx_data cd = helper_get_ctx_data(backend_sched, backend, /*init_opt_ctx =*/ true, /*optimizer_defaults =*/ false,
  214. /*nbatch_logical =*/ 999999, /*nbatch_physical =*/ 1);
  215. std::vector<float> grad_history(ndata);
  216. for (int64_t idata = 0; idata < ndata; ++idata) {
  217. grad_history[idata] = NAN;
  218. }
  219. for (int idata = 0; idata < ndata; ++idata) {
  220. const float idataf = idata;
  221. ggml_backend_tensor_set(cd.inputs, &idataf, 0, ggml_nbytes(cd.inputs));
  222. ggml_opt_forward_backward(cd.opt_ctx, cd.result);
  223. ggml_backend_tensor_get(ggml_opt_grad_acc(cd.opt_ctx, cd.weights), grad_history.data() + idata, 0, sizeof(float));
  224. }
  225. {
  226. bool subtest_ok = true;
  227. for (int idata = 0; idata < ndata; ++idata) {
  228. if (grad_history[idata] != idata + 1) {
  229. subtest_ok = false;
  230. }
  231. }
  232. printf(" %s(): ", __func__);
  233. if (subtest_ok) {
  234. printf("\033[1;32mOK\033[0m\n");
  235. npass++;
  236. } else {
  237. printf("\033[1;31mFAIL\033[0m\n");
  238. }
  239. ntest++;
  240. }
  241. helper_free_ctx_data(cd);
  242. return std::make_pair(npass, ntest);
  243. }
  244. static void helper_after_test_forward_backward(
  245. const char * func, const bool high_level, const bool shuffle,
  246. const std::string subtest, const bool subtest_ok, int & ntest, int & npass) {
  247. std::string options = ", shuffle=";
  248. options += shuffle ? "yes" : "no";
  249. helper_after_test(func, high_level, options, subtest, subtest_ok, ntest, npass);
  250. }
  251. static std::pair<int, int> test_forward_backward(
  252. ggml_backend_sched_t backend_sched, ggml_backend_t backend, const bool high_level, const bool shuffle) {
  253. int ntest = 0;
  254. int npass = 0;
  255. struct helper_ctx_data cd = helper_get_ctx_data(backend_sched, backend, /*init_opt_ctx =*/ true, /*optimizer_defaults =*/ false);
  256. struct ggml_tensor * loss = ggml_opt_loss(cd.opt_ctx);
  257. std::vector<float> loss_history(ndata);
  258. for (int64_t idata = 0; idata < ndata; ++idata) {
  259. loss_history[idata] = NAN;
  260. }
  261. {
  262. int64_t ndata;
  263. ggml_opt_result_ndata(cd.result, &ndata);
  264. double loss;
  265. double loss_unc;
  266. ggml_opt_result_loss(cd.result, &loss, &loss_unc);
  267. double accuracy;
  268. double accuracy_unc;
  269. ggml_opt_result_accuracy(cd.result, &accuracy, &accuracy_unc);
  270. const bool subtest_ok = ndata == 0 && loss == 0.0 && std::isnan(loss_unc) && std::isnan(accuracy) && std::isnan(accuracy_unc);
  271. helper_after_test_forward_backward(__func__, high_level, shuffle, "results_initial", subtest_ok, ntest, npass);
  272. }
  273. if (high_level) {
  274. ggml_opt_dataset_t dataset = cd.dataset_unsupervised;
  275. if (shuffle) {
  276. ggml_opt_dataset_shuffle(cd.opt_ctx, dataset, -1);
  277. }
  278. ggml_opt_epoch(cd.opt_ctx, dataset, nullptr, cd.result, 0, nullptr, nullptr);
  279. } else {
  280. for (int idata = 0; idata < ndata; ++idata) {
  281. const float idataf = idata;
  282. ggml_backend_tensor_set(cd.inputs, &idataf, 0, ggml_nbytes(cd.inputs));
  283. ggml_opt_forward(cd.opt_ctx, cd.result);
  284. ggml_backend_tensor_get(loss, loss_history.data() + idata, 0, sizeof(float));
  285. }
  286. }
  287. {
  288. float weights;
  289. ggml_backend_tensor_get(cd.weights, &weights, 0, sizeof(float));
  290. const bool subtest_ok = weights == ndata/2;
  291. helper_after_test_forward_backward(__func__, high_level, shuffle, "weights_after_forward", subtest_ok, ntest, npass);
  292. }
  293. {
  294. int64_t ndata;
  295. ggml_opt_result_ndata(cd.result, &ndata);
  296. bool subtest_ok = ndata == 6;
  297. double loss;
  298. double loss_unc;
  299. ggml_opt_result_loss(cd.result, &loss, &loss_unc);
  300. subtest_ok = subtest_ok && loss == 33.0 && almost_equal(loss_unc, sqrt(3.5), 1e-10);
  301. double accuracy;
  302. double accuracy_unc;
  303. ggml_opt_result_accuracy(cd.result, &accuracy, &accuracy_unc);
  304. subtest_ok = subtest_ok && std::isnan(accuracy) && std::isnan(accuracy_unc);
  305. helper_after_test_forward_backward(__func__, high_level, shuffle, "results_after_forward", subtest_ok, ntest, npass);
  306. }
  307. float w0;
  308. ggml_backend_tensor_get(cd.weights, &w0, 0, sizeof(float));
  309. for (int i = 0; i < 10; ++i) {
  310. ggml_opt_forward_backward(cd.opt_ctx, nullptr);
  311. }
  312. ggml_backend_tensor_set(cd.weights, &w0, 0, sizeof(float));
  313. ggml_opt_reset(cd.opt_ctx, /*optimizer =*/ false);
  314. ggml_opt_result_reset(cd.result);
  315. for (int64_t idata = 0; idata < ndata; ++idata) {
  316. loss_history[idata] = NAN;
  317. }
  318. if (high_level) {
  319. ggml_opt_dataset_t dataset = cd.dataset_unsupervised;
  320. if (shuffle) {
  321. ggml_opt_dataset_shuffle(cd.opt_ctx, dataset, -1);
  322. }
  323. ggml_opt_epoch(cd.opt_ctx, dataset, cd.result, nullptr, ndata, nullptr, nullptr);
  324. } else {
  325. for (int idata = 0; idata < ndata; ++idata) {
  326. const float idataf = idata;
  327. ggml_backend_tensor_set(cd.inputs, &idataf, 0, ggml_nbytes(cd.inputs));
  328. ggml_opt_forward_backward(cd.opt_ctx, cd.result);
  329. ggml_backend_tensor_get(loss, loss_history.data() + idata, 0, sizeof(float));
  330. }
  331. }
  332. {
  333. float weights;
  334. ggml_backend_tensor_get(cd.weights, &weights, 0, sizeof(float));
  335. const bool subtest_ok = weights == -ndata/2;
  336. helper_after_test_forward_backward(__func__, high_level, shuffle, "weights_after_forward_backward", subtest_ok, ntest, npass);
  337. }
  338. {
  339. int64_t ndata;
  340. ggml_opt_result_ndata(cd.result, &ndata);
  341. bool subtest_ok = ndata == 6;
  342. double loss;
  343. double loss_unc;
  344. ggml_opt_result_loss(cd.result, &loss, &loss_unc);
  345. subtest_ok = subtest_ok && loss == 18.0 && (shuffle || loss_unc == 0.0);
  346. double accuracy;
  347. double accuracy_unc;
  348. ggml_opt_result_accuracy(cd.result, &accuracy, &accuracy_unc);
  349. subtest_ok = subtest_ok && std::isnan(accuracy) && std::isnan(accuracy_unc);
  350. helper_after_test_forward_backward(__func__, high_level, shuffle, "result_after_forward_backward", subtest_ok, ntest, npass);
  351. }
  352. helper_free_ctx_data(cd);
  353. return std::make_pair(npass, ntest);
  354. }
  355. static std::pair<int, int> test_epoch_vs_fit(ggml_backend_sched_t backend_sched, ggml_backend_t backend) {
  356. int ntest = 0;
  357. int npass = 0;
  358. float weights_epoch;
  359. float weights_fit;
  360. {
  361. struct helper_ctx_data cd = helper_get_ctx_data(backend_sched, backend, /*init_opt_ctx =*/ true);
  362. ggml_opt_dataset_t dataset = cd.dataset_unsupervised;
  363. ggml_opt_dataset_shuffle(cd.opt_ctx, dataset, -1);
  364. ggml_opt_epoch(cd.opt_ctx, dataset, cd.result, nullptr, ndata, nullptr, nullptr);
  365. ggml_backend_tensor_get(cd.weights, &weights_epoch, 0, ggml_nbytes(cd.weights));
  366. helper_free_ctx_data(cd);
  367. }
  368. {
  369. struct helper_ctx_data cd = helper_get_ctx_data(backend_sched, backend, /*init_opt_ctx =*/ false);
  370. ggml_opt_dataset_t dataset = cd.dataset_unsupervised;
  371. ggml_opt_fit(backend_sched, cd.ctx_compute, cd.inputs, cd.outputs, dataset,
  372. GGML_OPT_LOSS_TYPE_SUM, ggml_opt_get_default_optimizer_params, 1, 1, 0.0f, true);
  373. ggml_backend_tensor_get(cd.weights, &weights_fit, 0, ggml_nbytes(cd.weights));
  374. helper_free_ctx_data(cd);
  375. }
  376. const bool subtest_ok = weights_epoch == weights_fit;
  377. printf(" %s(): ", __func__);
  378. if (subtest_ok) {
  379. printf("\033[1;32mOK\033[0m\n");
  380. npass++;
  381. } else {
  382. printf("\033[1;31mFAIL\033[0m\n");
  383. }
  384. ntest++;
  385. return std::make_pair(npass, ntest);
  386. }
  387. static void helper_after_test_idata_split(
  388. const char * func, const bool high_level, const int epoch,
  389. const std::string subtest, const bool subtest_ok, int & ntest, int & npass) {
  390. std::string options = ", epoch=";
  391. options += std::to_string(epoch);
  392. helper_after_test(func, high_level, options, subtest, subtest_ok, ntest, npass);
  393. }
  394. static std::pair<int, int> test_idata_split(ggml_backend_sched_t backend_sched, ggml_backend_t backend, const bool high_level) {
  395. int ntest = 0;
  396. int npass = 0;
  397. struct helper_ctx_data cd = helper_get_ctx_data(backend_sched, backend, /*init_opt_ctx =*/ true, /*optimizer_defaults =*/ false);
  398. struct ggml_tensor * loss = ggml_opt_loss(cd.opt_ctx);
  399. const int idata_split = ndata * 2/3;
  400. std::vector<float> loss_history(ndata);
  401. for (int64_t idata = 0; idata < ndata; ++idata) {
  402. loss_history[idata] = NAN;
  403. }
  404. for (int epoch = 1; epoch <= 4; ++epoch) {
  405. if (high_level) {
  406. ggml_opt_epoch(cd.opt_ctx, cd.dataset_unsupervised, cd.result, cd.result2, idata_split, nullptr, nullptr);
  407. } else {
  408. int idata = 0;
  409. for (; idata < idata_split; ++idata) {
  410. const float idataf = idata;
  411. ggml_backend_tensor_set(cd.inputs, &idataf, 0, ggml_nbytes(cd.inputs));
  412. ggml_opt_forward_backward(cd.opt_ctx, cd.result);
  413. ggml_backend_tensor_get(loss, loss_history.data() + idata, 0, sizeof(float));
  414. }
  415. for (; idata < ndata; ++idata) {
  416. const float idataf = idata;
  417. ggml_backend_tensor_set(cd.inputs, &idataf, 0, ggml_nbytes(cd.inputs));
  418. ggml_opt_forward(cd.opt_ctx, cd.result2);
  419. ggml_backend_tensor_get(loss, loss_history.data() + idata, 0, sizeof(float));
  420. }
  421. }
  422. {
  423. float weights;
  424. ggml_backend_tensor_get(cd.weights, &weights, 0, sizeof(float));
  425. const bool subtest_ok = weights == ndata/2 - epoch*idata_split;
  426. helper_after_test_idata_split(__func__, high_level, epoch, "weights", subtest_ok, ntest, npass);
  427. }
  428. {
  429. int64_t ndata_result;
  430. ggml_opt_result_ndata(cd.result, &ndata_result);
  431. bool subtest_ok = ndata_result == idata_split;
  432. double loss;
  433. double loss_unc;
  434. ggml_opt_result_loss(cd.result, &loss, &loss_unc);
  435. subtest_ok = subtest_ok && loss == 28.0 - epoch*16.0 && loss_unc == 0.0;
  436. double accuracy;
  437. double accuracy_unc;
  438. ggml_opt_result_accuracy(cd.result, &accuracy, &accuracy_unc);
  439. subtest_ok = subtest_ok && std::isnan(accuracy) && std::isnan(accuracy_unc);
  440. helper_after_test_idata_split(__func__, high_level, epoch, "results_backward", subtest_ok, ntest, npass);
  441. }
  442. {
  443. int64_t ndata_result;
  444. ggml_opt_result_ndata(cd.result2, &ndata_result);
  445. bool subtest_ok = ndata_result == ndata - idata_split;
  446. double loss;
  447. double loss_unc;
  448. ggml_opt_result_loss(cd.result2, &loss, &loss_unc);
  449. subtest_ok = subtest_ok && loss == 15.0 - epoch*8 && almost_equal(loss_unc, sqrt(0.5), 1e-10);
  450. double accuracy;
  451. double accuracy_unc;
  452. ggml_opt_result_accuracy(cd.result2, &accuracy, &accuracy_unc);
  453. subtest_ok = subtest_ok && std::isnan(accuracy) && std::isnan(accuracy_unc);
  454. helper_after_test_idata_split(__func__, high_level, epoch, "results_forward", subtest_ok, ntest, npass);
  455. }
  456. ggml_opt_result_reset(cd.result);
  457. ggml_opt_result_reset(cd.result2);
  458. }
  459. helper_free_ctx_data(cd);
  460. return std::make_pair(npass, ntest);
  461. }
  462. static void helper_after_test_gradient_accumulation(
  463. const char * func, const int nbatch_physical, const enum ggml_opt_loss_type loss_type, const int epoch,
  464. const std::string subtest, const bool subtest_ok, int & ntest, int & npass) {
  465. std::string options = ", nbatch_physical=";
  466. options += std::to_string(nbatch_physical);
  467. options += ", loss_type=";
  468. options += loss_type == GGML_OPT_LOSS_TYPE_MEAN ? "mean" : "sum";
  469. options += ", epoch=";
  470. options += std::to_string(epoch);
  471. helper_after_test(func, false, options, subtest, subtest_ok, ntest, npass);
  472. }
  473. static std::pair<int, int> test_gradient_accumulation(
  474. ggml_backend_sched_t backend_sched, ggml_backend_t backend, const int32_t nbatch_physical, const enum ggml_opt_loss_type loss_type) {
  475. int ntest = 0;
  476. int npass = 0;
  477. struct helper_ctx_data cd = helper_get_ctx_data(
  478. backend_sched, backend, /*init_opt_ctx =*/ true, /*optimizer_defaults =*/ false, /*nbatch_logical =*/ 6, nbatch_physical, loss_type);
  479. struct ggml_tensor * loss = ggml_opt_loss(cd.opt_ctx);
  480. std::vector<float> grad_history(ndata);
  481. for (int64_t idata = 0; idata < ndata; ++idata) {
  482. grad_history[idata] = NAN;
  483. }
  484. for (int epoch = 1; epoch <= 4; ++epoch) {
  485. if (nbatch_physical == 1) {
  486. for (int idata = 0; idata < ndata; ++idata) {
  487. const float idataf = idata;
  488. ggml_backend_tensor_set(cd.inputs, &idataf, 0, 1*sizeof(float));
  489. ggml_opt_forward_backward(cd.opt_ctx, cd.result);
  490. ggml_backend_tensor_get(ggml_opt_grad_acc(cd.opt_ctx, cd.weights), grad_history.data() + idata, 0, 1*sizeof(float));
  491. }
  492. } else if (nbatch_physical == 2) {
  493. for (int idata = 0; idata < ndata; idata += 2) {
  494. const float idataf[2] = {float(idata + 0), float(idata + 1)};
  495. ggml_backend_tensor_set(cd.inputs, idataf, 0, 2*sizeof(float));
  496. ggml_opt_forward_backward(cd.opt_ctx, cd.result);
  497. grad_history[idata + 0] = 0.0f;
  498. ggml_backend_tensor_get(ggml_opt_grad_acc(cd.opt_ctx, cd.weights), grad_history.data() + idata + 1, 0, 1*sizeof(float));
  499. }
  500. } else {
  501. GGML_ASSERT(false);
  502. }
  503. {
  504. GGML_ASSERT(ndata == 6);
  505. constexpr double atol = 1e-6;
  506. bool subtest_ok = true;
  507. if (loss_type == GGML_OPT_LOSS_TYPE_SUM) {
  508. if (nbatch_physical == 1) {
  509. subtest_ok = subtest_ok && almost_equal(grad_history[0], 1.0, atol);
  510. subtest_ok = subtest_ok && almost_equal(grad_history[2], 3.0, atol);
  511. subtest_ok = subtest_ok && almost_equal(grad_history[4], 5.0, atol);
  512. } else {
  513. subtest_ok = subtest_ok && almost_equal(grad_history[0], 0.0, atol);
  514. subtest_ok = subtest_ok && almost_equal(grad_history[2], 0.0, atol);
  515. subtest_ok = subtest_ok && almost_equal(grad_history[4], 0.0, atol);
  516. }
  517. subtest_ok = subtest_ok && almost_equal(grad_history[1], 2.0, atol);
  518. subtest_ok = subtest_ok && almost_equal(grad_history[3], 4.0, atol);
  519. subtest_ok = subtest_ok && almost_equal(grad_history[5], 0.0, atol);
  520. } else if (loss_type == GGML_OPT_LOSS_TYPE_MEAN) {
  521. if (nbatch_physical == 1) {
  522. subtest_ok = subtest_ok && almost_equal(grad_history[0], 1.0/ndata, atol);
  523. subtest_ok = subtest_ok && almost_equal(grad_history[2], 3.0/ndata, atol);
  524. subtest_ok = subtest_ok && almost_equal(grad_history[4], 5.0/ndata, atol);
  525. } else {
  526. subtest_ok = subtest_ok && almost_equal(grad_history[0], 0.0/ndata, atol);
  527. subtest_ok = subtest_ok && almost_equal(grad_history[2], 0.0/ndata, atol);
  528. subtest_ok = subtest_ok && almost_equal(grad_history[4], 0.0/ndata, atol);
  529. }
  530. subtest_ok = subtest_ok && almost_equal(grad_history[1], 2.0/ndata, atol);
  531. subtest_ok = subtest_ok && almost_equal(grad_history[3], 4.0/ndata, atol);
  532. subtest_ok = subtest_ok && almost_equal(grad_history[5], 0.0/ndata, atol);
  533. } else {
  534. GGML_ASSERT(false);
  535. }
  536. helper_after_test_gradient_accumulation(__func__, nbatch_physical, loss_type, epoch, "grads", subtest_ok, ntest, npass);
  537. }
  538. {
  539. float weights;
  540. ggml_backend_tensor_get(cd.weights, &weights, 0, sizeof(float));
  541. const bool subtest_ok = weights == (ndata/2) - epoch;
  542. helper_after_test_gradient_accumulation(__func__, nbatch_physical, loss_type, epoch, "weights", subtest_ok, ntest, npass);
  543. }
  544. {
  545. int64_t ndata_result;
  546. ggml_opt_result_ndata(cd.result, &ndata_result);
  547. bool subtest_ok = ndata_result == ndata/nbatch_physical;
  548. double loss;
  549. ggml_opt_result_loss(cd.result, &loss, /*loss_unc =*/ nullptr);
  550. if (loss_type == GGML_OPT_LOSS_TYPE_SUM) {
  551. subtest_ok = subtest_ok && loss == (39.0 - epoch*6.0);
  552. } else if (loss_type == GGML_OPT_LOSS_TYPE_MEAN) {
  553. subtest_ok = subtest_ok && almost_equal(loss, (39.0 - epoch*6.0) / ndata, 1e-6);
  554. } else {
  555. GGML_ASSERT(false);
  556. }
  557. double accuracy;
  558. double accuracy_unc;
  559. ggml_opt_result_accuracy(cd.result, &accuracy, &accuracy_unc);
  560. subtest_ok = subtest_ok && std::isnan(accuracy) && std::isnan(accuracy_unc);
  561. helper_after_test_gradient_accumulation(__func__, nbatch_physical, loss_type, epoch, "results", subtest_ok, ntest, npass);
  562. }
  563. ggml_opt_result_reset(cd.result);
  564. }
  565. helper_free_ctx_data(cd);
  566. return std::make_pair(npass, ntest);
  567. }
  568. static ggml_opt_optimizer_params helper_get_regression_opt_pars(void * userdata) {
  569. ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(userdata);
  570. result.adamw.alpha = 0.1f;
  571. return result;
  572. }
  573. static std::pair<int, int> test_regression(ggml_backend_sched_t backend_sched, ggml_backend_t backend) {
  574. int ntest = 0;
  575. int npass = 0;
  576. // Test for simple regression with f(x) = a*x + b
  577. constexpr int64_t ndata_regression = 201;
  578. constexpr float a_true = 1.2f;
  579. constexpr float b_true = 3.4f;
  580. std::mt19937 gen(12345);
  581. std::normal_distribution<float> nd{0.0f, 0.1f};
  582. ggml_opt_dataset_t dataset = ggml_opt_dataset_init(1, 1, ndata_regression, ndata_regression);
  583. float * data = ggml_get_data_f32(ggml_opt_dataset_data( dataset));
  584. float * labels = ggml_get_data_f32(ggml_opt_dataset_labels(dataset));
  585. constexpr float x_min = -100.0f;
  586. constexpr float x_max = 100.0f;
  587. for (int64_t idata = 0; idata < ndata_regression; ++idata) {
  588. const float x = x_min + (x_max - x_min) * idata/(ndata_regression-1);
  589. const float y = a_true*x + b_true + nd(gen);
  590. data[idata] = x;
  591. labels[idata] = y;
  592. }
  593. struct ggml_context * ctx_static;
  594. struct ggml_context * ctx_compute;
  595. {
  596. struct ggml_init_params params = {
  597. /*.mem_size =*/ 3*ggml_tensor_overhead(),
  598. /*.mem_buffer =*/ nullptr,
  599. /*.no_alloc =*/ true,
  600. };
  601. ctx_static = ggml_init(params);
  602. }
  603. {
  604. struct ggml_init_params params = {
  605. /*.mem_size =*/ GGML_DEFAULT_GRAPH_SIZE*ggml_tensor_overhead() + 3*ggml_graph_overhead(),
  606. /*.mem_buffer =*/ nullptr,
  607. /*.no_alloc =*/ true,
  608. };
  609. ctx_compute = ggml_init(params);
  610. }
  611. // The first dimension is the dimension of the datapoints, the second dimension is the number of datapoints.
  612. struct ggml_tensor * x = ggml_new_tensor_2d(ctx_static, GGML_TYPE_F32, 1, ndata_regression);
  613. ggml_set_name(x, "x");
  614. struct ggml_tensor * a = ggml_new_tensor_1d(ctx_static, GGML_TYPE_F32, 1);
  615. ggml_set_name(a, "a");
  616. ggml_set_param(ctx_static, a);
  617. struct ggml_tensor * b = ggml_new_tensor_1d(ctx_static, GGML_TYPE_F32, 1);
  618. ggml_set_name(b, "b");
  619. ggml_set_param(ctx_static, b);
  620. struct ggml_tensor * f = ggml_add(ctx_compute, ggml_mul(ctx_compute, x, a), b);
  621. ggml_set_name(f, "f");
  622. ggml_set_param(ctx_static, f);
  623. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx_static, backend);
  624. const float a0 = 1.0f;
  625. const float b0 = 3.0f;
  626. ggml_backend_tensor_set(a, &a0, 0, sizeof(float));
  627. ggml_backend_tensor_set(b, &b0, 0, sizeof(float));
  628. ggml_opt_fit(backend_sched, ctx_compute, x, f, dataset, GGML_OPT_LOSS_TYPE_MEAN_SQUARED_ERROR,
  629. helper_get_regression_opt_pars, 100, ndata_regression, 0.0f, true);
  630. {
  631. float a_fit;
  632. ggml_backend_tensor_get(a, &a_fit, 0, sizeof(float));
  633. float b_fit;
  634. ggml_backend_tensor_get(b, &b_fit, 0, sizeof(float));
  635. const bool subtest_ok = almost_equal(a_fit, a_true, 1e-2) && almost_equal(b_fit, b_true, 1e-2);
  636. printf(" %s(subtest=weights): ", __func__);
  637. if (subtest_ok) {
  638. printf("\033[1;32mOK\033[0m\n");
  639. npass++;
  640. } else {
  641. printf("\033[1;31mFAIL\033[0m\n");
  642. }
  643. ntest++;
  644. }
  645. ggml_backend_buffer_free(buf);
  646. ggml_free(ctx_static);
  647. ggml_opt_dataset_free(dataset);
  648. return std::make_pair(npass, ntest);
  649. }
  650. static std::pair<int, int> test_backend(ggml_backend_sched_t backend_sched, ggml_backend_t backend) {
  651. int npass = 0;
  652. int ntest = 0;
  653. for (bool shuffle : {false, true}) {
  654. std::pair<int, int> partial = test_dataset(backend_sched, backend, shuffle);
  655. npass += partial.first;
  656. ntest += partial.second;
  657. }
  658. {
  659. std::pair<int, int> partial = test_grad(backend_sched, backend);
  660. npass += partial.first;
  661. ntest += partial.second;
  662. }
  663. for (bool high_level : {false, true}){
  664. for (bool shuffle : {false, true}) {
  665. if (!high_level && shuffle) {
  666. continue;
  667. }
  668. std::pair<int, int> partial = test_forward_backward(backend_sched, backend, high_level, shuffle);
  669. npass += partial.first;
  670. ntest += partial.second;
  671. }
  672. }
  673. {
  674. std::pair<int, int> partial = test_epoch_vs_fit(backend_sched, backend);
  675. npass += partial.first;
  676. ntest += partial.second;
  677. }
  678. for (bool high_level : {false, true}){
  679. std::pair<int, int> partial = test_idata_split(backend_sched, backend, high_level);
  680. npass += partial.first;
  681. ntest += partial.second;
  682. }
  683. for (int32_t nbatch_physical : {2, 1}) {
  684. for (enum ggml_opt_loss_type loss_type : {GGML_OPT_LOSS_TYPE_SUM, GGML_OPT_LOSS_TYPE_MEAN}) {
  685. std::pair<int, int> partial = test_gradient_accumulation(backend_sched, backend, nbatch_physical, loss_type);
  686. npass += partial.first;
  687. ntest += partial.second;
  688. }
  689. }
  690. {
  691. std::pair<int, int> partial = test_regression(backend_sched, backend);
  692. npass += partial.first;
  693. ntest += partial.second;
  694. }
  695. return std::make_pair(npass, ntest);
  696. }
  697. int main(void) {
  698. const size_t dev_count = ggml_backend_dev_count();
  699. printf("Testing %zu devices\n\n", dev_count);
  700. size_t n_ok = 0;
  701. std::vector<ggml_backend_dev_t> devs;
  702. std::vector<ggml_backend_t> backends;
  703. for (size_t i = 0; i < dev_count; ++i) {
  704. devs.push_back(ggml_backend_dev_get(i));
  705. ggml_backend_t backend = ggml_backend_dev_init(devs[i], NULL);
  706. GGML_ASSERT(backend != NULL);
  707. if (ggml_backend_is_cpu(backend)) {
  708. ggml_backend_cpu_set_n_threads(backend, std::thread::hardware_concurrency() / 2);
  709. }
  710. backends.push_back(backend);
  711. }
  712. for (size_t i = 0; i < dev_count; ++i) {
  713. // Put the backend to be tested in front so that it's prioritized:
  714. std::vector<ggml_backend_t> backends_modded = {backends[i]};
  715. backends_modded.insert(backends_modded.end(), backends.begin(), backends.end());
  716. ggml_backend_sched_t backend_sched = ggml_backend_sched_new(
  717. backends_modded.data(), nullptr, backends_modded.size(), GGML_DEFAULT_GRAPH_SIZE, false);
  718. printf("Backend %zu/%zu: %s\n", i + 1, dev_count, ggml_backend_dev_name(devs[i]));
  719. printf(" Device description: %s\n", ggml_backend_dev_description(devs[i]));
  720. size_t free, total; // NOLINT
  721. ggml_backend_dev_memory(devs[i], &free, &total);
  722. printf(" Device memory: %zu MB (%zu MB free)\n", total / 1024 / 1024, free / 1024 / 1024);
  723. printf("\n");
  724. std::pair<int, int> result = test_backend(backend_sched, backends[i]);
  725. printf(" %d/%d tests passed\n", result.first, result.second);
  726. printf(" Backend %s: ", ggml_backend_name(backends[i]));
  727. if (result.first == result.second) {
  728. printf("\033[1;32mOK\033[0m\n");
  729. n_ok++;
  730. } else {
  731. printf("\033[1;31mFAIL\033[0m\n");
  732. }
  733. printf("\n");
  734. ggml_backend_sched_free(backend_sched);
  735. }
  736. for (ggml_backend_t backend : backends) {
  737. ggml_backend_free(backend);
  738. }
  739. printf("%zu/%zu backends passed\n", n_ok, dev_count);
  740. if (n_ok != dev_count) {
  741. printf("\033[1;31mFAIL\033[0m\n");
  742. return 1;
  743. }
  744. printf("\033[1;32mOK\033[0m\n");
  745. return 0;
  746. }