test-opt.cpp 38 KB

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