ggml-opt.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. enum ggml_opt_optimizer_type {
  62. GGML_OPT_OPTIMIZER_TYPE_ADAMW,
  63. GGML_OPT_OPTIMIZER_TYPE_SGD,
  64. GGML_OPT_OPTIMIZER_TYPE_COUNT
  65. };
  66. // parameters that control which optimizer is used and how said optimizer tries to find the minimal loss
  67. struct ggml_opt_optimizer_params {
  68. struct {
  69. float alpha; // learning rate
  70. float beta1; // first AdamW momentum
  71. float beta2; // second AdamW momentum
  72. float eps; // epsilon for numerical stability
  73. float wd; // weight decay - 0.0f to disable
  74. } adamw;
  75. struct {
  76. float alpha; // learning rate
  77. float wd; // weight decay
  78. } sgd;
  79. };
  80. // callback to calculate optimizer parameters prior to a backward pass
  81. // userdata can be used to pass arbitrary data
  82. typedef struct ggml_opt_optimizer_params (*ggml_opt_get_optimizer_params)(void * userdata);
  83. // returns the default optimizer params (constant, hard-coded values)
  84. // userdata is not used
  85. GGML_API struct ggml_opt_optimizer_params ggml_opt_get_default_optimizer_params(void * userdata);
  86. // casts userdata to ggml_opt_optimizer_params and returns it
  87. GGML_API struct ggml_opt_optimizer_params ggml_opt_get_constant_optimizer_params(void * userdata);
  88. // parameters for initializing a new optimization context
  89. struct ggml_opt_params {
  90. ggml_backend_sched_t backend_sched; // defines which backends are used to construct the compute graphs
  91. // by default the forward graph needs to be reconstructed for each eval
  92. // if ctx_compute, inputs, and outputs are set the graphs are instead allocated statically
  93. struct ggml_context * ctx_compute;
  94. struct ggml_tensor * inputs;
  95. struct ggml_tensor * outputs;
  96. enum ggml_opt_loss_type loss_type;
  97. enum ggml_opt_build_type build_type;
  98. int32_t opt_period; // after how many gradient accumulation steps an optimizer step should be done
  99. ggml_opt_get_optimizer_params get_opt_pars; // callback for calculating optimizer parameters
  100. void * get_opt_pars_ud; // userdata for calculating optimizer parameters
  101. // only GGML_OPT_OPTIMIZER_TYPE_ADAMW needs m, v momenta per parameter tensor
  102. enum ggml_opt_optimizer_type optimizer;
  103. };
  104. // get parameters for an optimization context with defaults set where possible
  105. // parameters for which no sensible defaults exist are supplied as arguments to this function
  106. GGML_API struct ggml_opt_params ggml_opt_default_params(
  107. ggml_backend_sched_t backend_sched,
  108. enum ggml_opt_loss_type loss_type);
  109. GGML_API ggml_opt_context_t ggml_opt_init(struct ggml_opt_params params);
  110. GGML_API void ggml_opt_free(ggml_opt_context_t opt_ctx);
  111. // set gradients to zero, initilize loss, and optionally reset the optimizer
  112. GGML_API void ggml_opt_reset(ggml_opt_context_t opt_ctx, bool optimizer);
  113. GGML_API bool ggml_opt_static_graphs(ggml_opt_context_t opt_ctx); // whether the graphs are allocated_statically
  114. // get underlying tensors that store data
  115. // if not using static graphs these pointers become invalid with the next call to ggml_opt_alloc
  116. GGML_API struct ggml_tensor * ggml_opt_inputs( ggml_opt_context_t opt_ctx); // forward graph input tensor
  117. GGML_API struct ggml_tensor * ggml_opt_outputs( ggml_opt_context_t opt_ctx); // forward graph output tensor
  118. GGML_API struct ggml_tensor * ggml_opt_labels( ggml_opt_context_t opt_ctx); // labels to compare outputs against
  119. GGML_API struct ggml_tensor * ggml_opt_loss( ggml_opt_context_t opt_ctx); // scalar tensor that contains the loss
  120. GGML_API struct ggml_tensor * ggml_opt_pred( ggml_opt_context_t opt_ctx); // predictions made by outputs
  121. GGML_API struct ggml_tensor * ggml_opt_ncorrect(ggml_opt_context_t opt_ctx); // number of matching predictions between outputs and labels
  122. // get the gradient accumulator for a node from the forward graph
  123. GGML_API struct ggml_tensor * ggml_opt_grad_acc(ggml_opt_context_t opt_ctx, struct ggml_tensor * node);
  124. GGML_API enum ggml_opt_optimizer_type ggml_opt_context_optimizer_type(ggml_opt_context_t); //TODO consistent naming scheme
  125. GGML_API const char * ggml_opt_optimizer_name(enum ggml_opt_optimizer_type);
  126. // ====== Optimization Result ======
  127. GGML_API ggml_opt_result_t ggml_opt_result_init(void);
  128. GGML_API void ggml_opt_result_free(ggml_opt_result_t result);
  129. GGML_API void ggml_opt_result_reset(ggml_opt_result_t result);
  130. // get data from result, uncertainties are optional and can be ignored by passing NULL
  131. GGML_API void ggml_opt_result_ndata( ggml_opt_result_t result, int64_t * ndata); // writes 1 value, number of datapoints
  132. GGML_API void ggml_opt_result_loss( ggml_opt_result_t result, double * loss, double * unc); // writes 1 value
  133. GGML_API void ggml_opt_result_pred( ggml_opt_result_t result, int32_t * pred); // writes ndata values
  134. GGML_API void ggml_opt_result_accuracy(ggml_opt_result_t result, double * accuracy, double * unc); // writes 1 value
  135. // ====== Computation ======
  136. // if not using static graphs, this function must be called prior to ggml_opt_alloc
  137. GGML_API void ggml_opt_prepare_alloc(
  138. ggml_opt_context_t opt_ctx,
  139. struct ggml_context * ctx_compute,
  140. struct ggml_cgraph * gf,
  141. struct ggml_tensor * inputs,
  142. struct ggml_tensor * outputs);
  143. // allocate the next graph for evaluation, either forward or forward + backward
  144. // must be called exactly once prior to calling ggml_opt_eval
  145. GGML_API void ggml_opt_alloc(ggml_opt_context_t opt_ctx, bool backward);
  146. // do forward pass, increment result if not NULL, do backward pass if allocated
  147. GGML_API void ggml_opt_eval(ggml_opt_context_t opt_ctx, ggml_opt_result_t result);
  148. // ############################################################################
  149. // ## The high-level functions start here. They do not depend on any private ##
  150. // ## functions or structs and can be copied to and adapted for user code. ##
  151. // ############################################################################
  152. // ====== Intended Usage ======
  153. //
  154. // 1. Select the appropriate loss for your problem.
  155. // 2. Create a dataset and set the data for the "data" tensor. Also set the "labels" tensor if your loss needs them.
  156. // Setting the shard size to 1 will be fine, it's the granularity with which data is shuffled/loaded (bigger values are faster).
  157. // 3. Create a GGML graph for your model with no_alloc == true. Use two separate contexts for the tensors.
  158. // The first context should contain the model parameters and inputs and be allocated statically in user code.
  159. // The second context should contain all other tensors and will be (re)allocated automatically.
  160. // Due to this automated allocation the data of the second context is not defined when accessed in user code.
  161. // Note that the second dimension of the inputs/outputs are interpreted as the number of datapoints in those tensors.
  162. // 4. Call ggml_opt_fit. If you need more control you can use ggml_opt_epoch instead.
  163. // signature for a callback while evaluating opt_ctx on dataset, called after an evaluation
  164. typedef void (*ggml_opt_epoch_callback)(
  165. bool train, // true after training evaluation, false after validation evaluation
  166. ggml_opt_context_t opt_ctx,
  167. ggml_opt_dataset_t dataset,
  168. ggml_opt_result_t result, // result associated with the dataset subsection
  169. int64_t ibatch, // number of batches that have been evaluated so far
  170. int64_t ibatch_max, // total number of batches in this dataset subsection
  171. int64_t t_start_us); // time at which the evaluation on the dataset subsection was started
  172. // do training on front of dataset, do evaluation only on back of dataset
  173. GGML_API void ggml_opt_epoch(
  174. ggml_opt_context_t opt_ctx,
  175. ggml_opt_dataset_t dataset,
  176. ggml_opt_result_t result_train, // result to increment during training, ignored if NULL
  177. ggml_opt_result_t result_eval, // result to increment during evaluation, ignored if NULL
  178. int64_t idata_split, // data index at which to split training and evaluation
  179. ggml_opt_epoch_callback callback_train,
  180. ggml_opt_epoch_callback callback_eval);
  181. // callback that prints a progress bar on stderr
  182. GGML_API void ggml_opt_epoch_callback_progress_bar(
  183. bool train,
  184. ggml_opt_context_t opt_ctx,
  185. ggml_opt_dataset_t dataset,
  186. ggml_opt_result_t result,
  187. int64_t ibatch,
  188. int64_t ibatch_max,
  189. int64_t t_start_us);
  190. // fit model defined by inputs and outputs to dataset
  191. GGML_API void ggml_opt_fit(
  192. ggml_backend_sched_t backend_sched, // backend scheduler for constructing the compute graphs
  193. struct ggml_context * ctx_compute, // context with temporarily allocated tensors to calculate the outputs
  194. struct ggml_tensor * inputs, // input tensor with shape [ne_datapoint, ndata_batch]
  195. struct ggml_tensor * outputs, // output tensor, must have shape [ne_label, ndata_batch] if labels are used
  196. ggml_opt_dataset_t dataset, // dataset with data and optionally also labels
  197. enum ggml_opt_loss_type loss_type, // loss to minimize
  198. enum ggml_opt_optimizer_type optimizer, // sgd or adamw
  199. ggml_opt_get_optimizer_params get_opt_pars, // callback to get optimizer params, userdata is pointer to epoch (of type int64_t)
  200. int64_t nepoch, // how many times the dataset should be iterated over
  201. int64_t nbatch_logical, // datapoints optimizer step, must be a multiple of ndata_batch in inputs/outputs
  202. float val_split, // fraction of the dataset to use for validation, must be in [0.0f, 1.0f)
  203. bool silent); // whether or not info prints to stderr should be suppressed
  204. #ifdef __cplusplus
  205. }
  206. #endif