ggml-opt.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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_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_cpu = nullptr;
  34. std::mt19937 rng;
  35. enum ggml_opt_loss_type loss_type;
  36. enum ggml_opt_build_type build_type;
  37. enum ggml_opt_build_type build_type_alloc;
  38. struct ggml_tensor * inputs = nullptr;
  39. struct ggml_tensor * outputs = nullptr;
  40. struct ggml_tensor * labels = nullptr;
  41. struct ggml_tensor * loss = nullptr;
  42. struct ggml_tensor * pred = nullptr;
  43. struct ggml_tensor * ncorrect = nullptr;
  44. struct ggml_cgraph * gf = nullptr;
  45. struct ggml_cgraph * gb_grad = nullptr;
  46. struct ggml_cgraph * gb_opt = nullptr;
  47. bool static_graphs = false;
  48. bool eval_ready = false;
  49. std::vector<struct ggml_tensor *> grad_accs;
  50. std::vector<struct ggml_tensor *> grad_m;
  51. std::vector<struct ggml_tensor *> grad_v;
  52. int64_t iter = 1;
  53. int32_t opt_period = 1;
  54. int32_t opt_i = 0;
  55. bool loss_per_datapoint = false;
  56. ggml_opt_get_optimizer_params get_opt_pars = nullptr;
  57. void * get_opt_pars_ud = nullptr;
  58. struct ggml_tensor * adamw_params = nullptr;
  59. };
  60. struct ggml_opt_result {
  61. int64_t ndata = 0;
  62. std::vector<float> loss;
  63. std::vector<int32_t> pred;
  64. int64_t ncorrect = 0;
  65. int64_t opt_period = -1;
  66. bool loss_per_datapoint = false;
  67. };
  68. // ====== Dataset ======
  69. ggml_opt_dataset_t ggml_opt_dataset_init(
  70. enum ggml_type type_data,
  71. enum ggml_type type_label,
  72. int64_t ne_datapoint,
  73. int64_t ne_label,
  74. int64_t ndata,
  75. int64_t ndata_shard) {
  76. GGML_ASSERT(ne_datapoint > 0);
  77. GGML_ASSERT(ne_label >= 0);
  78. GGML_ASSERT(ndata > 0);
  79. GGML_ASSERT(ndata_shard > 0);
  80. ggml_opt_dataset_t result = new ggml_opt_dataset;
  81. result->ndata = ndata;
  82. result->ndata_shard = ndata_shard;
  83. {
  84. struct ggml_init_params params = {
  85. /*.mem_size =*/ 2*ggml_tensor_overhead(),
  86. /*.mem_buffer =*/ nullptr,
  87. /*.no_alloc =*/ true,
  88. };
  89. result->ctx = ggml_init(params);
  90. }
  91. result->data = ggml_new_tensor_2d(result->ctx, type_data, ne_datapoint, ndata);
  92. result->nbs_data = ggml_nbytes(result->data) * ndata_shard/ndata;
  93. if (ne_label > 0) {
  94. result->labels = ggml_new_tensor_2d(result->ctx, type_label, ne_label, ndata);
  95. result->nbs_labels = ggml_nbytes(result->labels) * ndata_shard/ndata;
  96. } else {
  97. result->labels = nullptr;
  98. result->nbs_labels = 0;
  99. }
  100. result->buf = ggml_backend_alloc_ctx_tensors_from_buft(result->ctx, ggml_backend_cpu_buffer_type());
  101. const int64_t nshards = ndata/ndata_shard;
  102. result->permutation.resize(nshards);
  103. for (int64_t i = 0; i < nshards; ++i) {
  104. result->permutation[i] = i;
  105. }
  106. return result;
  107. }
  108. void ggml_opt_dataset_free(ggml_opt_dataset_t dataset) {
  109. ggml_backend_buffer_free(dataset->buf);
  110. ggml_free(dataset->ctx);
  111. delete dataset;
  112. }
  113. int64_t ggml_opt_dataset_ndata(ggml_opt_dataset_t dataset) {
  114. return dataset->ndata;
  115. }
  116. struct ggml_tensor * ggml_opt_dataset_data(ggml_opt_dataset_t dataset) {
  117. return dataset->data;
  118. }
  119. struct ggml_tensor * ggml_opt_dataset_labels(ggml_opt_dataset_t dataset) {
  120. return dataset->labels;
  121. }
  122. void ggml_opt_dataset_shuffle(ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, int64_t idata) {
  123. GGML_ASSERT(idata <= dataset->ndata);
  124. if (idata < 0) {
  125. std::shuffle(dataset->permutation.begin(), dataset->permutation.end(), opt_ctx->rng);
  126. return;
  127. }
  128. GGML_ASSERT(idata % dataset->ndata_shard == 0);
  129. const int64_t ishard_max = idata / dataset->ndata_shard;
  130. std::shuffle(dataset->permutation.begin(), dataset->permutation.begin() + ishard_max, opt_ctx->rng);
  131. }
  132. void ggml_opt_dataset_get_batch(ggml_opt_dataset_t dataset, struct ggml_tensor * data_batch, struct ggml_tensor * labels_batch, int64_t ibatch) {
  133. GGML_ASSERT( data_batch && ggml_is_contiguous(data_batch));
  134. GGML_ASSERT(!labels_batch || ggml_is_contiguous(labels_batch));
  135. GGML_ASSERT((labels_batch == nullptr) == (dataset->labels == nullptr));
  136. GGML_ASSERT( data_batch->type == dataset->data->type);
  137. GGML_ASSERT(!labels_batch || labels_batch->type == dataset->labels->type);
  138. const size_t nb_data_batch = ggml_nbytes(data_batch);
  139. GGML_ASSERT(nb_data_batch % dataset->nbs_data == 0);
  140. const int64_t shards_per_batch = nb_data_batch / dataset->nbs_data;
  141. if (labels_batch) {
  142. const size_t nb_labels_batch = ggml_nbytes(labels_batch);
  143. GGML_ASSERT(nb_labels_batch == shards_per_batch*dataset->nbs_labels);
  144. }
  145. GGML_ASSERT((ibatch + 1)*shards_per_batch <= int64_t(dataset->permutation.size()));
  146. for (int64_t ishard_batch = 0; ishard_batch < shards_per_batch; ++ishard_batch) {
  147. const int64_t ishard = dataset->permutation[ibatch*shards_per_batch + ishard_batch];
  148. const char * ptr_data = (const char *) dataset->data->data + ishard*dataset->nbs_data;
  149. ggml_backend_tensor_set(data_batch, ptr_data, ishard_batch*dataset->nbs_data, dataset->nbs_data);
  150. if (!labels_batch) {
  151. continue;
  152. }
  153. const char * ptr_labels = (const char *) dataset->labels->data + ishard*dataset->nbs_labels;
  154. ggml_backend_tensor_set(labels_batch, ptr_labels, ishard_batch*dataset->nbs_labels, dataset->nbs_labels);
  155. }
  156. }
  157. void ggml_opt_dataset_get_batch_host(ggml_opt_dataset_t dataset, void * data_batch, size_t nb_data_batch, void * labels_batch, int64_t ibatch) {
  158. GGML_ASSERT((labels_batch == nullptr) == (dataset->labels == nullptr));
  159. GGML_ASSERT(nb_data_batch % dataset->nbs_data == 0);
  160. const int64_t shards_per_batch = nb_data_batch / dataset->nbs_data;
  161. GGML_ASSERT((ibatch + 1)*shards_per_batch <= int64_t(dataset->permutation.size()));
  162. for (int64_t ishard_batch = 0; ishard_batch < shards_per_batch; ++ishard_batch) {
  163. const int64_t ishard = dataset->permutation[ibatch*shards_per_batch + ishard_batch];
  164. const char * ptr_data = (const char *) dataset->data->data + ishard *dataset->nbs_data;
  165. char * ptr_data_batch = (char *) data_batch + ishard_batch*dataset->nbs_data;
  166. memcpy(ptr_data_batch, ptr_data, dataset->nbs_data);
  167. if (!labels_batch) {
  168. continue;
  169. }
  170. const char * ptr_labels = (const char *) dataset->labels->data + ishard *dataset->nbs_labels;
  171. char * ptr_labels_batch = (char *) labels_batch + ishard_batch*dataset->nbs_labels;
  172. memcpy(ptr_labels_batch, ptr_labels, dataset->nbs_labels);
  173. }
  174. }
  175. // ====== Model / Context ======
  176. struct ggml_opt_optimizer_params ggml_opt_get_default_optimizer_params(void * userdata) {
  177. GGML_UNUSED(userdata);
  178. ggml_opt_optimizer_params result;
  179. result.adamw.alpha = 0.001f;
  180. result.adamw.beta1 = 0.9f;
  181. result.adamw.beta2 = 0.999f;
  182. result.adamw.eps = 1e-8f;
  183. result.adamw.wd = 0.0f;
  184. return result;
  185. }
  186. struct ggml_opt_optimizer_params ggml_opt_get_constant_optimizer_params(void * userdata) {
  187. return *((struct ggml_opt_optimizer_params *) userdata);
  188. }
  189. struct ggml_opt_params ggml_opt_default_params(
  190. ggml_backend_sched_t backend_sched,
  191. enum ggml_opt_loss_type loss_type) {
  192. return {
  193. /*backend_sched =*/ backend_sched,
  194. /*ctx_compute =*/ nullptr,
  195. /*inputs =*/ nullptr,
  196. /*logits =*/ nullptr,
  197. /*loss_type =*/ loss_type,
  198. /*build_type =*/ GGML_OPT_BUILD_TYPE_OPT,
  199. /*opt_period =*/ 1,
  200. /*get_opt_pars =*/ ggml_opt_get_default_optimizer_params,
  201. /*get_opt_pars_ud =*/ nullptr,
  202. };
  203. }
  204. static ggml_tensor * map_tensor(std::map<ggml_tensor *, ggml_tensor *> & tensor_map, ggml_context * ctx, ggml_tensor * tensor) {
  205. if (!tensor) {
  206. return nullptr;
  207. }
  208. if (tensor_map.find(tensor) != tensor_map.end()) {
  209. return tensor_map[tensor];
  210. }
  211. ggml_tensor * new_tensor = ggml_dup_tensor(ctx, tensor);
  212. tensor_map[tensor] = new_tensor;
  213. new_tensor->op = tensor->op;
  214. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  215. new_tensor->nb[i] = tensor->nb[i];
  216. }
  217. new_tensor->flags = tensor->flags;
  218. memcpy(new_tensor->op_params, tensor->op_params, sizeof(tensor->op_params));
  219. strcpy(new_tensor->name, tensor->name);
  220. new_tensor->data = tensor->data;
  221. new_tensor->buffer = tensor->buffer;
  222. new_tensor->extra = tensor->extra;
  223. new_tensor->view_offs = tensor->view_offs;
  224. new_tensor->view_src = map_tensor(tensor_map, ctx, tensor->view_src);
  225. for (int i = 0; i < GGML_MAX_SRC; i++) {
  226. new_tensor->src[i] = map_tensor(tensor_map, ctx, tensor->src[i]);
  227. }
  228. return new_tensor;
  229. }
  230. static ggml_cgraph * dup_graph(ggml_context * ctx, ggml_cgraph * src) {
  231. std::map<ggml_tensor *, ggml_tensor *> tensor_map;
  232. ggml_cgraph * dst = ggml_new_graph_custom(ctx, src->size, /*grads =*/ true);
  233. for (int i = 0; i < src->n_leafs; i++) {
  234. ggml_build_forward_expand(dst, map_tensor(tensor_map, ctx, src->leafs[i]));
  235. }
  236. GGML_ASSERT(dst->n_leafs == src->n_leafs);
  237. for (int i = 0; i < src->n_nodes; i++) {
  238. ggml_build_forward_expand(dst, map_tensor(tensor_map, ctx, src->nodes[i]));
  239. }
  240. GGML_ASSERT(dst->n_nodes == src->n_nodes);
  241. for (int i = 0; i < src->n_nodes; ++i) {
  242. const size_t igrad_src = ggml_hash_find(&src->visited_hash_set, src->nodes[i]);
  243. const size_t igrad_dst = ggml_hash_find(&dst->visited_hash_set, dst->nodes[i]);
  244. GGML_ASSERT(igrad_src != GGML_HASHSET_FULL);
  245. GGML_ASSERT(ggml_bitset_get(src->visited_hash_set.used, igrad_src));
  246. GGML_ASSERT(igrad_dst != GGML_HASHSET_FULL);
  247. GGML_ASSERT(ggml_bitset_get(dst->visited_hash_set.used, igrad_dst));
  248. dst->grads[igrad_dst] = src->grads[igrad_src];
  249. dst->grad_accs[igrad_dst] = src->grad_accs[igrad_src];
  250. }
  251. return dst;
  252. }
  253. static void ggml_opt_build(ggml_opt_context_t opt_ctx) {
  254. GGML_ASSERT(opt_ctx->ctx_compute && "no compute context set, either use static graphs or set one with ggml_opt_prepare_alloc");
  255. GGML_ASSERT((!opt_ctx->static_graphs || opt_ctx->inputs->data) && "when using static graphs the inputs must be allocated statically");
  256. const bool accumulate = opt_ctx->build_type_alloc >= GGML_OPT_BUILD_TYPE_GRAD &&
  257. !(opt_ctx->static_graphs && opt_ctx->build_type_alloc == GGML_OPT_BUILD_TYPE_OPT && opt_ctx->opt_period == 1);
  258. ggml_set_input(opt_ctx->inputs);
  259. ggml_set_output(opt_ctx->outputs);
  260. int n_param = 0;
  261. for (int i = 0; i < opt_ctx->gf->n_nodes; ++i) {
  262. const struct ggml_tensor * node = opt_ctx->gf->nodes[i];
  263. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  264. n_param++;
  265. }
  266. GGML_ASSERT(!(node->flags & GGML_TENSOR_FLAG_LOSS) && "support for extra loss terms not implemented");
  267. }
  268. if (!opt_ctx->ctx_static) {
  269. // The static context is used for:
  270. // - gradients (1 per loss, 1 tensor per param if using gradient accumulation)
  271. // - optimizer momenta (2 tensors per param)
  272. // - labels (if using static graphs)
  273. // - loss (if using static graphs, up to 5 tensors)
  274. // - pred (if using static graphs)
  275. // - ncorrect (if using static graphs, 2 tensors).
  276. constexpr size_t n_loss = 1;
  277. const size_t tensors_per_param = (accumulate ? 1 : 0) +
  278. (opt_ctx->build_type_alloc == GGML_OPT_BUILD_TYPE_OPT ? 2 : 0);
  279. const size_t tensors_const = opt_ctx->static_graphs ? 9 : 0;
  280. const size_t size_meta = (n_loss + tensors_per_param*n_param + tensors_const) * ggml_tensor_overhead();
  281. struct ggml_init_params params = {
  282. /*.mem_size =*/ size_meta,
  283. /*.mem_buffer =*/ nullptr,
  284. /*.no_alloc =*/ true,
  285. };
  286. opt_ctx->ctx_static = ggml_init(params);
  287. }
  288. GGML_ASSERT(opt_ctx->build_type <= opt_ctx->build_type_alloc);
  289. {
  290. // The cpu context is allocated statically if using static graphs, dynamically otherwise.
  291. // It is used for:
  292. // - optimizer parameters (1 shared for all optimizer invocations)
  293. const size_t size_meta = 1 * ggml_tensor_overhead();
  294. struct ggml_init_params params = {
  295. /*.mem_size =*/ size_meta,
  296. /*.mem_buffer =*/ nullptr,
  297. /*.no_alloc =*/ true,
  298. };
  299. ggml_free(opt_ctx->ctx_cpu);
  300. opt_ctx->ctx_cpu = ggml_init(params);
  301. ggml_backend_buffer_free(opt_ctx->buf_cpu);
  302. opt_ctx->buf_cpu = nullptr;
  303. }
  304. struct ggml_context * ctx_results = opt_ctx->static_graphs ? opt_ctx->ctx_static : opt_ctx->ctx_compute;
  305. switch (opt_ctx->loss_type) {
  306. case GGML_OPT_LOSS_TYPE_MEAN: {
  307. opt_ctx->loss = ggml_sum(ctx_results, opt_ctx->outputs);
  308. ggml_set_name(opt_ctx->loss, "loss_sum");
  309. const float scale = 1.0f / (opt_ctx->opt_period * ggml_nelements(opt_ctx->outputs));
  310. opt_ctx->loss = ggml_scale(ctx_results, opt_ctx->loss, scale);
  311. ggml_set_name(opt_ctx->loss, "loss_mean");
  312. opt_ctx->loss_per_datapoint = true;
  313. break;
  314. }
  315. case GGML_OPT_LOSS_TYPE_SUM: {
  316. opt_ctx->loss = ggml_sum(ctx_results, opt_ctx->outputs);
  317. ggml_set_name(opt_ctx->loss, "loss_sum");
  318. opt_ctx->loss_per_datapoint = false;
  319. break;
  320. }
  321. case GGML_OPT_LOSS_TYPE_CROSS_ENTROPY: {
  322. opt_ctx->labels = ggml_dup_tensor(ctx_results, opt_ctx->outputs);
  323. ggml_set_input(opt_ctx->labels);
  324. ggml_set_name(opt_ctx->labels, "labels");
  325. opt_ctx->loss = ggml_cross_entropy_loss(ctx_results, opt_ctx->outputs, opt_ctx->labels);
  326. ggml_set_name(opt_ctx->loss, "loss_cross_entropy");
  327. if (opt_ctx->opt_period > 1) {
  328. opt_ctx->loss = ggml_scale(ctx_results, opt_ctx->loss, 1.0f / opt_ctx->opt_period);
  329. ggml_set_name(opt_ctx->loss, "loss_cross_entropy_scaled");
  330. }
  331. opt_ctx->loss_per_datapoint = true;
  332. break;
  333. }
  334. case GGML_OPT_LOSS_TYPE_MEAN_SQUARED_ERROR: {
  335. opt_ctx->labels = ggml_dup_tensor(ctx_results, opt_ctx->outputs);
  336. ggml_set_input(opt_ctx->labels);
  337. ggml_set_name(opt_ctx->labels, "labels");
  338. opt_ctx->loss = ggml_sub(ctx_results, opt_ctx->outputs, opt_ctx->labels);
  339. ggml_set_name(opt_ctx->loss, "loss_error");
  340. opt_ctx->loss = ggml_sqr(ctx_results, opt_ctx->loss);
  341. ggml_set_name(opt_ctx->loss, "loss_squared_error");
  342. opt_ctx->loss = ggml_sum(ctx_results, opt_ctx->loss);
  343. ggml_set_name(opt_ctx->loss, "loss_sum_squared_error");
  344. const float scale = 1.0f / (opt_ctx->opt_period * ggml_nelements(opt_ctx->outputs));
  345. opt_ctx->loss = ggml_scale(ctx_results, opt_ctx->loss, scale);
  346. ggml_set_name(opt_ctx->loss, "loss_mean_squared_error");
  347. opt_ctx->loss_per_datapoint = true;
  348. break;
  349. }
  350. }
  351. ggml_set_output(opt_ctx->loss);
  352. ggml_set_loss(opt_ctx->loss);
  353. ggml_build_forward_expand(opt_ctx->gf, opt_ctx->loss);
  354. if (opt_ctx->loss_type == GGML_OPT_LOSS_TYPE_CROSS_ENTROPY) {
  355. opt_ctx->pred = ggml_argmax(ctx_results, opt_ctx->outputs);
  356. ggml_set_name(opt_ctx->pred, "pred");
  357. ggml_set_output(opt_ctx->pred);
  358. ggml_build_forward_expand(opt_ctx->gf, opt_ctx->pred);
  359. opt_ctx->ncorrect = ggml_count_equal(ctx_results, opt_ctx->pred, ggml_argmax(ctx_results, opt_ctx->labels));
  360. ggml_set_name(opt_ctx->ncorrect, "ncorrect");
  361. ggml_set_output(opt_ctx->ncorrect);
  362. ggml_build_forward_expand(opt_ctx->gf, opt_ctx->ncorrect);
  363. }
  364. if (opt_ctx->buf_static) {
  365. if (opt_ctx->build_type == GGML_OPT_BUILD_TYPE_FORWARD) {
  366. return;
  367. }
  368. } else if (opt_ctx->build_type_alloc == GGML_OPT_BUILD_TYPE_FORWARD) {
  369. opt_ctx->buf_static = ggml_backend_alloc_ctx_tensors(
  370. opt_ctx->ctx_static, ggml_backend_sched_get_backend(opt_ctx->backend_sched, 0));
  371. return;
  372. }
  373. if (opt_ctx->grad_accs.empty()) {
  374. GGML_ASSERT(opt_ctx->build_type_alloc >= GGML_OPT_BUILD_TYPE_GRAD);
  375. const int n_nodes = opt_ctx->gf->n_nodes;
  376. opt_ctx->grad_accs.resize(n_nodes);
  377. for (int i = 0; i < n_nodes; ++i) {
  378. ggml_tensor * node = opt_ctx->gf->nodes[i];
  379. if ((accumulate && (node->flags & GGML_TENSOR_FLAG_PARAM)) || (node->flags & GGML_TENSOR_FLAG_LOSS)) {
  380. opt_ctx->grad_accs[i] = ggml_new_tensor(opt_ctx->ctx_static, GGML_TYPE_F32, GGML_MAX_DIMS, node->ne);
  381. } else {
  382. opt_ctx->grad_accs[i] = nullptr;
  383. }
  384. }
  385. if (opt_ctx->build_type_alloc >= GGML_OPT_BUILD_TYPE_OPT) {
  386. opt_ctx->grad_m.resize(n_nodes);
  387. opt_ctx->grad_v.resize(n_nodes);
  388. for (int i = 0; i < n_nodes; ++i) {
  389. ggml_tensor * node = opt_ctx->gf->nodes[i];
  390. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  391. opt_ctx->grad_m[i] = ggml_new_tensor(opt_ctx->ctx_static, GGML_TYPE_F32, GGML_MAX_DIMS, node->ne);
  392. opt_ctx->grad_v[i] = ggml_new_tensor(opt_ctx->ctx_static, GGML_TYPE_F32, GGML_MAX_DIMS, node->ne);
  393. } else {
  394. opt_ctx->grad_m[i] = nullptr;
  395. opt_ctx->grad_v[i] = nullptr;
  396. }
  397. }
  398. }
  399. }
  400. // gb_grad == graph backward gradients, forward pass, then backward pass to calculate gradients.
  401. opt_ctx->gb_grad = ggml_graph_dup(opt_ctx->ctx_compute, opt_ctx->gf, /*force_grads =*/ true);
  402. ggml_build_backward_expand(opt_ctx->ctx_compute, opt_ctx->gb_grad, opt_ctx->grad_accs.data());
  403. if (opt_ctx->buf_static) {
  404. if (opt_ctx->build_type == GGML_OPT_BUILD_TYPE_GRAD) {
  405. return;
  406. }
  407. } else if (opt_ctx->build_type_alloc == GGML_OPT_BUILD_TYPE_GRAD) {
  408. opt_ctx->buf_static = ggml_backend_alloc_ctx_tensors(opt_ctx->ctx_static, ggml_backend_sched_get_backend(opt_ctx->backend_sched, 0));
  409. ggml_graph_reset(opt_ctx->gb_grad);
  410. }
  411. GGML_ASSERT(opt_ctx->build_type_alloc == GGML_OPT_BUILD_TYPE_OPT);
  412. // gb_opt == graph backward optimize, forward pass, then backward pass to calculate gradients, then optimizer step.
  413. opt_ctx->gb_opt = ggml_graph_dup(opt_ctx->ctx_compute, opt_ctx->gb_grad, /*force_grads =*/ true);
  414. opt_ctx->adamw_params = ggml_new_tensor_1d(opt_ctx->ctx_cpu, GGML_TYPE_F32, 7);
  415. ggml_set_input(opt_ctx->adamw_params);
  416. ggml_set_name(opt_ctx->adamw_params, "adamw_params");
  417. for (int i = opt_ctx->gf->n_nodes-1; i >= 0; --i) {
  418. struct ggml_tensor * node = opt_ctx->gb_opt->nodes[i];
  419. struct ggml_tensor * grad = ggml_graph_get_grad(opt_ctx->gb_opt, node);
  420. if (grad && (node->flags & GGML_TENSOR_FLAG_PARAM)) {
  421. struct ggml_tensor * m = opt_ctx->grad_m[i];
  422. struct ggml_tensor * v = opt_ctx->grad_v[i];
  423. struct ggml_tensor * opt_step = ggml_opt_step_adamw(opt_ctx->ctx_compute, node, grad, m, v, opt_ctx->adamw_params);
  424. ggml_set_name(m, (std::string("AdamW m for ") + std::string(node->name)).c_str());
  425. ggml_set_name(v, (std::string("AdamW v for ") + std::string(node->name)).c_str());
  426. ggml_set_name(opt_step, (std::string("AdamW step for ") + std::string(node->name)).c_str());
  427. ggml_build_forward_expand(opt_ctx->gb_opt, opt_step);
  428. }
  429. }
  430. if (!opt_ctx->buf_static) {
  431. opt_ctx->buf_static = ggml_backend_alloc_ctx_tensors(
  432. opt_ctx->ctx_static, ggml_backend_sched_get_backend(opt_ctx->backend_sched, 0));
  433. ggml_graph_reset(opt_ctx->gb_opt);
  434. }
  435. opt_ctx->buf_cpu = ggml_backend_alloc_ctx_tensors_from_buft(opt_ctx->ctx_cpu, ggml_backend_cpu_buffer_type());
  436. }
  437. ggml_opt_context_t ggml_opt_init(struct ggml_opt_params params) {
  438. ggml_opt_context_t result = new struct ggml_opt_context;
  439. result->backend_sched = params.backend_sched;
  440. result->ctx_compute = params.ctx_compute;
  441. result->loss_type = params.loss_type;
  442. result->build_type = params.build_type;
  443. result->build_type_alloc = params.build_type;
  444. result->inputs = params.inputs;
  445. result->outputs = params.outputs;
  446. result->opt_period = params.opt_period;
  447. result->get_opt_pars = params.get_opt_pars;
  448. result->get_opt_pars_ud = params.get_opt_pars_ud;
  449. GGML_ASSERT(result->opt_period >= 1);
  450. result->static_graphs = result->ctx_compute;
  451. if (!result->static_graphs) {
  452. GGML_ASSERT(!result->inputs);
  453. GGML_ASSERT(!result->outputs);
  454. return result;
  455. }
  456. GGML_ASSERT(result->inputs);
  457. GGML_ASSERT(result->outputs);
  458. result->gf = ggml_new_graph_custom(result->ctx_compute, GGML_DEFAULT_GRAPH_SIZE, /*grads =*/ true); // Forward pass.
  459. ggml_build_forward_expand(result->gf, result->outputs);
  460. ggml_opt_build(result);
  461. return result;
  462. }
  463. void ggml_opt_free(ggml_opt_context_t opt_ctx) {
  464. if (opt_ctx == nullptr) {
  465. return;
  466. }
  467. ggml_backend_buffer_free(opt_ctx->buf_static);
  468. ggml_backend_buffer_free(opt_ctx->buf_cpu);
  469. ggml_free(opt_ctx->ctx_static);
  470. ggml_free(opt_ctx->ctx_cpu);
  471. delete opt_ctx;
  472. }
  473. void ggml_opt_reset(ggml_opt_context_t opt_ctx, bool optimizer) {
  474. if (optimizer) {
  475. ggml_graph_reset(opt_ctx->gb_opt);
  476. opt_ctx->iter = 1;
  477. } else {
  478. ggml_graph_reset(opt_ctx->gb_grad);
  479. }
  480. }
  481. bool ggml_opt_static_graphs(ggml_opt_context_t opt_ctx) {
  482. return opt_ctx->static_graphs;
  483. }
  484. struct ggml_tensor * ggml_opt_inputs(ggml_opt_context_t opt_ctx) {
  485. return opt_ctx->inputs;
  486. }
  487. struct ggml_tensor * ggml_opt_outputs(ggml_opt_context_t opt_ctx) {
  488. return opt_ctx->outputs;
  489. }
  490. struct ggml_tensor * ggml_opt_labels(ggml_opt_context_t opt_ctx) {
  491. return opt_ctx->labels;
  492. }
  493. struct ggml_tensor * ggml_opt_loss(ggml_opt_context_t opt_ctx) {
  494. return opt_ctx->loss;
  495. }
  496. struct ggml_tensor * ggml_opt_pred(ggml_opt_context_t opt_ctx) {
  497. return opt_ctx->pred;
  498. }
  499. struct ggml_tensor * ggml_opt_ncorrect(ggml_opt_context_t opt_ctx) {
  500. return opt_ctx->ncorrect;
  501. }
  502. struct ggml_tensor * ggml_opt_grad_acc(ggml_opt_context_t opt_ctx, struct ggml_tensor * node) {
  503. return ggml_graph_get_grad_acc(opt_ctx->gb_opt, node);
  504. }
  505. // ====== Optimization Result ======
  506. ggml_opt_result_t ggml_opt_result_init() {
  507. return new ggml_opt_result;
  508. }
  509. void ggml_opt_result_free(ggml_opt_result_t result) {
  510. delete result;
  511. }
  512. void ggml_opt_result_reset(ggml_opt_result_t result) {
  513. result->ndata = 0;
  514. result->loss.clear();
  515. result->pred.clear();
  516. result->ncorrect = 0;
  517. }
  518. void ggml_opt_result_ndata(ggml_opt_result_t result, int64_t * ndata) {
  519. *ndata = result->ndata;
  520. }
  521. void ggml_opt_result_loss(ggml_opt_result_t result, double * loss, double * unc) {
  522. const int64_t nbatches = result->loss.size(); // Number of physical batches.
  523. if (nbatches == 0) {
  524. *loss = 0.0;
  525. *unc = NAN;
  526. return;
  527. }
  528. double sum = 0.0;
  529. double sum_squared = 0.0;
  530. for (const float & loss : result->loss) {
  531. // If the loss is per datapoint it was scaled by 1.0f/opt_period for each physical batch.
  532. const float loss_scaled = result->loss_per_datapoint ? loss*result->opt_period : loss;
  533. sum += loss_scaled;
  534. sum_squared += loss_scaled*loss_scaled;
  535. }
  536. const double mean = sum/nbatches;
  537. *loss = result->loss_per_datapoint ? mean : sum;
  538. if (!unc) {
  539. return;
  540. }
  541. if (nbatches < 2) {
  542. *unc = NAN;
  543. return;
  544. }
  545. const double var_sum = sum_squared/nbatches - mean*mean; // variance without Bessel's correction, i.e. nbatches/(nbatches-1)
  546. *unc = result->loss_per_datapoint ? sqrt(var_sum / (nbatches - 1)) : sqrt(var_sum * nbatches/(nbatches - 1));
  547. }
  548. void ggml_opt_result_pred(ggml_opt_result_t result, int32_t * pred) {
  549. for (size_t i = 0; i < result->pred.size(); ++i) {
  550. pred[i] = result->pred[i];
  551. }
  552. }
  553. void ggml_opt_result_accuracy(ggml_opt_result_t result, double * accuracy, double * unc) {
  554. *accuracy = result->ncorrect >= 0 ? double(result->ncorrect) / double(result->ndata) : NAN;
  555. if (!unc) {
  556. return;
  557. }
  558. *unc = result->ncorrect >= 0 && result->ndata >= 2 ?
  559. sqrt((*accuracy) * (1.0 - (*accuracy)) / double(result->ndata - 1)) : NAN;
  560. }
  561. // ====== Computation ======
  562. void ggml_opt_prepare_alloc(
  563. ggml_opt_context_t opt_ctx,
  564. struct ggml_context * ctx_compute,
  565. struct ggml_cgraph * gf,
  566. struct ggml_tensor * inputs,
  567. struct ggml_tensor * outputs) {
  568. GGML_ASSERT(!opt_ctx->static_graphs);
  569. opt_ctx->ctx_compute = ctx_compute;
  570. opt_ctx->gf = gf;
  571. opt_ctx->inputs = inputs;
  572. opt_ctx->outputs = outputs;
  573. }
  574. void ggml_opt_alloc(ggml_opt_context_t opt_ctx, bool backward) {
  575. GGML_ASSERT(!opt_ctx->eval_ready);
  576. if (opt_ctx->build_type == GGML_OPT_BUILD_TYPE_OPT && opt_ctx->opt_period > 1 && opt_ctx->opt_i == 0) {
  577. ggml_graph_reset(opt_ctx->gb_grad);
  578. }
  579. if (backward) {
  580. const int32_t opt_i_next = (opt_ctx->opt_i + 1) % opt_ctx->opt_period;
  581. opt_ctx->build_type = opt_i_next == 0 ? GGML_OPT_BUILD_TYPE_OPT : GGML_OPT_BUILD_TYPE_GRAD;
  582. } else {
  583. opt_ctx->build_type = GGML_OPT_BUILD_TYPE_FORWARD;
  584. }
  585. if (!opt_ctx->static_graphs) {
  586. ggml_opt_build(opt_ctx);
  587. }
  588. struct ggml_cgraph * graph = nullptr;
  589. switch (opt_ctx->build_type) {
  590. case GGML_OPT_BUILD_TYPE_FORWARD: {
  591. graph = opt_ctx->gf;
  592. } break;
  593. case GGML_OPT_BUILD_TYPE_GRAD: {
  594. graph = opt_ctx->gb_grad;
  595. } break;
  596. case GGML_OPT_BUILD_TYPE_OPT: {
  597. graph = opt_ctx->gb_opt;
  598. } break;
  599. }
  600. GGML_ASSERT(graph);
  601. if (opt_ctx->allocated_graph == graph) {
  602. opt_ctx->eval_ready = true;
  603. return;
  604. }
  605. ggml_backend_sched_reset(opt_ctx->backend_sched); // clear allocation of previous graph
  606. if (opt_ctx->static_graphs) {
  607. ggml_init_params params = {
  608. /*.mem_size =*/ graph->size*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph->size, graph->grads),
  609. /*.mem_buffer =*/ nullptr,
  610. /*.no_alloc =*/ true,
  611. };
  612. ggml_free(opt_ctx->ctx_copy);
  613. opt_ctx->ctx_copy = ggml_init(params);
  614. opt_ctx->allocated_graph_copy = dup_graph(opt_ctx->ctx_copy, graph);
  615. } else {
  616. opt_ctx->allocated_graph_copy = graph;
  617. }
  618. ggml_backend_sched_alloc_graph(opt_ctx->backend_sched, opt_ctx->allocated_graph_copy);
  619. opt_ctx->allocated_graph = graph;
  620. opt_ctx->eval_ready = true;
  621. }
  622. void ggml_opt_eval(ggml_opt_context_t opt_ctx, ggml_opt_result_t result) {
  623. GGML_ASSERT(opt_ctx->eval_ready);
  624. if (opt_ctx->allocated_graph == opt_ctx->gb_opt) {
  625. struct ggml_opt_optimizer_params opt_pars = opt_ctx->get_opt_pars(opt_ctx->get_opt_pars_ud);
  626. GGML_ASSERT(opt_pars.adamw.alpha > 0.0f);
  627. GGML_ASSERT(opt_pars.adamw.beta1 >= 0.0f);
  628. GGML_ASSERT(opt_pars.adamw.beta1 <= 1.0f);
  629. GGML_ASSERT(opt_pars.adamw.beta2 >= 0.0f);
  630. GGML_ASSERT(opt_pars.adamw.beta2 <= 1.0f);
  631. GGML_ASSERT(opt_pars.adamw.eps >= 0.0f);
  632. GGML_ASSERT(opt_pars.adamw.wd >= 0.0f);
  633. GGML_ASSERT(opt_pars.adamw.wd <= 1.0f);
  634. // beta1, beta2 after applying warmup
  635. const float beta1h = 1.0f/(1.0f - powf(opt_pars.adamw.beta1, opt_ctx->iter));
  636. const float beta2h = 1.0f/(1.0f - powf(opt_pars.adamw.beta2, opt_ctx->iter));
  637. float * adamw_par_data = ggml_get_data_f32(opt_ctx->adamw_params);
  638. adamw_par_data[0] = opt_pars.adamw.alpha;
  639. adamw_par_data[1] = opt_pars.adamw.beta1;
  640. adamw_par_data[2] = opt_pars.adamw.beta2;
  641. adamw_par_data[3] = opt_pars.adamw.eps;
  642. adamw_par_data[4] = opt_pars.adamw.wd;
  643. adamw_par_data[5] = beta1h;
  644. adamw_par_data[6] = beta2h;
  645. }
  646. ggml_backend_sched_graph_compute(opt_ctx->backend_sched, opt_ctx->allocated_graph_copy);
  647. opt_ctx->iter += opt_ctx->allocated_graph == opt_ctx->gb_opt;
  648. opt_ctx->opt_i = (opt_ctx->opt_i + 1) % opt_ctx->opt_period;
  649. if (!opt_ctx->static_graphs) {
  650. opt_ctx->gf = nullptr;
  651. opt_ctx->gb_grad = nullptr;
  652. opt_ctx->gb_opt = nullptr;
  653. opt_ctx->allocated_graph = nullptr;
  654. opt_ctx->allocated_graph_copy = nullptr;
  655. }
  656. opt_ctx->eval_ready = false;
  657. if (!result) {
  658. return;
  659. }
  660. if (result->ndata == 0) {
  661. result->loss_per_datapoint = opt_ctx->loss_per_datapoint;
  662. result->opt_period = opt_ctx->opt_period;
  663. } else {
  664. GGML_ASSERT(result->loss_per_datapoint == opt_ctx->loss_per_datapoint);
  665. GGML_ASSERT(result->opt_period == opt_ctx->opt_period);
  666. }
  667. const int64_t ndata = opt_ctx->outputs->ne[1];
  668. GGML_ASSERT(result->ndata == ndata*int64_t(result->loss.size()) && "varying batch size not supported");
  669. result->ndata += ndata;
  670. GGML_ASSERT(ggml_is_scalar(opt_ctx->loss));
  671. GGML_ASSERT(opt_ctx->loss->type == GGML_TYPE_F32);
  672. float loss;
  673. ggml_backend_tensor_get(opt_ctx->loss, &loss, 0, ggml_nbytes(opt_ctx->loss));
  674. result->loss.push_back(loss);
  675. if (opt_ctx->pred) {
  676. GGML_ASSERT(opt_ctx->pred->type == GGML_TYPE_I32);
  677. std::vector<int32_t> pred(ndata);
  678. ggml_backend_tensor_get(opt_ctx->pred, pred.data(), 0, ggml_nbytes(opt_ctx->pred));
  679. result->pred.insert(result->pred.end(), pred.begin(), pred.end());
  680. }
  681. if (!opt_ctx->ncorrect || result->ncorrect < 0) {
  682. result->ncorrect = -1;
  683. return;
  684. }
  685. GGML_ASSERT(ggml_is_scalar(opt_ctx->ncorrect));
  686. GGML_ASSERT(opt_ctx->ncorrect->type == GGML_TYPE_I64);
  687. int64_t ncorrect;
  688. ggml_backend_tensor_get(opt_ctx->ncorrect, &ncorrect, 0, ggml_nbytes(opt_ctx->ncorrect));
  689. result->ncorrect += ncorrect;
  690. }
  691. // ====== High-Level Functions ======
  692. void ggml_opt_epoch(
  693. ggml_opt_context_t opt_ctx,
  694. ggml_opt_dataset_t dataset,
  695. ggml_opt_result_t result_train,
  696. ggml_opt_result_t result_eval,
  697. int64_t idata_split,
  698. ggml_opt_epoch_callback callback_train,
  699. ggml_opt_epoch_callback callback_eval) {
  700. GGML_ASSERT(ggml_opt_static_graphs(opt_ctx) && "ggml_opt_epoch requires static graphs");
  701. struct ggml_tensor * inputs = ggml_opt_inputs(opt_ctx);
  702. struct ggml_tensor * labels = ggml_opt_labels(opt_ctx);
  703. struct ggml_tensor * data = ggml_opt_dataset_data(dataset);
  704. GGML_ASSERT(data->ne[0] == inputs->ne[0]);
  705. const int64_t ndata = data->ne[1];
  706. const int64_t ndata_batch = inputs->ne[1];
  707. GGML_ASSERT(data->ne[1] % inputs->ne[1] == 0);
  708. const int64_t nbatches = ndata/ndata_batch;
  709. idata_split = idata_split < 0 ? ndata : idata_split;
  710. GGML_ASSERT(idata_split % ndata_batch == 0);
  711. const int64_t ibatch_split = idata_split / ndata_batch;
  712. int64_t ibatch = 0;
  713. int64_t t_loop_start = ggml_time_us();
  714. for (; ibatch < ibatch_split; ++ibatch) {
  715. ggml_opt_alloc(opt_ctx, /*backward =*/ true);
  716. ggml_opt_dataset_get_batch(dataset, inputs, labels, ibatch);
  717. ggml_opt_eval(opt_ctx, result_train);
  718. if (callback_train) {
  719. callback_train(true, opt_ctx, dataset, result_train, ibatch+1, ibatch_split, t_loop_start);
  720. }
  721. }
  722. t_loop_start = ggml_time_us();
  723. for (; ibatch < nbatches; ++ibatch) {
  724. ggml_opt_alloc(opt_ctx, /*backward =*/ false);
  725. ggml_opt_dataset_get_batch(dataset, inputs, labels, ibatch);
  726. ggml_opt_eval(opt_ctx, result_eval);
  727. if (callback_eval) {
  728. callback_eval(false, opt_ctx, dataset, result_eval, ibatch+1-ibatch_split, nbatches-ibatch_split, t_loop_start);
  729. }
  730. }
  731. }
  732. void ggml_opt_epoch_callback_progress_bar(
  733. bool train,
  734. ggml_opt_context_t opt_ctx,
  735. ggml_opt_dataset_t dataset,
  736. ggml_opt_result_t result,
  737. int64_t ibatch,
  738. int64_t ibatch_max,
  739. int64_t t_start_us) {
  740. fprintf(stderr, "%s[", train ? "train: " : "val: ");
  741. // The progress bar consists of partially filled blocks, unicode has 8 separate fill levels.
  742. constexpr int64_t bar_length = 8;
  743. const int64_t ibatch8 = 8 * ibatch;
  744. for (int64_t j = 0; j < bar_length; ++j) {
  745. if (ibatch_max * (8*j + 8) / bar_length < ibatch8) {
  746. fprintf(stderr, "\u2588"); // full block
  747. } else if (ibatch_max * (8*j + 7) / bar_length < ibatch8) {
  748. fprintf(stderr, "\u2589"); // 7/8 filled
  749. } else if (ibatch_max * (8*j + 6) / bar_length < ibatch8) {
  750. fprintf(stderr, "\u258A"); // 6/8 filled
  751. } else if (ibatch_max * (8*j + 5) / bar_length < ibatch8) {
  752. fprintf(stderr, "\u258B"); // 5/8 filled
  753. } else if (ibatch_max * (8*j + 4) / bar_length < ibatch8) {
  754. fprintf(stderr, "\u258C"); // 4/8 filled
  755. } else if (ibatch_max * (8*j + 3) / bar_length < ibatch8) {
  756. fprintf(stderr, "\u258D"); // 3/8 filled
  757. } else if (ibatch_max * (8*j + 2) / bar_length < ibatch8) {
  758. fprintf(stderr, "\u258E"); // 2/8 filled
  759. } else if (ibatch_max * (8*j + 1) / bar_length < ibatch8) {
  760. fprintf(stderr, "\u258F"); // 1/8 filled
  761. } else {
  762. fprintf(stderr, " ");
  763. }
  764. }
  765. const int64_t batch_size = ggml_opt_inputs(opt_ctx)->ne[1];
  766. const int64_t idata = ibatch*batch_size;
  767. const int64_t idata_max = ibatch_max*batch_size;
  768. double loss;
  769. double loss_unc;
  770. ggml_opt_result_loss(result, &loss, &loss_unc);
  771. double accuracy;
  772. double accuracy_unc;
  773. ggml_opt_result_accuracy(result, &accuracy, &accuracy_unc);
  774. const int64_t t_ibatch_us = ggml_time_us() - t_start_us;
  775. int64_t t_ibatch_s = t_ibatch_us / 1000000;
  776. const int64_t t_ibatch_h = t_ibatch_s / 3600;
  777. t_ibatch_s -= t_ibatch_h * 3600;
  778. const int64_t t_ibatch_m = t_ibatch_s / 60;
  779. t_ibatch_s -= t_ibatch_m * 60;
  780. const int64_t t_eta_us = t_ibatch_us * (ibatch_max - ibatch)/ibatch;
  781. int64_t t_eta_s = t_eta_us / 1000000;
  782. const int64_t t_eta_h = t_eta_s / 3600;
  783. t_eta_s -= t_eta_h * 3600;
  784. const int64_t t_eta_m = t_eta_s / 60;
  785. t_eta_s -= t_eta_m * 60;
  786. fprintf(stderr, "] data=%07" PRId64 "/%07" PRId64 " loss=%.5lf±%.5lf acc=%.2lf±%.2lf%% "
  787. "t=%02" PRId64 ":%02" PRId64 ":%02" PRId64 " ETA=%02" PRId64 ":%02" PRId64 ":%02" PRId64 " \r",
  788. idata, idata_max, loss, loss_unc, 100.0*accuracy, 100.0*accuracy_unc,
  789. t_ibatch_h, t_ibatch_m, t_ibatch_s, t_eta_h, t_eta_m, t_eta_s);
  790. if (ibatch == ibatch_max) {
  791. fprintf(stderr, "\n");
  792. }
  793. fflush(stderr);
  794. GGML_UNUSED(dataset);
  795. }
  796. void ggml_opt_fit(
  797. ggml_backend_sched_t backend_sched,
  798. ggml_context * ctx_compute,
  799. ggml_tensor * inputs,
  800. ggml_tensor * outputs,
  801. ggml_opt_dataset_t dataset,
  802. enum ggml_opt_loss_type loss_type,
  803. ggml_opt_get_optimizer_params get_opt_pars,
  804. int64_t nepoch,
  805. int64_t nbatch_logical,
  806. float val_split,
  807. bool silent) {
  808. ggml_time_init();
  809. const int64_t t_start_us = ggml_time_us();
  810. const int64_t ndata = ggml_opt_dataset_data(dataset)->ne[1];
  811. const int64_t nbatch_physical = inputs->ne[1];
  812. GGML_ASSERT(ndata % nbatch_logical == 0);
  813. GGML_ASSERT(nbatch_logical % nbatch_physical == 0);
  814. const int64_t opt_period = nbatch_logical / nbatch_physical;
  815. const int64_t nbatches_logical = ndata / nbatch_logical;
  816. GGML_ASSERT(val_split >= 0.0f);
  817. GGML_ASSERT(val_split < 1.0f);
  818. const int64_t ibatch_split = int64_t(((1.0f - val_split) * nbatches_logical)) * opt_period; // train <-> val split index (physical)
  819. const int64_t idata_split = ibatch_split * nbatch_physical;
  820. int64_t epoch = 1;
  821. ggml_opt_params params = ggml_opt_default_params(backend_sched, loss_type);
  822. params.ctx_compute = ctx_compute;
  823. params.inputs = inputs;
  824. params.outputs = outputs;
  825. params.opt_period = opt_period;
  826. params.get_opt_pars = get_opt_pars;
  827. params.get_opt_pars_ud = &epoch;
  828. ggml_opt_context_t opt_ctx = ggml_opt_init(params);
  829. // Shuffling the data is generally useful but there is only a point if not all data is used in a single batch.
  830. if (nbatch_logical < ndata) {
  831. ggml_opt_dataset_shuffle(opt_ctx, dataset, -1); // Shuffle all data (train + validation).
  832. }
  833. ggml_opt_result_t result_train = ggml_opt_result_init();
  834. ggml_opt_result_t result_val = ggml_opt_result_init();
  835. ggml_opt_epoch_callback epoch_callback = silent ? nullptr : ggml_opt_epoch_callback_progress_bar;
  836. for (; epoch <= nepoch; ++epoch) {
  837. if (nbatch_logical < idata_split) {
  838. ggml_opt_dataset_shuffle(opt_ctx, dataset, idata_split);
  839. }
  840. ggml_opt_result_reset(result_train);
  841. ggml_opt_result_reset(result_val);
  842. if (!silent) {
  843. fprintf(stderr, "%s: epoch %04" PRId64 "/%04" PRId64 ":\n", __func__, epoch, nepoch);
  844. }
  845. ggml_opt_epoch(opt_ctx, dataset, result_train, result_val, idata_split, epoch_callback, epoch_callback);
  846. if (!silent) {
  847. fprintf(stderr, "\n");
  848. }
  849. }
  850. if (!silent) {
  851. int64_t t_total_s = (ggml_time_us() - t_start_us) / 1000000;
  852. const int64_t t_total_h = t_total_s / 3600;
  853. t_total_s -= t_total_h * 3600;
  854. const int64_t t_total_m = t_total_s / 60;
  855. t_total_s -= t_total_m * 60;
  856. fprintf(stderr, "%s: training took %02" PRId64 ":%02" PRId64 ":%02" PRId64 "\n", __func__, t_total_h, t_total_m, t_total_s);
  857. }
  858. ggml_opt_free(opt_ctx);
  859. ggml_opt_result_free(result_train);
  860. ggml_opt_result_free(result_val);
  861. }