ggml-opt.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // This file contains functionality for training models using GGML.
  2. // It is not strictly needed vs. just vanilla GGML but it provides a more high-level interface for common needs such as datasets.
  3. // At the bottom of this file especially there are relatively high-level functions that are suitable use or adaptation in user code.
  4. //
  5. // Module maintainer: Johannes Gäßler (@JohannesGaessler, johannesg@5d6.de)
  6. #pragma once
  7. #include "ggml.h"
  8. #include "ggml-backend.h"
  9. #include <stdint.h>
  10. #ifdef __cplusplus
  11. extern "C" {
  12. #endif
  13. struct ggml_opt_dataset;
  14. struct ggml_opt_context;
  15. struct ggml_opt_result;
  16. typedef struct ggml_opt_dataset * ggml_opt_dataset_t;
  17. typedef struct ggml_opt_context * ggml_opt_context_t;
  18. typedef struct ggml_opt_result * ggml_opt_result_t;
  19. // ====== Loss ======
  20. // built-in loss types, i.e. the built-in quantities minimized by the optimizer
  21. // custom loss types can be defined via mean or sum which simply reduce the outputs for all datapoints to a single value
  22. enum ggml_opt_loss_type {
  23. GGML_OPT_LOSS_TYPE_MEAN,
  24. GGML_OPT_LOSS_TYPE_SUM,
  25. GGML_OPT_LOSS_TYPE_CROSS_ENTROPY,
  26. GGML_OPT_LOSS_TYPE_MEAN_SQUARED_ERROR,
  27. };
  28. // ====== Dataset ======
  29. GGML_API ggml_opt_dataset_t ggml_opt_dataset_init(
  30. enum ggml_type type_data, // the type for the internal data tensor
  31. enum ggml_type type_label, // the type for the internal labels tensor
  32. int64_t ne_datapoint, // number of elements per datapoint
  33. int64_t ne_label, // number of elements per label
  34. int64_t ndata, // total number of datapoints/labels
  35. int64_t ndata_shard); // number of datapoints/labels per shard (unit at which the dataset is shuffled/copied)
  36. GGML_API void ggml_opt_dataset_free(ggml_opt_dataset_t dataset);
  37. // get underlying tensors that store the data
  38. GGML_API int64_t ggml_opt_dataset_ndata (ggml_opt_dataset_t dataset);
  39. GGML_API struct ggml_tensor * ggml_opt_dataset_data (ggml_opt_dataset_t dataset); // shape = [ne_datapoint, ndata]
  40. GGML_API struct ggml_tensor * ggml_opt_dataset_labels(ggml_opt_dataset_t dataset); // shape = [nd_label, ndata]
  41. // shuffle idata first datapoints from dataset with RNG from opt_ctx, shuffle all datapoints if idata is negative
  42. GGML_API void ggml_opt_dataset_shuffle(ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, int64_t idata);
  43. // get batch at position ibatch from dataset and copy the data to data_batch and labels_batch
  44. GGML_API void ggml_opt_dataset_get_batch(
  45. ggml_opt_dataset_t dataset,
  46. struct ggml_tensor * data_batch, // shape = [ne_datapoint, ndata_batch]
  47. struct ggml_tensor * labels_batch, // shape = [ne_label, ndata_batch]
  48. int64_t ibatch);
  49. GGML_API void ggml_opt_dataset_get_batch_host(
  50. ggml_opt_dataset_t dataset,
  51. void * data_batch,
  52. size_t nb_data_batch,
  53. void * labels_batch,
  54. int64_t ibatch);
  55. // ====== Model / Context ======
  56. enum ggml_opt_build_type {
  57. GGML_OPT_BUILD_TYPE_FORWARD = 10,
  58. GGML_OPT_BUILD_TYPE_GRAD = 20,
  59. GGML_OPT_BUILD_TYPE_OPT = 30,
  60. };
  61. // parameters that control which optimizer is used and how said optimizer tries to find the minimal loss
  62. struct ggml_opt_optimizer_params {
  63. // AdamW optimizer parameters
  64. struct {
  65. float alpha; // learning rate
  66. float beta1;
  67. float beta2;
  68. float eps; // epsilon for numerical stability
  69. float wd; // weight decay for AdamW, use 0.0f to disable
  70. } adamw;
  71. };
  72. // callback to calculate optimizer parameters prior to a backward pass
  73. // userdata can be used to pass arbitrary data
  74. typedef struct ggml_opt_optimizer_params (*ggml_opt_get_optimizer_params)(void * userdata);
  75. // returns the default optimizer params (constant, hard-coded values)
  76. // userdata is not used
  77. GGML_API struct ggml_opt_optimizer_params ggml_opt_get_default_optimizer_params(void * userdata);
  78. // casts userdata to ggml_opt_optimizer_params and returns it
  79. GGML_API struct ggml_opt_optimizer_params ggml_opt_get_constant_optimizer_params(void * userdata);
  80. // parameters for initializing a new optimization context
  81. struct ggml_opt_params {
  82. ggml_backend_sched_t backend_sched; // defines which backends are used to construct the compute graphs
  83. // by default the forward graph needs to be reconstructed for each eval
  84. // if ctx_compute, inputs, and outputs are set the graphs are instead allocated statically
  85. struct ggml_context * ctx_compute;
  86. struct ggml_tensor * inputs;
  87. struct ggml_tensor * outputs;
  88. enum ggml_opt_loss_type loss_type;
  89. enum ggml_opt_build_type build_type;
  90. int32_t opt_period; // after how many gradient accumulation steps an optimizer step should be done
  91. ggml_opt_get_optimizer_params get_opt_pars; // callback for calculating optimizer parameters
  92. void * get_opt_pars_ud; // userdata for calculating optimizer parameters
  93. };
  94. // get parameters for an optimization context with defaults set where possible
  95. // parameters for which no sensible defaults exist are supplied as arguments to this function
  96. GGML_API struct ggml_opt_params ggml_opt_default_params(
  97. ggml_backend_sched_t backend_sched,
  98. enum ggml_opt_loss_type loss_type);
  99. GGML_API ggml_opt_context_t ggml_opt_init(struct ggml_opt_params params);
  100. GGML_API void ggml_opt_free(ggml_opt_context_t opt_ctx);
  101. // set gradients to zero, initilize loss, and optionally reset the optimizer
  102. GGML_API void ggml_opt_reset(ggml_opt_context_t opt_ctx, bool optimizer);
  103. GGML_API bool ggml_opt_static_graphs(ggml_opt_context_t opt_ctx); // whether the graphs are allocated_statically
  104. // get underlying tensors that store data
  105. // if not using static graphs these pointers become invalid with the next call to ggml_opt_alloc
  106. GGML_API struct ggml_tensor * ggml_opt_inputs( ggml_opt_context_t opt_ctx); // forward graph input tensor
  107. GGML_API struct ggml_tensor * ggml_opt_outputs( ggml_opt_context_t opt_ctx); // forward graph output tensor
  108. GGML_API struct ggml_tensor * ggml_opt_labels( ggml_opt_context_t opt_ctx); // labels to compare outputs against
  109. GGML_API struct ggml_tensor * ggml_opt_loss( ggml_opt_context_t opt_ctx); // scalar tensor that contains the loss
  110. GGML_API struct ggml_tensor * ggml_opt_pred( ggml_opt_context_t opt_ctx); // predictions made by outputs
  111. GGML_API struct ggml_tensor * ggml_opt_ncorrect(ggml_opt_context_t opt_ctx); // number of matching predictions between outputs and labels
  112. // get the gradient accumulator for a node from the forward graph
  113. GGML_API struct ggml_tensor * ggml_opt_grad_acc(ggml_opt_context_t opt_ctx, struct ggml_tensor * node);
  114. // ====== Optimization Result ======
  115. GGML_API ggml_opt_result_t ggml_opt_result_init(void);
  116. GGML_API void ggml_opt_result_free(ggml_opt_result_t result);
  117. GGML_API void ggml_opt_result_reset(ggml_opt_result_t result);
  118. // get data from result, uncertainties are optional and can be ignored by passing NULL
  119. GGML_API void ggml_opt_result_ndata( ggml_opt_result_t result, int64_t * ndata); // writes 1 value, number of datapoints
  120. GGML_API void ggml_opt_result_loss( ggml_opt_result_t result, double * loss, double * unc); // writes 1 value
  121. GGML_API void ggml_opt_result_pred( ggml_opt_result_t result, int32_t * pred); // writes ndata values
  122. GGML_API void ggml_opt_result_accuracy(ggml_opt_result_t result, double * accuracy, double * unc); // writes 1 value
  123. // ====== Computation ======
  124. // if not using static graphs, this function must be called prior to ggml_opt_alloc
  125. GGML_API void ggml_opt_prepare_alloc(
  126. ggml_opt_context_t opt_ctx,
  127. struct ggml_context * ctx_compute,
  128. struct ggml_cgraph * gf,
  129. struct ggml_tensor * inputs,
  130. struct ggml_tensor * outputs);
  131. // allocate the next graph for evaluation, either forward or forward + backward
  132. // must be called exactly once prior to calling ggml_opt_eval
  133. GGML_API void ggml_opt_alloc(ggml_opt_context_t opt_ctx, bool backward);
  134. // do forward pass, increment result if not NULL, do backward pass if allocated
  135. GGML_API void ggml_opt_eval(ggml_opt_context_t opt_ctx, ggml_opt_result_t result);
  136. // ############################################################################
  137. // ## The high-level functions start here. They do not depend on any private ##
  138. // ## functions or structs and can be copied to and adapted for user code. ##
  139. // ############################################################################
  140. // ====== Intended Usage ======
  141. //
  142. // 1. Select the appropriate loss for your problem.
  143. // 2. Create a dataset and set the data for the "data" tensor. Also set the "labels" tensor if your loss needs them.
  144. // Setting the shard size to 1 will be fine, it's the granularity with which data is shuffled/loaded (bigger values are faster).
  145. // 3. Create a GGML graph for your model with no_alloc == true. Use two separate contexts for the tensors.
  146. // The first context should contain the model parameters and inputs and be allocated statically in user code.
  147. // The second context should contain all other tensors and will be (re)allocated automatically.
  148. // Due to this automated allocation the data of the second context is not defined when accessed in user code.
  149. // Note that the second dimension of the inputs/outputs are interpreted as the number of datapoints in those tensors.
  150. // 4. Call ggml_opt_fit. If you need more control you can use ggml_opt_epoch instead.
  151. // signature for a callback while evaluating opt_ctx on dataset, called after an evaluation
  152. typedef void (*ggml_opt_epoch_callback)(
  153. bool train, // true after training evaluation, false after validation evaluation
  154. ggml_opt_context_t opt_ctx,
  155. ggml_opt_dataset_t dataset,
  156. ggml_opt_result_t result, // result associated with the dataset subsection
  157. int64_t ibatch, // number of batches that have been evaluated so far
  158. int64_t ibatch_max, // total number of batches in this dataset subsection
  159. int64_t t_start_us); // time at which the evaluation on the dataset subsection was started
  160. // do training on front of dataset, do evaluation only on back of dataset
  161. GGML_API void ggml_opt_epoch(
  162. ggml_opt_context_t opt_ctx,
  163. ggml_opt_dataset_t dataset,
  164. ggml_opt_result_t result_train, // result to increment during training, ignored if NULL
  165. ggml_opt_result_t result_eval, // result to increment during evaluation, ignored if NULL
  166. int64_t idata_split, // data index at which to split training and evaluation
  167. ggml_opt_epoch_callback callback_train,
  168. ggml_opt_epoch_callback callback_eval);
  169. // callback that prints a progress bar on stderr
  170. GGML_API void ggml_opt_epoch_callback_progress_bar(
  171. bool train,
  172. ggml_opt_context_t opt_ctx,
  173. ggml_opt_dataset_t dataset,
  174. ggml_opt_result_t result,
  175. int64_t ibatch,
  176. int64_t ibatch_max,
  177. int64_t t_start_us);
  178. // fit model defined by inputs and outputs to dataset
  179. GGML_API void ggml_opt_fit(
  180. ggml_backend_sched_t backend_sched, // backend scheduler for constructing the compute graphs
  181. struct ggml_context * ctx_compute, // context with temporarily allocated tensors to calculate the outputs
  182. struct ggml_tensor * inputs, // input tensor with shape [ne_datapoint, ndata_batch]
  183. struct ggml_tensor * outputs, // output tensor, must have shape [ne_label, ndata_batch] if labels are used
  184. ggml_opt_dataset_t dataset, // dataset with data and optionally also labels
  185. enum ggml_opt_loss_type loss_type, // loss to minimize
  186. ggml_opt_get_optimizer_params get_opt_pars, // callback to get optimizer params, userdata is pointer to epoch (of type int64_t)
  187. int64_t nepoch, // how many times the dataset should be iterated over
  188. int64_t nbatch_logical, // datapoints optimizer step, must be a multiple of ndata_batch in inputs/outputs
  189. float val_split, // fraction of the dataset to use for validation, must be in [0.0f, 1.0f)
  190. bool silent); // whether or not info prints to stderr should be suppressed
  191. #ifdef __cplusplus
  192. }
  193. #endif