| 723 | } |
| 724 | |
| 725 | void ggml_opt_alloc(ggml_opt_context_t opt_ctx, bool backward) { |
| 726 | GGML_ASSERT(!opt_ctx->eval_ready); |
| 727 | if (opt_ctx->build_type == GGML_OPT_BUILD_TYPE_OPT && opt_ctx->opt_period > 1 && opt_ctx->opt_i == 0) { |
| 728 | ggml_graph_reset(opt_ctx->gb_grad); |
| 729 | } |
| 730 | if (backward) { |
| 731 | const int32_t opt_i_next = (opt_ctx->opt_i + 1) % opt_ctx->opt_period; |
| 732 | opt_ctx->build_type = opt_i_next == 0 ? GGML_OPT_BUILD_TYPE_OPT : GGML_OPT_BUILD_TYPE_GRAD; |
| 733 | } else { |
| 734 | opt_ctx->build_type = GGML_OPT_BUILD_TYPE_FORWARD; |
| 735 | } |
| 736 | |
| 737 | if (!opt_ctx->static_graphs) { |
| 738 | ggml_opt_build(opt_ctx); |
| 739 | } |
| 740 | |
| 741 | struct ggml_cgraph * graph = nullptr; |
| 742 | switch (opt_ctx->build_type) { |
| 743 | case GGML_OPT_BUILD_TYPE_FORWARD: { |
| 744 | graph = opt_ctx->gf; |
| 745 | } break; |
| 746 | case GGML_OPT_BUILD_TYPE_GRAD: { |
| 747 | graph = opt_ctx->gb_grad; |
| 748 | } break; |
| 749 | case GGML_OPT_BUILD_TYPE_OPT: { |
| 750 | graph = opt_ctx->gb_opt; |
| 751 | } break; |
| 752 | } |
| 753 | GGML_ASSERT(graph); |
| 754 | |
| 755 | if (opt_ctx->allocated_graph == graph) { |
| 756 | opt_ctx->eval_ready = true; |
| 757 | return; |
| 758 | } |
| 759 | |
| 760 | ggml_backend_sched_reset(opt_ctx->backend_sched); // clear allocation of previous graph |
| 761 | |
| 762 | if (opt_ctx->static_graphs) { |
| 763 | ggml_init_params params = { |
| 764 | /*.mem_size =*/ graph->size*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph->size, graph->grads), |
| 765 | /*.mem_buffer =*/ nullptr, |
| 766 | /*.no_alloc =*/ true, |
| 767 | }; |
| 768 | ggml_free(opt_ctx->ctx_copy); |
| 769 | opt_ctx->ctx_copy = ggml_init(params); |
| 770 | |
| 771 | opt_ctx->allocated_graph_copy = dup_graph(opt_ctx->ctx_copy, graph); |
| 772 | } else { |
| 773 | opt_ctx->allocated_graph_copy = graph; |
| 774 | } |
| 775 | |
| 776 | ggml_backend_sched_alloc_graph(opt_ctx->backend_sched, opt_ctx->allocated_graph_copy); |
| 777 | opt_ctx->allocated_graph = graph; |
| 778 | |
| 779 | opt_ctx->eval_ready = true; |
| 780 | } |
| 781 | |
| 782 | void ggml_opt_eval(ggml_opt_context_t opt_ctx, ggml_opt_result_t result) { |