ggml-opt.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. int64_t ne_datapoint, // number of elements per datapoint
  31. int64_t ne_label, // number of elements per label
  32. int64_t ndata, // total number of datapoints/labels
  33. int64_t ndata_shard); // number of datapoints/labels per shard (unit at which the dataset is shuffled/copied)
  34. GGML_API void ggml_opt_dataset_free(ggml_opt_dataset_t dataset);
  35. // get underlying tensors that store the data
  36. GGML_API struct ggml_tensor * ggml_opt_dataset_data (ggml_opt_dataset_t dataset); // shape = [ne_datapoint, ndata]
  37. GGML_API struct ggml_tensor * ggml_opt_dataset_labels(ggml_opt_dataset_t dataset); // shape = [nd_label, ndata]
  38. // shuffle idata first datapoints from dataset with RNG from opt_ctx, shuffle all datapoints if idata is negative
  39. GGML_API void ggml_opt_dataset_shuffle(ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, int64_t idata);
  40. // get batch at position ibatch from dataset and copy the data to data_batch and labels_batch
  41. GGML_API void ggml_opt_dataset_get_batch(
  42. ggml_opt_dataset_t dataset,
  43. struct ggml_tensor * data_batch, // shape = [ne_datapoint, ndata_batch]
  44. struct ggml_tensor * labels_batch, // shape = [ne_label, ndata_batch]
  45. int64_t ibatch);
  46. // ====== Model / Context ======
  47. enum ggml_opt_build_type {
  48. GGML_OPT_BUILD_TYPE_FORWARD,
  49. GGML_OPT_BUILD_TYPE_GRAD,
  50. GGML_OPT_BUILD_TYPE_OPT,
  51. };
  52. // parameters that control which optimizer is used and how said optimizer tries to find the minimal loss
  53. struct ggml_opt_optimizer_params {
  54. // AdamW optimizer parameters
  55. struct {
  56. float alpha; // learning rate
  57. float beta1;
  58. float beta2;
  59. float eps; // epsilon for numerical stability
  60. float wd; // weight decay for AdamW, use 0.0f to disable
  61. } adamw;
  62. };
  63. // callback to calculate optimizer parameters prior to a backward pass
  64. // userdata can be used to pass arbitrary data
  65. typedef struct ggml_opt_optimizer_params (*ggml_opt_get_optimizer_params)(void * userdata);
  66. // returns the default optimizer params (constant)
  67. // userdata is not used
  68. GGML_API struct ggml_opt_optimizer_params ggml_opt_get_default_optimizer_params(void * userdata);
  69. // parameters for initializing a new optimization context
  70. struct ggml_opt_params {
  71. ggml_backend_sched_t backend_sched; // defines which backends are used to construct the compute graphs
  72. struct ggml_context * ctx_compute; // created in user code, holds non-static tensors
  73. // the forward graph is defined by inputs and outputs
  74. // those tensors and all tensors inbetween are not intended to be reusable between multiple optimization contexts
  75. struct ggml_tensor * inputs;
  76. struct ggml_tensor * outputs;
  77. enum ggml_opt_loss_type loss_type;
  78. enum ggml_opt_build_type build_type;
  79. int32_t opt_period; // after how many gradient accumulation steps an optimizer step should be done
  80. ggml_opt_get_optimizer_params get_opt_pars; // callback for calculating optimizer parameters
  81. void * get_opt_pars_ud; // userdata for calculating optimizer parameters
  82. };
  83. // get parameters for an optimization context with defaults set where possible
  84. // parameters for which no sensible defaults exist are supplied as arguments to this function
  85. GGML_API ggml_opt_params ggml_opt_default_params(
  86. ggml_backend_sched_t backend_sched,
  87. struct ggml_context * ctx_compute,
  88. struct ggml_tensor * inputs,
  89. struct ggml_tensor * outputs,
  90. enum ggml_opt_loss_type loss_type);
  91. GGML_API ggml_opt_context_t ggml_opt_init(struct ggml_opt_params params);
  92. GGML_API void ggml_opt_free(ggml_opt_context_t opt_ctx);
  93. // set gradients to zero, initilize loss, and optionally reset the optimizer
  94. GGML_API void ggml_opt_reset(ggml_opt_context_t opt_ctx, bool optimizer);
  95. // get underlying tensors that store data
  96. GGML_API struct ggml_tensor * ggml_opt_inputs( ggml_opt_context_t opt_ctx); // forward graph input tensor
  97. GGML_API struct ggml_tensor * ggml_opt_outputs( ggml_opt_context_t opt_ctx); // forward graph output tensor
  98. GGML_API struct ggml_tensor * ggml_opt_labels( ggml_opt_context_t opt_ctx); // labels to compare outputs against
  99. GGML_API struct ggml_tensor * ggml_opt_loss( ggml_opt_context_t opt_ctx); // scalar tensor that contains the loss
  100. GGML_API struct ggml_tensor * ggml_opt_pred( ggml_opt_context_t opt_ctx); // predictions made by outputs
  101. GGML_API struct ggml_tensor * ggml_opt_ncorrect(ggml_opt_context_t opt_ctx); // number of matching predictions between outputs and labels
  102. GGML_API struct ggml_tensor * ggml_opt_grad_acc(ggml_opt_context_t opt_ctx, struct ggml_tensor * node);
  103. // ====== Optimization Result ======
  104. GGML_API ggml_opt_result_t ggml_opt_result_init();
  105. GGML_API void ggml_opt_result_free(ggml_opt_result_t result);
  106. GGML_API void ggml_opt_result_reset(ggml_opt_result_t result);
  107. // get data from result, uncertainties are optional and can be ignored by passing NULL
  108. GGML_API void ggml_opt_result_ndata( ggml_opt_result_t result, int64_t * ndata); // writes 1 value, number of datapoints
  109. GGML_API void ggml_opt_result_loss( ggml_opt_result_t result, double * loss, double * unc); // writes 1 value
  110. GGML_API void ggml_opt_result_pred( ggml_opt_result_t result, int32_t * pred); // writes ndata values
  111. GGML_API void ggml_opt_result_accuracy(ggml_opt_result_t result, double * accuracy, double * unc); // writes 1 value
  112. // ====== Computation ======
  113. // do forward pass, increment result if not NULL
  114. GGML_API void ggml_opt_forward(ggml_opt_context_t opt_ctx, ggml_opt_result_t result);
  115. // do forward pass, increment result if not NULL, do backward pass
  116. GGML_API void ggml_opt_forward_backward(ggml_opt_context_t opt_ctx, ggml_opt_result_t result);
  117. // ############################################################################
  118. // ## The high-level functions start here. They do not depend on any private ##
  119. // ## functions or structs and can be copied to and adapted for user code. ##
  120. // ############################################################################
  121. // ====== Intended Usage ======
  122. //
  123. // 1. Select the appropriate loss for your problem.
  124. // 2. Create a dataset and set the data for the "data" tensor. Also set the "labels" tensor if your loss needs them.
  125. // Setting the shard size to 1 will be fine, it's the granularity with which data is shuffled/loaded (bigger values are faster).
  126. // 3. Create a GGML graph for your model with no_alloc == true. Use two separate contexts for the tensors.
  127. // The first context should contain the model parameters and inputs and be allocated statically in user code.
  128. // The second context should contain all other tensors and will be (re)allocated automatically.
  129. // Due to this automated allocation the data of the second context is not defined when accessed in user code.
  130. // Note that the second dimension of the inputs/outputs are interpreted as the number of datapoints in those tensors.
  131. // 4. Call ggml_opt_fit. If you need more control you can use ggml_opt_epoch instead.
  132. // signature for a callback while evaluating opt_ctx on dataset, called after an evaluation
  133. typedef void (*ggml_opt_epoch_callback)(
  134. bool train, // true after training evaluation, false after validation evaluation
  135. ggml_opt_context_t opt_ctx,
  136. ggml_opt_dataset_t dataset,
  137. ggml_opt_result_t result, // result associated with the dataset subsection
  138. int64_t ibatch, // number of batches that have been evaluated so far
  139. int64_t ibatch_max, // total number of batches in this dataset subsection
  140. int64_t t_start_us); // time at which the evaluation on the dataset subsection was started
  141. // do training on front of dataset, do evaluation only on back of dataset
  142. GGML_API void ggml_opt_epoch(
  143. ggml_opt_context_t opt_ctx,
  144. ggml_opt_dataset_t dataset,
  145. ggml_opt_result_t result_train, // result to increment during training, ignored if NULL
  146. ggml_opt_result_t result_eval, // result to increment during evaluation, ignored if NULL
  147. int64_t idata_split, // data index at which to split training and evaluation
  148. ggml_opt_epoch_callback callback_train,
  149. ggml_opt_epoch_callback callback_eval);
  150. // callback that prints a progress bar on stderr
  151. GGML_API void ggml_opt_epoch_callback_progress_bar(
  152. bool train,
  153. ggml_opt_context_t opt_ctx,
  154. ggml_opt_dataset_t dataset,
  155. ggml_opt_result_t result,
  156. int64_t ibatch,
  157. int64_t ibatch_max,
  158. int64_t t_start_us);
  159. // fit model defined by inputs and outputs to dataset
  160. GGML_API void ggml_opt_fit(
  161. ggml_backend_sched_t backend_sched, // backend scheduler for constructing the compute graphs
  162. ggml_context * ctx_compute, // context with temporarily allocated tensors to calculate the outputs
  163. ggml_tensor * inputs, // input tensor with shape [ne_datapoint, ndata_batch]
  164. ggml_tensor * outputs, // output tensor, must have shape [ne_label, ndata_batch] if labels are used
  165. ggml_opt_dataset_t dataset, // dataset with data and optionally also labels
  166. enum ggml_opt_loss_type loss_type, // loss to minimize
  167. ggml_opt_get_optimizer_params get_opt_pars, // callback to get optimizer params, userdata is pointer to epoch (of type int64_t)
  168. int64_t nepoch, // how many times the dataset should be iterated over
  169. int64_t nbatch_logical, // datapoints optimizer step, must be a multiple of ndata_batch in inputs/outputs
  170. float val_split, // fraction of the dataset to use for validation, must be in [0.0f, 1.0f)
  171. bool silent); // whether or not info prints to stderr should be suppressed
  172. #ifdef __cplusplus
  173. }
  174. #endif