ggml-opt.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. #include "ggml-opt.h"
  2. #include "ggml.h"
  3. #include "ggml-alloc.h"
  4. #include "ggml-backend.h"
  5. #include "ggml-impl.h"
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <cstdint>
  9. #include <cinttypes>
  10. #include <map>
  11. #include <random>
  12. #include <vector>
  13. struct ggml_opt_dataset {
  14. struct ggml_context * ctx = nullptr;
  15. ggml_backend_buffer_t buf = nullptr;
  16. struct ggml_tensor * data = nullptr;
  17. struct ggml_tensor * labels = nullptr;
  18. int64_t ndata = -1;
  19. int64_t ndata_shard = -1;
  20. size_t nbs_data = -1;
  21. size_t nbs_labels = -1;
  22. std::vector<int64_t> permutation;
  23. };
  24. struct ggml_opt_context {
  25. ggml_backend_sched_t backend_sched = nullptr;
  26. ggml_cgraph * allocated_graph = nullptr;
  27. ggml_cgraph * allocated_graph_copy = nullptr;
  28. struct ggml_context * ctx_static = nullptr;
  29. struct ggml_context * ctx_static_cpu = nullptr;
  30. struct ggml_context * ctx_compute = nullptr;
  31. struct ggml_context * ctx_copy = nullptr;
  32. ggml_backend_buffer_t buf_static = nullptr;
  33. ggml_backend_buffer_t buf_static_cpu = nullptr;
  34. std::mt19937 rng;
  35. struct ggml_tensor * inputs = nullptr;
  36. struct ggml_tensor * outputs = nullptr;
  37. struct ggml_tensor * labels = nullptr;
  38. struct ggml_tensor * loss = nullptr;
  39. struct ggml_tensor * pred = nullptr;
  40. struct ggml_tensor * ncorrect = nullptr;
  41. struct ggml_cgraph * gf = nullptr;
  42. struct ggml_cgraph * gb_grad = nullptr;
  43. struct ggml_cgraph * gb_opt = nullptr;
  44. int64_t iter = 1;
  45. int32_t opt_period = 1;
  46. int32_t opt_i = 0;
  47. bool loss_per_datapoint = false;
  48. ggml_opt_get_optimizer_params get_opt_pars = nullptr;
  49. void * get_opt_pars_ud = nullptr;
  50. struct ggml_tensor * adamw_params = nullptr;
  51. };
  52. struct ggml_opt_result {
  53. int64_t ndata = 0;
  54. std::vector<float> loss;
  55. std::vector<int32_t> pred;
  56. int64_t ncorrect = 0;
  57. int64_t opt_period = -1;
  58. bool loss_per_datapoint = false;
  59. };
  60. // ====== Dataset ======
  61. ggml_opt_dataset_t ggml_opt_dataset_init(int64_t ne_datapoint, int64_t ne_label, int64_t ndata, int64_t ndata_shard) {
  62. GGML_ASSERT(ne_datapoint > 0);
  63. GGML_ASSERT(ne_label >= 0);
  64. GGML_ASSERT(ndata > 0);
  65. GGML_ASSERT(ndata_shard > 0);
  66. ggml_opt_dataset_t result = new ggml_opt_dataset;
  67. result->ndata = ndata;
  68. result->ndata_shard = ndata_shard;
  69. {
  70. struct ggml_init_params params = {
  71. /*.mem_size =*/ 2*ggml_tensor_overhead(),
  72. /*.mem_buffer =*/ nullptr,
  73. /*.no_alloc =*/ true,
  74. };
  75. result->ctx = ggml_init(params);
  76. }
  77. result->data = ggml_new_tensor_2d(result->ctx, GGML_TYPE_F32, ne_datapoint, ndata);
  78. result->nbs_data = ggml_nbytes(result->data) * ndata_shard/ndata;
  79. if (ne_label > 0) {
  80. result->labels = ggml_new_tensor_2d(result->ctx, GGML_TYPE_F32, ne_label, ndata);
  81. result->nbs_labels = ggml_nbytes(result->labels) * ndata_shard/ndata;
  82. } else {
  83. result->labels = nullptr;
  84. result->nbs_labels = 0;
  85. }
  86. result->buf = ggml_backend_alloc_ctx_tensors_from_buft(result->ctx, ggml_backend_cpu_buffer_type());
  87. const int64_t nshards = ndata/ndata_shard;
  88. result->permutation.resize(nshards);
  89. for (int64_t i = 0; i < nshards; ++i) {
  90. result->permutation[i] = i;
  91. }
  92. return result;
  93. }
  94. void ggml_opt_dataset_free(ggml_opt_dataset_t dataset) {
  95. ggml_backend_buffer_free(dataset->buf);
  96. ggml_free(dataset->ctx);
  97. delete dataset;
  98. }
  99. struct ggml_tensor * ggml_opt_dataset_data(ggml_opt_dataset_t dataset) {
  100. return dataset->data;
  101. }
  102. struct ggml_tensor * ggml_opt_dataset_labels(ggml_opt_dataset_t dataset) {
  103. return dataset->labels;
  104. }
  105. void ggml_opt_dataset_shuffle(ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, int64_t idata) {
  106. GGML_ASSERT(idata <= dataset->ndata);
  107. if (idata < 0) {
  108. std::shuffle(dataset->permutation.begin(), dataset->permutation.end(), opt_ctx->rng);
  109. return;
  110. }
  111. GGML_ASSERT(idata % dataset->ndata_shard == 0);
  112. const int64_t ishard_max = idata / dataset->ndata_shard;
  113. std::shuffle(dataset->permutation.begin(), dataset->permutation.begin() + ishard_max, opt_ctx->rng);
  114. }
  115. void ggml_opt_dataset_get_batch(ggml_opt_dataset_t dataset, struct ggml_tensor * data_batch, struct ggml_tensor * labels_batch, int64_t ibatch) {
  116. GGML_ASSERT( data_batch && ggml_is_contiguous(data_batch));
  117. GGML_ASSERT(!labels_batch || ggml_is_contiguous(labels_batch));
  118. GGML_ASSERT((labels_batch == nullptr) == (dataset->labels == nullptr));
  119. const size_t nb_data_batch = ggml_nbytes(data_batch);
  120. GGML_ASSERT(nb_data_batch % dataset->nbs_data == 0);
  121. const int64_t shards_per_batch = nb_data_batch / dataset->nbs_data;
  122. if (labels_batch) {
  123. const size_t nb_labels_batch = ggml_nbytes(labels_batch);
  124. GGML_ASSERT(nb_labels_batch == shards_per_batch*dataset->nbs_labels);
  125. }
  126. GGML_ASSERT((ibatch + 1)*shards_per_batch <= int64_t(dataset->permutation.size()));
  127. for (int64_t ishard_batch = 0; ishard_batch < shards_per_batch; ++ishard_batch) {
  128. const int64_t ishard = dataset->permutation[ibatch*shards_per_batch + ishard_batch];
  129. const char * ptr_data = (const char *) dataset->data->data + ishard*dataset->nbs_data;
  130. ggml_backend_tensor_set(data_batch, ptr_data, ishard_batch*dataset->nbs_data, dataset->nbs_data);
  131. if (!labels_batch) {
  132. continue;
  133. }
  134. const char * ptr_labels = (const char *) dataset->labels->data + ishard*dataset->nbs_labels;
  135. ggml_backend_tensor_set(labels_batch, ptr_labels, ishard_batch*dataset->nbs_labels, dataset->nbs_labels);
  136. }
  137. }
  138. // ====== Model / Context ======
  139. struct ggml_opt_optimizer_params ggml_opt_get_default_optimizer_params(void * userdata) {
  140. GGML_UNUSED(userdata);
  141. ggml_opt_optimizer_params result;
  142. result.adamw.alpha = 0.001f;
  143. result.adamw.beta1 = 0.9f;
  144. result.adamw.beta2 = 0.999f;
  145. result.adamw.eps = 1e-8f;
  146. result.adamw.wd = 0.0f;
  147. return result;
  148. }
  149. struct ggml_opt_params ggml_opt_default_params(
  150. ggml_backend_sched_t backend_sched,
  151. struct ggml_context * ctx_compute,
  152. struct ggml_tensor * inputs,
  153. struct ggml_tensor * outputs,
  154. enum ggml_opt_loss_type loss_type) {
  155. return {
  156. /*backend_sched =*/ backend_sched,
  157. /*ctx_compute =*/ ctx_compute,
  158. /*inputs =*/ inputs,
  159. /*logits =*/ outputs,
  160. /*loss_type =*/ loss_type,
  161. /*build_type =*/ GGML_OPT_BUILD_TYPE_OPT,
  162. /*opt_period =*/ 1,
  163. /*get_opt_pars =*/ ggml_opt_get_default_optimizer_params,
  164. /*get_opt_pars_ud =*/ nullptr,
  165. };
  166. }
  167. static ggml_tensor * map_tensor(std::map<ggml_tensor *, ggml_tensor *> & tensor_map, ggml_context * ctx, ggml_tensor * tensor) {
  168. if (!tensor) {
  169. return nullptr;
  170. }
  171. if (tensor_map.find(tensor) != tensor_map.end()) {
  172. return tensor_map[tensor];
  173. }
  174. ggml_tensor * new_tensor = ggml_dup_tensor(ctx, tensor);
  175. tensor_map[tensor] = new_tensor;
  176. new_tensor->op = tensor->op;
  177. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  178. new_tensor->nb[i] = tensor->nb[i];
  179. }
  180. new_tensor->flags = tensor->flags;
  181. memcpy(new_tensor->op_params, tensor->op_params, sizeof(tensor->op_params));
  182. strcpy(new_tensor->name, tensor->name);
  183. new_tensor->data = tensor->data;
  184. new_tensor->buffer = tensor->buffer;
  185. new_tensor->extra = tensor->extra;
  186. new_tensor->view_offs = tensor->view_offs;
  187. new_tensor->view_src = map_tensor(tensor_map, ctx, tensor->view_src);
  188. for (int i = 0; i < GGML_MAX_SRC; i++) {
  189. new_tensor->src[i] = map_tensor(tensor_map, ctx, tensor->src[i]);
  190. }
  191. return new_tensor;
  192. }
  193. static ggml_cgraph * dup_graph(ggml_context * ctx, ggml_cgraph * src) {
  194. std::map<ggml_tensor *, ggml_tensor *> tensor_map;
  195. ggml_cgraph * dst = ggml_new_graph_custom(ctx, src->size, /*grads =*/ true);
  196. for (int i = 0; i < src->n_leafs; i++) {
  197. ggml_build_forward_expand(dst, map_tensor(tensor_map, ctx, src->leafs[i]));
  198. }
  199. GGML_ASSERT(dst->n_leafs == src->n_leafs);
  200. for (int i = 0; i < src->n_nodes; i++) {
  201. ggml_build_forward_expand(dst, map_tensor(tensor_map, ctx, src->nodes[i]));
  202. }
  203. GGML_ASSERT(dst->n_nodes == src->n_nodes);
  204. for (int i = 0; i < src->n_nodes; ++i) {
  205. const size_t igrad_src = ggml_hash_find(&src->visited_hash_set, src->nodes[i]);
  206. const size_t igrad_dst = ggml_hash_find(&dst->visited_hash_set, dst->nodes[i]);
  207. GGML_ASSERT(igrad_src != GGML_HASHSET_FULL);
  208. GGML_ASSERT(ggml_bitset_get(src->visited_hash_set.used, igrad_src));
  209. GGML_ASSERT(igrad_dst != GGML_HASHSET_FULL);
  210. GGML_ASSERT(ggml_bitset_get(dst->visited_hash_set.used, igrad_dst));
  211. dst->grads[igrad_dst] = src->grads[igrad_src];
  212. dst->grad_accs[igrad_dst] = src->grad_accs[igrad_src];
  213. }
  214. return dst;
  215. }
  216. static void ggml_opt_alloc_graph(ggml_opt_context_t opt_ctx, ggml_cgraph * graph) {
  217. GGML_ASSERT(graph);
  218. if (opt_ctx->allocated_graph == graph) {
  219. return;
  220. }
  221. ggml_backend_sched_reset(opt_ctx->backend_sched); // clear allocation of previous graph
  222. {
  223. ggml_init_params params = {
  224. /*.mem_size =*/ ggml_tensor_overhead() * GGML_DEFAULT_GRAPH_SIZE,
  225. /*.mem_buffer =*/ nullptr,
  226. /*.no_alloc =*/ true,
  227. };
  228. ggml_free(opt_ctx->ctx_copy);
  229. opt_ctx->ctx_copy = ggml_init(params);
  230. }
  231. opt_ctx->allocated_graph_copy = dup_graph(opt_ctx->ctx_copy, graph);
  232. ggml_backend_sched_alloc_graph(opt_ctx->backend_sched, opt_ctx->allocated_graph_copy);
  233. opt_ctx->allocated_graph = graph;
  234. }
  235. ggml_opt_context_t ggml_opt_init(struct ggml_opt_params params) {
  236. ggml_opt_context_t result = new struct ggml_opt_context;
  237. result->backend_sched = params.backend_sched;
  238. result->ctx_compute = params.ctx_compute;
  239. result->inputs = params.inputs;
  240. result->outputs = params.outputs;
  241. result->opt_period = params.opt_period;
  242. result->get_opt_pars = params.get_opt_pars;
  243. result->get_opt_pars_ud = params.get_opt_pars_ud;
  244. GGML_ASSERT(result->inputs->data && "the inputs must be allocated statically");
  245. GGML_ASSERT(result->opt_period >= 1);
  246. const bool accumulate = params.build_type == GGML_OPT_BUILD_TYPE_GRAD ||
  247. (params.build_type == GGML_OPT_BUILD_TYPE_OPT && result->opt_period > 1);
  248. ggml_set_input(result->inputs);
  249. ggml_set_output(result->outputs);
  250. result->gf = ggml_new_graph_custom(result->ctx_compute, GGML_DEFAULT_GRAPH_SIZE, /*grads =*/ true); // Forward pass.
  251. ggml_build_forward_expand(result->gf, result->outputs);
  252. int n_param = 0;
  253. for (int i = 0; i < result->gf->n_nodes; ++i) {
  254. if (result->gf->nodes[i]->flags & GGML_TENSOR_FLAG_PARAM) {
  255. n_param++;
  256. }
  257. }
  258. {
  259. // The static context is used for:
  260. // - gradients (1 tensor per param if using gradient accumulation)
  261. // - optimizer momenta (2 tensors per param)
  262. // - labels
  263. // - loss + its gradient (up to 5 tensors)
  264. // - pred
  265. // - ncorrect (2 tensors).
  266. const size_t tensors_per_param = (accumulate ? 1 : 0) + (params.build_type == GGML_OPT_BUILD_TYPE_OPT ? 2 : 0);
  267. const size_t size_meta = (tensors_per_param*n_param + 9) * ggml_tensor_overhead();
  268. struct ggml_init_params params = {
  269. /*.mem_size =*/ size_meta,
  270. /*.mem_buffer =*/ nullptr,
  271. /*.no_alloc =*/ true,
  272. };
  273. result->ctx_static = ggml_init(params);
  274. }
  275. {
  276. // The static cpu context is used for:
  277. // - optimizer parameters (1 for the entire context)
  278. const size_t size_meta = 1 * ggml_tensor_overhead();
  279. struct ggml_init_params params = {
  280. /*.mem_size =*/ size_meta,
  281. /*.mem_buffer =*/ nullptr,
  282. /*.no_alloc =*/ true,
  283. };
  284. result->ctx_static_cpu = ggml_init(params);
  285. }
  286. switch (params.loss_type) {
  287. case GGML_OPT_LOSS_TYPE_MEAN: {
  288. result->loss = ggml_sum(result->ctx_static, result->outputs);
  289. ggml_set_name(result->loss, "loss_sum");
  290. const float scale = 1.0f / (result->opt_period * ggml_nelements(result->outputs));
  291. result->loss = ggml_scale(result->ctx_static, result->loss, scale);
  292. ggml_set_name(result->loss, "loss_mean");
  293. result->loss_per_datapoint = true;
  294. break;
  295. }
  296. case GGML_OPT_LOSS_TYPE_SUM: {
  297. result->loss = ggml_sum(result->ctx_static, result->outputs);
  298. ggml_set_name(result->loss, "loss_sum");
  299. result->loss_per_datapoint = false;
  300. break;
  301. }
  302. case GGML_OPT_LOSS_TYPE_CROSS_ENTROPY: {
  303. result->labels = ggml_dup_tensor(result->ctx_static, result->outputs);
  304. ggml_set_input(result->labels);
  305. ggml_set_name(result->labels, "labels");
  306. result->loss = ggml_cross_entropy_loss(result->ctx_static, result->outputs, result->labels);
  307. ggml_set_name(result->loss, "loss_cross_entropy");
  308. if (result->opt_period > 1) {
  309. result->loss = ggml_scale(result->ctx_static, result->loss, 1.0f / result->opt_period);
  310. ggml_set_name(result->loss, "loss_cross_entropy_scaled");
  311. }
  312. result->loss_per_datapoint = true;
  313. break;
  314. }
  315. case GGML_OPT_LOSS_TYPE_MEAN_SQUARED_ERROR: {
  316. result->labels = ggml_dup_tensor(result->ctx_static, result->outputs);
  317. ggml_set_input(result->labels);
  318. ggml_set_name(result->labels, "labels");
  319. result->loss = ggml_sub(result->ctx_static, result->outputs, result->labels);
  320. ggml_set_name(result->loss, "loss_error");
  321. result->loss = ggml_sqr(result->ctx_static, result->loss);
  322. ggml_set_name(result->loss, "loss_squared_error");
  323. result->loss = ggml_sum(result->ctx_static, result->loss);
  324. ggml_set_name(result->loss, "loss_sum_squared_error");
  325. const float scale = 1.0f / (result->opt_period * ggml_nelements(result->outputs));
  326. result->loss = ggml_scale(result->ctx_static, result->loss, scale);
  327. ggml_set_name(result->loss, "loss_mean_squared_error");
  328. result->loss_per_datapoint = true;
  329. break;
  330. }
  331. }
  332. ggml_set_output(result->loss);
  333. ggml_set_loss(result->loss);
  334. ggml_build_forward_expand(result->gf, result->loss);
  335. result->pred = ggml_argmax(result->ctx_static, result->outputs);
  336. ggml_set_name(result->pred, "pred");
  337. ggml_set_output(result->pred);
  338. ggml_build_forward_expand(result->gf, result->pred);
  339. if (result->labels) {
  340. result->ncorrect = ggml_count_equal(result->ctx_static, result->pred, ggml_argmax(result->ctx_static, result->labels));
  341. ggml_set_name(result->ncorrect, "ncorrect");
  342. ggml_set_output(result->ncorrect);
  343. ggml_build_forward_expand(result->gf, result->ncorrect);
  344. } else {
  345. result->ncorrect = nullptr;
  346. }
  347. if (params.build_type == GGML_OPT_BUILD_TYPE_FORWARD) {
  348. result->buf_static = ggml_backend_alloc_ctx_tensors(result->ctx_static, ggml_backend_sched_get_backend(result->backend_sched, 0));
  349. return result;
  350. }
  351. // gb_grad == graph backward gradients, forward pass, then backward pass to calculate gradients.
  352. result->gb_grad = ggml_graph_dup(result->ctx_compute, result->gf);
  353. ggml_build_backward_expand(result->ctx_static, result->ctx_compute, result->gb_grad, accumulate);
  354. if (params.build_type == GGML_OPT_BUILD_TYPE_GRAD) {
  355. result->buf_static = ggml_backend_alloc_ctx_tensors(result->ctx_static, ggml_backend_sched_get_backend(result->backend_sched, 0));
  356. ggml_graph_reset(result->gb_grad);
  357. return result;
  358. }
  359. GGML_ASSERT(params.build_type == GGML_OPT_BUILD_TYPE_OPT);
  360. // gb_opt == graph backward optimize, forward pass, then backward pass to calculate gradients, then optimizer step.
  361. result->gb_opt = ggml_graph_dup(result->ctx_compute, result->gb_grad);
  362. result->adamw_params = ggml_new_tensor_1d(result->ctx_static_cpu, GGML_TYPE_F32, 7);
  363. ggml_set_input(result->adamw_params);
  364. ggml_set_name(result->adamw_params, "adamw_params");
  365. for (int i = result->gf->n_nodes-1; i >= 0; --i) {
  366. struct ggml_tensor * node = result->gb_opt->nodes[i];
  367. struct ggml_tensor * grad = ggml_graph_get_grad(result->gb_opt, node);
  368. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  369. struct ggml_tensor * m = ggml_dup_tensor(result->ctx_static, node);
  370. struct ggml_tensor * v = ggml_dup_tensor(result->ctx_static, node);
  371. struct ggml_tensor * opt_step = ggml_opt_step_adamw(result->ctx_compute, node, grad, m, v, result->adamw_params);
  372. ggml_build_forward_expand(result->gb_opt, opt_step);
  373. }
  374. }
  375. result->buf_static = ggml_backend_alloc_ctx_tensors(
  376. result->ctx_static, ggml_backend_sched_get_backend(result->backend_sched, 0));
  377. result->buf_static_cpu = ggml_backend_alloc_ctx_tensors_from_buft(result->ctx_static_cpu, ggml_backend_cpu_buffer_type());
  378. ggml_graph_reset(result->gb_opt);
  379. return result;
  380. }
  381. void ggml_opt_free(ggml_opt_context_t opt_ctx) {
  382. if (opt_ctx == nullptr) {
  383. return;
  384. }
  385. ggml_backend_buffer_free(opt_ctx->buf_static);
  386. ggml_backend_buffer_free(opt_ctx->buf_static_cpu);
  387. ggml_free(opt_ctx->ctx_static);
  388. ggml_free(opt_ctx->ctx_static_cpu);
  389. delete opt_ctx;
  390. }
  391. void ggml_opt_reset(ggml_opt_context_t opt_ctx, bool optimizer) {
  392. if (optimizer) {
  393. ggml_graph_reset(opt_ctx->gb_opt);
  394. opt_ctx->iter = 1;
  395. } else {
  396. ggml_graph_reset(opt_ctx->gb_grad);
  397. }
  398. }
  399. struct ggml_tensor * ggml_opt_inputs(ggml_opt_context_t opt_ctx) {
  400. return opt_ctx->inputs;
  401. }
  402. struct ggml_tensor * ggml_opt_outputs(ggml_opt_context_t opt_ctx) {
  403. return opt_ctx->outputs;
  404. }
  405. struct ggml_tensor * ggml_opt_labels(ggml_opt_context_t opt_ctx) {
  406. return opt_ctx->labels;
  407. }
  408. struct ggml_tensor * ggml_opt_loss(ggml_opt_context_t opt_ctx) {
  409. return opt_ctx->loss;
  410. }
  411. struct ggml_tensor * ggml_opt_pred(ggml_opt_context_t opt_ctx) {
  412. return opt_ctx->pred;
  413. }
  414. struct ggml_tensor * ggml_opt_ncorrect(ggml_opt_context_t opt_ctx) {
  415. return opt_ctx->ncorrect;
  416. }
  417. struct ggml_tensor * ggml_opt_grad_acc(ggml_opt_context_t opt_ctx, struct ggml_tensor * node) {
  418. return ggml_graph_get_grad_acc(opt_ctx->gb_opt, node);
  419. }
  420. // ====== Optimization Result ======
  421. ggml_opt_result_t ggml_opt_result_init() {
  422. return new ggml_opt_result;
  423. }
  424. void ggml_opt_result_free(ggml_opt_result_t result) {
  425. delete result;
  426. }
  427. void ggml_opt_result_reset(ggml_opt_result_t result) {
  428. result->ndata = 0;
  429. result->loss.clear();
  430. result->pred.clear();
  431. result->ncorrect = 0;
  432. }
  433. void ggml_opt_result_ndata(ggml_opt_result_t result, int64_t * ndata) {
  434. *ndata = result->ndata;
  435. }
  436. void ggml_opt_result_loss(ggml_opt_result_t result, double * loss, double * unc) {
  437. const int64_t nbatches = result->loss.size(); // Number of physical batches.
  438. if (nbatches == 0) {
  439. *loss = 0.0;
  440. *unc = NAN;
  441. return;
  442. }
  443. double sum = 0.0;
  444. double sum_squared = 0.0;
  445. for (const float & loss : result->loss) {
  446. // If the loss is per datapoint it was scaled by 1.0f/opt_period for each physical batch.
  447. const float loss_scaled = result->loss_per_datapoint ? loss*result->opt_period : loss;
  448. sum += loss_scaled;
  449. sum_squared += loss_scaled*loss_scaled;
  450. }
  451. const double mean = sum/nbatches;
  452. *loss = result->loss_per_datapoint ? mean : sum;
  453. if (!unc) {
  454. return;
  455. }
  456. if (nbatches < 2) {
  457. *unc = NAN;
  458. return;
  459. }
  460. const double var_sum = sum_squared/nbatches - mean*mean; // variance without Bessel's correction, i.e. nbatches/(nbatches-1)
  461. *unc = result->loss_per_datapoint ? sqrt(var_sum / (nbatches - 1)) : sqrt(var_sum * nbatches/(nbatches - 1));
  462. }
  463. void ggml_opt_result_pred(ggml_opt_result_t result, int32_t * pred) {
  464. for (size_t i = 0; i < result->pred.size(); ++i) {
  465. pred[i] = result->pred[i];
  466. }
  467. }
  468. void ggml_opt_result_accuracy(ggml_opt_result_t result, double * accuracy, double * unc) {
  469. *accuracy = result->ncorrect >= 0 ? double(result->ncorrect) / double(result->ndata) : NAN;
  470. if (!unc) {
  471. return;
  472. }
  473. *unc = result->ncorrect >= 0 && result->ndata >= 2 ?
  474. sqrt((*accuracy) * (1.0 - (*accuracy)) / double(result->ndata - 1)) : NAN;
  475. }
  476. // ====== Computation ======
  477. static void ggml_opt_eval_graph(ggml_opt_context_t opt_ctx, ggml_cgraph * graph, ggml_opt_result * result) {
  478. if (graph != opt_ctx->gf) {
  479. struct ggml_opt_optimizer_params opt_pars = opt_ctx->get_opt_pars(opt_ctx->get_opt_pars_ud);
  480. GGML_ASSERT(opt_pars.adamw.alpha > 0.0f);
  481. GGML_ASSERT(opt_pars.adamw.beta1 >= 0.0f);
  482. GGML_ASSERT(opt_pars.adamw.beta1 <= 1.0f);
  483. GGML_ASSERT(opt_pars.adamw.beta2 >= 0.0f);
  484. GGML_ASSERT(opt_pars.adamw.beta2 <= 1.0f);
  485. GGML_ASSERT(opt_pars.adamw.eps >= 0.0f);
  486. GGML_ASSERT(opt_pars.adamw.wd >= 0.0f);
  487. GGML_ASSERT(opt_pars.adamw.wd <= 1.0f);
  488. // beta1, beta2 after applying warmup
  489. const float beta1h = 1.0f/(1.0f - powf(opt_pars.adamw.beta1, opt_ctx->iter));
  490. const float beta2h = 1.0f/(1.0f - powf(opt_pars.adamw.beta2, opt_ctx->iter));
  491. float * adamw_par_data = ggml_get_data_f32(opt_ctx->adamw_params);
  492. adamw_par_data[0] = opt_pars.adamw.alpha;
  493. adamw_par_data[1] = opt_pars.adamw.beta1;
  494. adamw_par_data[2] = opt_pars.adamw.beta2;
  495. adamw_par_data[3] = opt_pars.adamw.eps;
  496. adamw_par_data[4] = opt_pars.adamw.wd;
  497. adamw_par_data[5] = beta1h;
  498. adamw_par_data[6] = beta2h;
  499. }
  500. ggml_opt_alloc_graph(opt_ctx, graph);
  501. ggml_backend_sched_graph_compute(opt_ctx->backend_sched, opt_ctx->allocated_graph_copy);
  502. opt_ctx->iter += opt_ctx->allocated_graph == opt_ctx->gb_opt;
  503. if (!result) {
  504. return;
  505. }
  506. if (result->ndata == 0) {
  507. result->loss_per_datapoint = opt_ctx->loss_per_datapoint;
  508. result->opt_period = opt_ctx->opt_period;
  509. } else {
  510. GGML_ASSERT(result->loss_per_datapoint == opt_ctx->loss_per_datapoint);
  511. GGML_ASSERT(result->opt_period == opt_ctx->opt_period);
  512. }
  513. const int64_t ndata = opt_ctx->outputs->ne[1];
  514. GGML_ASSERT(result->ndata == ndata*int64_t(result->loss.size()) && "varying batch size not supported");
  515. result->ndata += ndata;
  516. GGML_ASSERT(ggml_is_scalar(opt_ctx->loss));
  517. GGML_ASSERT(opt_ctx->loss->type == GGML_TYPE_F32);
  518. float loss;
  519. ggml_backend_tensor_get(opt_ctx->loss, &loss, 0, ggml_nbytes(opt_ctx->loss));
  520. result->loss.push_back(loss);
  521. GGML_ASSERT(opt_ctx->pred->type == GGML_TYPE_I32);
  522. std::vector<int32_t> pred(ndata);
  523. ggml_backend_tensor_get(opt_ctx->pred, pred.data(), 0, ggml_nbytes(opt_ctx->pred));
  524. result->pred.insert(result->pred.end(), pred.begin(), pred.end());
  525. if (!opt_ctx->labels || result->ncorrect < 0) {
  526. result->ncorrect = -1;
  527. return;
  528. }
  529. GGML_ASSERT(ggml_is_scalar(opt_ctx->ncorrect));
  530. GGML_ASSERT(opt_ctx->ncorrect->type == GGML_TYPE_I64);
  531. int64_t ncorrect;
  532. ggml_backend_tensor_get(opt_ctx->ncorrect, &ncorrect, 0, ggml_nbytes(opt_ctx->ncorrect));
  533. result->ncorrect += ncorrect;
  534. }
  535. void ggml_opt_forward(ggml_opt_context_t opt_ctx, ggml_opt_result * result) {
  536. ggml_opt_eval_graph(opt_ctx, opt_ctx->gf, result);
  537. }
  538. void ggml_opt_forward_backward(ggml_opt_context_t opt_ctx, ggml_opt_result * result) {
  539. if (opt_ctx->opt_period == 1) {
  540. ggml_opt_eval_graph(opt_ctx, opt_ctx->gb_opt, result);
  541. return;
  542. }
  543. const int32_t opt_i_next = (opt_ctx->opt_i + 1) % opt_ctx->opt_period;
  544. if (opt_i_next == 0) {
  545. ggml_opt_eval_graph(opt_ctx, opt_ctx->gb_opt, result);
  546. ggml_opt_reset(opt_ctx, /*optimizer =*/ false);
  547. } else {
  548. ggml_opt_eval_graph(opt_ctx, opt_ctx->gb_grad, result);
  549. }
  550. opt_ctx->opt_i = opt_i_next;
  551. }
  552. // ====== High-Level Functions ======
  553. void ggml_opt_epoch(
  554. ggml_opt_context_t opt_ctx,
  555. ggml_opt_dataset_t dataset,
  556. ggml_opt_result_t result_train,
  557. ggml_opt_result_t result_eval,
  558. int64_t idata_split,
  559. ggml_opt_epoch_callback callback_train,
  560. ggml_opt_epoch_callback callback_eval) {
  561. struct ggml_tensor * inputs = ggml_opt_inputs(opt_ctx);
  562. struct ggml_tensor * labels = ggml_opt_labels(opt_ctx);
  563. struct ggml_tensor * data = ggml_opt_dataset_data(dataset);
  564. GGML_ASSERT(data->ne[0] == inputs->ne[0]);
  565. const int64_t ndata = data->ne[1];
  566. const int64_t ndata_batch = inputs->ne[1];
  567. GGML_ASSERT(data->ne[1] % inputs->ne[1] == 0);
  568. const int64_t nbatches = ndata/ndata_batch;
  569. idata_split = idata_split < 0 ? ndata : idata_split;
  570. GGML_ASSERT(idata_split % ndata_batch == 0);
  571. const int64_t ibatch_split = idata_split / ndata_batch;
  572. int64_t ibatch = 0;
  573. int64_t t_loop_start = ggml_time_us();
  574. for (; ibatch < ibatch_split; ++ibatch) {
  575. ggml_opt_dataset_get_batch(dataset, inputs, labels, ibatch);
  576. ggml_opt_forward_backward(opt_ctx, result_train);
  577. if (callback_train) {
  578. callback_train(true, opt_ctx, dataset, result_train, ibatch+1, ibatch_split, t_loop_start);
  579. }
  580. }
  581. t_loop_start = ggml_time_us();
  582. for (; ibatch < nbatches; ++ibatch) {
  583. ggml_opt_dataset_get_batch(dataset, inputs, labels, ibatch);
  584. ggml_opt_forward(opt_ctx, result_eval);
  585. if (callback_eval) {
  586. callback_eval(false, opt_ctx, dataset, result_eval, ibatch+1-ibatch_split, nbatches-ibatch_split, t_loop_start);
  587. }
  588. }
  589. }
  590. void ggml_opt_epoch_callback_progress_bar(
  591. bool train,
  592. ggml_opt_context_t opt_ctx,
  593. ggml_opt_dataset_t dataset,
  594. ggml_opt_result_t result,
  595. int64_t ibatch,
  596. int64_t ibatch_max,
  597. int64_t t_start_us) {
  598. fprintf(stderr, "%s[", train ? "train: " : "val: ");
  599. constexpr int64_t bar_length = 25;
  600. for (int64_t j = 0; j < bar_length; ++j) {
  601. const int64_t ibatch_j = ibatch_max * j/bar_length;
  602. if (ibatch_j < ibatch) {
  603. fprintf(stderr, "=");
  604. } else if (ibatch_max * (j - 1)/bar_length < ibatch) {
  605. fprintf(stderr, ">");
  606. } else {
  607. fprintf(stderr, " ");
  608. }
  609. }
  610. const int64_t batch_size = ggml_opt_inputs(opt_ctx)->ne[1];
  611. const int64_t idata = ibatch*batch_size;
  612. const int64_t idata_max = ibatch_max*batch_size;
  613. double loss;
  614. double loss_unc;
  615. ggml_opt_result_loss(result, &loss, &loss_unc);
  616. double accuracy;
  617. double accuracy_unc;
  618. ggml_opt_result_accuracy(result, &accuracy, &accuracy_unc);
  619. const int64_t t_ibatch_us = ggml_time_us() - t_start_us;
  620. int64_t t_ibatch_s = t_ibatch_us / 1000000;
  621. const int64_t t_ibatch_h = t_ibatch_s / 3600;
  622. t_ibatch_s -= t_ibatch_h * 3600;
  623. const int64_t t_ibatch_m = t_ibatch_s / 60;
  624. t_ibatch_s -= t_ibatch_m * 60;
  625. const int64_t t_eta_us = t_ibatch_us * (ibatch_max - ibatch)/ibatch;
  626. int64_t t_eta_s = t_eta_us / 1000000;
  627. const int64_t t_eta_h = t_eta_s / 3600;
  628. t_eta_s -= t_eta_h * 3600;
  629. const int64_t t_eta_m = t_eta_s / 60;
  630. t_eta_s -= t_eta_m * 60;
  631. fprintf(stderr, "| data=%06" PRId64 "/%06" PRId64 ", loss=%.6lf+-%.6lf, accuracy=%.2lf+-%.2lf%%, "
  632. "t=%02" PRId64 ":%02" PRId64 ":%02" PRId64 ", ETA=%02" PRId64 ":%02" PRId64 ":%02" PRId64 "]\r",
  633. idata, idata_max, loss, loss_unc, 100.0*accuracy, 100.0*accuracy_unc,
  634. t_ibatch_h, t_ibatch_m, t_ibatch_s, t_eta_h, t_eta_m, t_eta_s);
  635. if (ibatch == ibatch_max) {
  636. fprintf(stderr, "\n");
  637. }
  638. fflush(stderr);
  639. GGML_UNUSED(dataset);
  640. }
  641. void ggml_opt_fit(
  642. ggml_backend_sched_t backend_sched,
  643. ggml_context * ctx_compute,
  644. ggml_tensor * inputs,
  645. ggml_tensor * outputs,
  646. ggml_opt_dataset_t dataset,
  647. enum ggml_opt_loss_type loss_type,
  648. ggml_opt_get_optimizer_params get_opt_pars,
  649. int64_t nepoch,
  650. int64_t nbatch_logical,
  651. float val_split,
  652. bool silent) {
  653. ggml_time_init();
  654. const int64_t t_start_us = ggml_time_us();
  655. const int64_t ndata = ggml_opt_dataset_data(dataset)->ne[1];
  656. const int64_t nbatch_physical = inputs->ne[1];
  657. GGML_ASSERT(ndata % nbatch_logical == 0);
  658. GGML_ASSERT(nbatch_logical % nbatch_physical == 0);
  659. const int64_t opt_period = nbatch_logical / nbatch_physical;
  660. const int64_t nbatches_logical = ndata / nbatch_logical;
  661. GGML_ASSERT(val_split >= 0.0f);
  662. GGML_ASSERT(val_split < 1.0f);
  663. const int64_t ibatch_split = int64_t(((1.0f - val_split) * nbatches_logical)) * opt_period; // train <-> val split index (physical)
  664. const int64_t idata_split = ibatch_split * nbatch_physical;
  665. int64_t epoch = 1;
  666. ggml_opt_params params = ggml_opt_default_params(backend_sched, ctx_compute, inputs, outputs, loss_type);
  667. params.opt_period = opt_period;
  668. params.get_opt_pars = get_opt_pars;
  669. params.get_opt_pars_ud = &epoch;
  670. ggml_opt_context_t opt_ctx = ggml_opt_init(params);
  671. // Shuffling the data is generally useful but there is only a point if not all data is used in a single batch.
  672. if (nbatch_logical < ndata) {
  673. ggml_opt_dataset_shuffle(opt_ctx, dataset, -1); // Shuffle all data (train + validation).
  674. }
  675. ggml_opt_result_t result_train = ggml_opt_result_init();
  676. ggml_opt_result_t result_val = ggml_opt_result_init();
  677. ggml_opt_epoch_callback epoch_callback = silent ? nullptr : ggml_opt_epoch_callback_progress_bar;
  678. for (; epoch <= nepoch; ++epoch) {
  679. if (nbatch_logical < idata_split) {
  680. ggml_opt_dataset_shuffle(opt_ctx, dataset, idata_split);
  681. }
  682. ggml_opt_result_reset(result_train);
  683. ggml_opt_result_reset(result_val);
  684. if (!silent) {
  685. fprintf(stderr, "%s: epoch %04" PRId64 "/%04" PRId64 ":\n", __func__, epoch, nepoch);
  686. }
  687. ggml_opt_epoch(opt_ctx, dataset, result_train, result_val, idata_split, epoch_callback, epoch_callback);
  688. if (!silent) {
  689. fprintf(stderr, "\n");
  690. }
  691. }
  692. if (!silent) {
  693. int64_t t_total_s = (ggml_time_us() - t_start_us) / 1000000;
  694. const int64_t t_total_h = t_total_s / 3600;
  695. t_total_s -= t_total_h * 3600;
  696. const int64_t t_total_m = t_total_s / 60;
  697. t_total_s -= t_total_m * 60;
  698. fprintf(stderr, "%s: training took %02" PRId64 ":%02" PRId64 ":%02" PRId64 "\n", __func__, t_total_h, t_total_m, t_total_s);
  699. }
  700. ggml_opt_free(opt_ctx);
  701. ggml_opt_result_free(result_train);
  702. ggml_opt_result_free(result_val);
  703. }