train.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  1. #include "train.h"
  2. #include "common.h"
  3. #include <random>
  4. #include <sstream>
  5. #include <functional>
  6. struct random_normal_distribution {
  7. std::mt19937 gen;
  8. std::normal_distribution<float> rd;
  9. float min;
  10. float max;
  11. };
  12. struct random_uniform_distribution {
  13. std::mt19937 gen;
  14. std::uniform_real_distribution<float> rd;
  15. };
  16. struct train_state * init_train_state() {
  17. struct train_state * state = new struct train_state;
  18. state->train_its = 0;
  19. state->train_samples = 0;
  20. state->train_tokens = 0;
  21. state->train_epochs = 0;
  22. state->shuffle_samples_hash = 0;
  23. state->shuffle_sample_count = 0;
  24. state->shuffle_next_sample = 0;
  25. state->shuffle_rng_state_current = "";
  26. state->shuffle_rng_state_next = "";
  27. state->opt = new struct ggml_opt_context;
  28. state->opt->ctx = NULL;
  29. state->opt->params = ggml_opt_default_params(GGML_OPT_ADAM);
  30. state->opt->params.graph_size = LLAMA_TRAIN_MAX_NODES;
  31. state->opt->loss_after = 0.0f;
  32. return state;
  33. }
  34. void free_train_state(struct train_state * state) {
  35. delete state->opt;
  36. delete state;
  37. }
  38. struct random_normal_distribution * init_random_normal_distribution(
  39. int seed, float mean, float std, float min, float max
  40. ) {
  41. struct random_normal_distribution * rnd = (struct random_normal_distribution *) malloc(sizeof(struct random_normal_distribution));
  42. rnd->gen = std::mt19937(seed);
  43. rnd->rd = std::normal_distribution<float>{mean, std};
  44. rnd->min = min;
  45. rnd->max = max;
  46. return rnd;
  47. }
  48. struct random_uniform_distribution * init_random_uniform_distribution(int seed, float min, float max) {
  49. struct random_uniform_distribution * rnd = (struct random_uniform_distribution *) malloc(sizeof(struct random_uniform_distribution));
  50. rnd->gen = std::mt19937(seed);
  51. rnd->rd = std::uniform_real_distribution<float>{min, max};
  52. return rnd;
  53. }
  54. void free_random_normal_distribution (struct random_normal_distribution * rnd) {
  55. free(rnd);
  56. }
  57. void free_random_uniform_distribution(struct random_uniform_distribution * rnd) {
  58. free(rnd);
  59. }
  60. struct ggml_tensor * randomize_tensor_normal(struct ggml_tensor * tensor, struct random_normal_distribution * rnd) {
  61. float scale = 1.0f; // xavier
  62. switch (tensor->n_dims) {
  63. case 1:
  64. scale /= sqrtf((float) tensor->ne[0]);
  65. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  66. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0]);
  67. *dst = scale * frand_normal(rnd);
  68. }
  69. break;
  70. case 2:
  71. scale /= sqrtf((float) tensor->ne[0]+tensor->ne[1]);
  72. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  73. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  74. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  75. *dst = scale * frand_normal(rnd);
  76. }
  77. }
  78. break;
  79. case 3:
  80. scale /= sqrtf((float) tensor->ne[0]+tensor->ne[1]);
  81. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  82. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  83. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  84. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  85. *dst = scale * frand_normal(rnd);
  86. }
  87. }
  88. }
  89. break;
  90. case 4:
  91. scale /= sqrtf((float) tensor->ne[0]+tensor->ne[1]);
  92. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  93. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  94. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  95. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  96. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]);
  97. *dst = scale * frand_normal(rnd);
  98. }
  99. }
  100. }
  101. }
  102. break;
  103. default:
  104. die("Unsupported tensor->n_dims");
  105. };
  106. return tensor;
  107. }
  108. struct ggml_tensor * randomize_tensor_uniform(struct ggml_tensor * tensor, struct random_uniform_distribution * rnd) {
  109. switch (tensor->n_dims) {
  110. case 1:
  111. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  112. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0]);
  113. *dst = frand_uniform(rnd);
  114. }
  115. break;
  116. case 2:
  117. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  118. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  119. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1]);
  120. *dst = frand_uniform(rnd);
  121. }
  122. }
  123. break;
  124. case 3:
  125. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  126. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  127. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  128. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2]);
  129. *dst = frand_uniform(rnd);
  130. }
  131. }
  132. }
  133. break;
  134. case 4:
  135. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  136. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  137. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  138. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  139. float * dst = (float *) ((char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]);
  140. *dst = frand_uniform(rnd);
  141. }
  142. }
  143. }
  144. }
  145. break;
  146. default:
  147. die("Unsupported tensor->n_dims");
  148. };
  149. return tensor;
  150. }
  151. float frand() {
  152. return (float)rand()/((float)(RAND_MAX) + 1.0f);
  153. }
  154. float frand_normal(struct random_normal_distribution * rnd) {
  155. return fclamp(rnd->rd(rnd->gen), rnd->min, rnd->max);
  156. }
  157. float frand_uniform(struct random_uniform_distribution * rnd) {
  158. return rnd->rd(rnd->gen);
  159. }
  160. int clamp(const int v, const int min, const int max) {
  161. return ((v < min) ? (min) : (v > max) ? (max) : v);
  162. }
  163. float fclamp(const float v, const float min, const float max) {
  164. return ((v < min) ? (min) : (v > max) ? (max) : v);
  165. }
  166. void assert_shape_1d(struct ggml_tensor * tensor, int64_t ne0) {
  167. GGML_ASSERT(tensor->n_dims == 1);
  168. GGML_ASSERT(tensor->ne[0] == ne0);
  169. }
  170. void assert_shape_2d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1) {
  171. GGML_ASSERT(tensor->n_dims == 2);
  172. GGML_ASSERT(tensor->ne[0] == ne0);
  173. GGML_ASSERT(tensor->ne[1] == ne1);
  174. }
  175. void assert_shape_3d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2) {
  176. GGML_ASSERT(tensor->n_dims == 3);
  177. GGML_ASSERT(tensor->ne[0] == ne0);
  178. GGML_ASSERT(tensor->ne[1] == ne1);
  179. GGML_ASSERT(tensor->ne[2] == ne2);
  180. }
  181. void assert_shape_4d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
  182. GGML_ASSERT(tensor->n_dims == 4);
  183. GGML_ASSERT(tensor->ne[0] == ne0);
  184. GGML_ASSERT(tensor->ne[1] == ne1);
  185. GGML_ASSERT(tensor->ne[2] == ne2);
  186. GGML_ASSERT(tensor->ne[3] == ne3);
  187. }
  188. int64_t get_example_targets_batch(
  189. struct llama_context * lctx,
  190. struct ggml_tensor * tokens_input,
  191. struct ggml_tensor * target_probs,
  192. int64_t example_id,
  193. const size_t * samples_offs,
  194. const size_t * samples_begin,
  195. const size_t * samples_size,
  196. size_t samples_count,
  197. const llama_token * train_data,
  198. size_t n_train_data,
  199. bool separate_with_eos,
  200. bool separate_with_bos,
  201. bool fill_with_next_samples,
  202. bool sample_random_offsets
  203. ) {
  204. GGML_ASSERT(samples_count > 0);
  205. GGML_ASSERT(tokens_input->n_dims == 2);
  206. GGML_ASSERT(target_probs->n_dims == 3);
  207. int64_t n_vocab = target_probs->ne[0];
  208. int64_t n_tokens = tokens_input->ne[0];
  209. int64_t n_batch = tokens_input->ne[1];
  210. GGML_ASSERT(n_vocab == target_probs->ne[0]);
  211. GGML_ASSERT(n_tokens == target_probs->ne[1]);
  212. GGML_ASSERT(n_batch == target_probs->ne[2]);
  213. int64_t used_samples = 0;
  214. ggml_set_f32(target_probs, 0.0f);
  215. llama_token bos = llama_token_bos(llama_get_model(lctx));
  216. llama_token eos = llama_token_eos(llama_get_model(lctx));
  217. // printf("%s: example_id=%d n_batch=%d n_train_samples=%zu\n", __func__, example_id, n_batch, n_train_samples);
  218. for (int k=0; k<n_batch; ++k) {
  219. // printf("%s: batch %d\n", __func__, k);
  220. size_t sample_idx = (example_id + used_samples) % samples_count;
  221. size_t sample_offs = sample_random_offsets ? samples_offs[sample_idx] : 0;
  222. size_t sample_begin = samples_begin[sample_idx];
  223. size_t sample_size = samples_size[sample_idx];
  224. ++used_samples;
  225. // printf("%s: sample_idx=%zu sample=%zu\n", __func__, sample_idx, sample);
  226. GGML_ASSERT(sample_begin+sample_size-1 < n_train_data);
  227. ggml_set_i32_nd(tokens_input, 0, k, 0, 0, bos);
  228. bool sample_separation_eos = !separate_with_eos;
  229. bool sample_separation_bos = !separate_with_bos;
  230. for (int64_t i=0; i<n_tokens; ++i) {
  231. llama_token token = eos;
  232. if (sample_offs >= sample_size && fill_with_next_samples) {
  233. if (!sample_separation_eos) {
  234. // insert eos token to separate samples
  235. sample_separation_eos = true;
  236. } else if (!sample_separation_bos) {
  237. // insert bos token to separate samples
  238. sample_separation_bos = true;
  239. token = bos;
  240. } else {
  241. // sample separation is done, continue with next sample
  242. sample_separation_eos = !separate_with_eos;
  243. sample_separation_bos = !separate_with_bos;
  244. sample_offs = 0;
  245. sample_idx = (example_id + used_samples) % samples_count;
  246. sample_begin = samples_begin[sample_idx];
  247. sample_size = samples_size[sample_idx];
  248. ++used_samples;
  249. }
  250. }
  251. // note: no else-if here
  252. if (sample_offs < sample_size) {
  253. token = clamp(train_data[sample_begin+sample_offs], 0, (llama_token) (n_vocab - 1));
  254. ++sample_offs;
  255. }
  256. ggml_set_f32_nd(target_probs, token, (int) i, (int) k, 0, +1.0f);
  257. if (i+1<n_tokens) {
  258. ggml_set_i32_nd(tokens_input, (int) (i + 1), (int) k, 0, 0, token);
  259. }
  260. }
  261. }
  262. return used_samples;
  263. }
  264. void mt19937_set_state(std::mt19937& rng, const std::string& rng_state) {
  265. std::stringstream s_rng_state;
  266. s_rng_state.imbue(std::locale::classic());
  267. s_rng_state.exceptions(std::stringstream::failbit);
  268. s_rng_state.str(rng_state);
  269. s_rng_state >> rng;
  270. }
  271. std::string mt19937_get_state(const std::mt19937& rng) {
  272. std::stringstream s_rng_state;
  273. s_rng_state.imbue(std::locale::classic());
  274. s_rng_state << rng;
  275. return s_rng_state.str();
  276. }
  277. std::string mt19937_seed_to_state(unsigned seed) {
  278. std::mt19937 rng(seed);
  279. return mt19937_get_state(rng);
  280. }
  281. std::string shuffle_samples(
  282. const std::string & rng_state,
  283. size_t * shuffled_offs,
  284. size_t * shuffled_begins,
  285. size_t * shuffled_sizes,
  286. const size_t * begins,
  287. const size_t * sizes,
  288. size_t count) {
  289. if (count == 0) return rng_state;
  290. std::mt19937 rng;
  291. mt19937_set_state(rng, rng_state);
  292. // sort indices by random value for each index
  293. std::vector<size_t> idcs;
  294. {
  295. std::vector<unsigned> rnd;
  296. idcs.resize(count);
  297. rnd.resize(count);
  298. for (unsigned i=0; i<count; ++i) {
  299. idcs[i] = i;
  300. rnd[i] = rng();
  301. }
  302. std::sort(idcs.begin(), idcs.end(), [&rnd](size_t a, size_t b){
  303. // stable sort for reproducibility
  304. return (rnd[a] == rnd[b]) ? (a < b) : (rnd[a] < rnd[b]);
  305. });
  306. }
  307. // create random offsets
  308. for (unsigned i=0; i<count; ++i) {
  309. shuffled_offs[i] = (size_t) ((sizes[idcs[i]] - 1) * ((double) rng() / (double) (rng.max()-1)));
  310. }
  311. // reorder begins and sizes by sorted indices
  312. for (unsigned i=0; i<count; ++i) {
  313. shuffled_begins[i] = begins[idcs[i]];
  314. }
  315. for (unsigned i=0; i<count; ++i) {
  316. shuffled_sizes[i] = sizes[idcs[i]];
  317. }
  318. return mt19937_get_state(rng);
  319. }
  320. size_t hash_combine(size_t h1, size_t h2) {
  321. return h1 ^ (h2 << 1);
  322. }
  323. size_t compute_samples_hash(const char* fn, const size_t* samples_begin, const size_t* samples_size, size_t sample_count) {
  324. std::hash<std::string> h_string;
  325. std::hash<unsigned long long> h_ull;
  326. size_t h = h_string(std::string(fn));
  327. h = hash_combine(h, h_ull((unsigned long long) sample_count));
  328. for (size_t i=0; i< sample_count; ++i) {
  329. h = hash_combine(h, h_ull((unsigned long long) samples_begin[i]));
  330. h = hash_combine(h, h_ull((unsigned long long) samples_size[i]));
  331. }
  332. return h;
  333. }
  334. std::string replace_str(const char * s, const char * needle, const char * replacement) {
  335. std::string str = s;
  336. size_t pos = str.find(needle);
  337. if (pos != std::string::npos) {
  338. str.replace(pos, strlen(needle), replacement);
  339. }
  340. return str;
  341. }
  342. void print_duration(double fmillis) {
  343. if (fmillis < 1000.0f) {
  344. printf("%.1fms", (float) fmillis);
  345. return;
  346. }
  347. const int64_t one_sec = 1000;
  348. const int64_t one_min = one_sec * 60;
  349. const int64_t one_hour = one_min * 60;
  350. const int64_t one_day = one_hour * 24;
  351. int64_t millis = (int64_t) fmillis;
  352. int64_t days = millis/one_day;
  353. int64_t hours = (millis - days*one_day)/one_hour;
  354. int64_t minutes = (millis - days*one_day - hours*one_hour)/one_min;
  355. int64_t seconds = (millis - days*one_day - hours*one_hour - minutes*one_min)/one_sec;
  356. // to print int64_t either cast to (long long int) or use macro PRId64 from <inttypes.h>
  357. if (days > 0) {
  358. printf("%lldd ", (long long int) days);
  359. }
  360. printf("%02lld:%02lld:%02lld", (long long int) hours, (long long int) minutes, (long long int) seconds);
  361. }
  362. float cosine_decay(int64_t step, int64_t decay_steps, float minimum) {
  363. if (step > decay_steps) {
  364. step = decay_steps;
  365. }
  366. const float cosine_decay = 0.50f*(1.0f + cosf(3.14159265359f*step/decay_steps));
  367. const float decay = (1 - minimum)*cosine_decay + minimum;
  368. return decay;
  369. }
  370. float cosine_decay_restart(int64_t step, int64_t decay_steps, float minimum, float restart_step_mult) {
  371. while (step > decay_steps) {
  372. step -= decay_steps;
  373. decay_steps = (int64_t) (restart_step_mult * decay_steps);
  374. }
  375. return cosine_decay(step, decay_steps, minimum);
  376. }
  377. float learning_schedule(
  378. int64_t step,
  379. int64_t warmup_steps,
  380. int64_t cos_decay_steps,
  381. float learning_rate,
  382. float overall_minimum,
  383. float cos_decay_minimum,
  384. float cos_decay_restart_step_mult,
  385. bool enable_restart) {
  386. float result =
  387. (step < warmup_steps)
  388. ? (float) step / (float) warmup_steps
  389. : enable_restart
  390. ? cosine_decay_restart(
  391. step - warmup_steps,
  392. cos_decay_steps,
  393. cos_decay_minimum,
  394. cos_decay_restart_step_mult)
  395. : cosine_decay(
  396. step,
  397. cos_decay_steps,
  398. cos_decay_minimum);
  399. float min = overall_minimum / learning_rate;
  400. result = min + result * (1.0f - min);
  401. return result;
  402. }
  403. static bool are_same_layout(struct ggml_tensor * a, struct ggml_tensor * b) {
  404. GGML_ASSERT(a != NULL);
  405. GGML_ASSERT(b != NULL);
  406. GGML_ASSERT(a->type == b->type);
  407. GGML_ASSERT(ggml_are_same_shape(a, b));
  408. GGML_ASSERT(ggml_is_contiguous(a) && ggml_is_contiguous(b));
  409. return true;
  410. }
  411. void copy_tensor_by_name(struct ggml_tensor * dst, struct ggml_context * ctx, const char * name) {
  412. if (dst == NULL) {
  413. return;
  414. }
  415. struct ggml_tensor * t = ggml_get_tensor(ctx, name);
  416. GGML_ASSERT(are_same_layout(dst, t));
  417. memcpy(dst->data, t->data, ggml_nbytes(t));
  418. if (strlen(ggml_get_name(dst)) == 0) {
  419. ggml_set_name(dst, name);
  420. }
  421. }
  422. // gguf constants
  423. static const char * LLM_KV_OPTIMIZER_TYPE = "optimizer.type";
  424. static const char * LLM_KV_OPTIMIZER_TYPE_ADAM = "adam";
  425. static const char * LLM_KV_OPTIMIZER_TYPE_LBFGS = "lbfgs";
  426. static const char * LLM_KV_OPTIMIZER_FILE_VERSION = "optimizer.file_version";
  427. static const char * LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT = "optimizer.convergence_past_count";
  428. static const char * LLM_KV_OPTIMIZER_PARAMETER_COUNT = "optimizer.parameter_count";
  429. static const char * LLM_KV_OPTIMIZER_ITERATION_COUNT = "optimizer.iteration_count";
  430. static const char * LLM_KV_OPTIMIZER_JUST_INITIALIZED = "optimizer.just_initialized";
  431. static const char * LLM_KV_OPTIMIZER_ADAM_BEST_LOSS = "optimizer.adam.best_loss";
  432. static const char * LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS = "optimizer.adam.previous_loss";
  433. static const char * LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT = "optimizer.adam.no_improvement_count";
  434. static const char * LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT = "optimizer.lbfgs.approx_hessian_count";
  435. static const char * LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS = "optimizer.lbfgs.best_loss";
  436. static const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP = "optimizer.lbfgs.line_search_step";
  437. static const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J = "optimizer.lbfgs.line_search_j";
  438. static const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K = "optimizer.lbfgs.line_search_k";
  439. static const char * LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END = "optimizer.lbfgs.line_search_end";
  440. static const char * LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT = "optimizer.lbfgs.no_improvement_count";
  441. static const char * LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS = "optimizer.adam.first_moments";
  442. static const char * LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS = "optimizer.adam.second_moments";
  443. static const char * LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES = "optimizer.adam.past_loss_values";
  444. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS = "optimizer.lbfgs.current_parameters";
  445. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS = "optimizer.lbfgs.previous_parameters";
  446. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS = "optimizer.lbfgs.current_gradients";
  447. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS = "optimizer.lbfgs.previous_gradients";
  448. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION = "optimizer.lbfgs.search_direction";
  449. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES = "optimizer.lbfgs.past_loss_values";
  450. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA = "optimizer.lbfgs.memory_alpha";
  451. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS = "optimizer.lbfgs.memory_ys";
  452. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S = "optimizer.lbfgs.memory_s";
  453. static const char * LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y = "optimizer.lbfgs.memory_y";
  454. static const char * LLM_KV_TRAINING_FILE_VERSION = "training.file_version";
  455. static const char * LLM_KV_TRAINING_ITERATION_COUNT = "training.iteration_count";
  456. static const char * LLM_KV_TRAINING_SAMPLE_COUNT = "training.sample_count";
  457. static const char * LLM_KV_TRAINING_TOKEN_COUNT = "training.token_count";
  458. static const char * LLM_KV_TRAINING_EPOCH_COUNT = "training.epoch_count";
  459. static const char * LLM_KV_TRAINING_SHUFFLE_SAMPLES_HASH = "training.shuffle.samples_hash";
  460. static const char * LLM_KV_TRAINING_SHUFFLE_RNG_STATE = "training.shuffle.rng_state";
  461. static const char * LLM_KV_TRAINING_SHUFFLE_SAMPLE_COUNT = "training.shuffle.sample_count";
  462. static const char * LLM_KV_TRAINING_SHUFFLE_NEXT_SAMPLE = "training.shuffle.next_sample";
  463. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  464. { \
  465. const std::string skey(key); \
  466. const int kid = gguf_find_key(ctx, skey.c_str()); \
  467. if (kid >= 0) { \
  468. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  469. if (ktype != (type)) { \
  470. die_fmt("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype)); \
  471. } \
  472. (dst) = func(ctx, kid); \
  473. } else if (req) { \
  474. die_fmt("key not found in model: %s", skey.c_str()); \
  475. } \
  476. }
  477. void load_opt_context_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct ggml_opt_context * opt) {
  478. // NOTE: gguf_context must be initialized with f_ggml_ctx and no_alloc=false, otherwise tensor data can not be read
  479. uint32_t file_version;
  480. GGUF_GET_KEY(fctx, file_version, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_FILE_VERSION);
  481. GGML_ASSERT(file_version == 0);
  482. GGUF_GET_KEY(fctx, opt->params.past, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT);
  483. GGUF_GET_KEY(fctx, opt->iter, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_ITERATION_COUNT);
  484. GGUF_GET_KEY(fctx, opt->just_initialized, gguf_get_val_bool, GGUF_TYPE_BOOL, true, LLM_KV_OPTIMIZER_JUST_INITIALIZED);
  485. uint64_t nx;
  486. GGUF_GET_KEY(fctx, nx, gguf_get_val_u64, GGUF_TYPE_UINT64, true, LLM_KV_OPTIMIZER_PARAMETER_COUNT);
  487. opt->nx = (size_t) nx;
  488. // don't call ggml_opt_init until optimizer type and optimizer specific parameters are know
  489. std::string opt_type;
  490. GGUF_GET_KEY(fctx, opt_type, gguf_get_val_str, GGUF_TYPE_STRING, true, LLM_KV_OPTIMIZER_TYPE);
  491. if (opt_type == LLM_KV_OPTIMIZER_TYPE_ADAM) {
  492. opt->params.type = GGML_OPT_ADAM;
  493. GGUF_GET_KEY(fctx, opt->adam.fx_best, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_ADAM_BEST_LOSS);
  494. GGUF_GET_KEY(fctx, opt->adam.fx_prev, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS);
  495. GGUF_GET_KEY(fctx, opt->adam.n_no_improvement, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT);
  496. ggml_opt_init(opt->ctx, opt, opt->params, opt->nx);
  497. copy_tensor_by_name(opt->adam.m, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS);
  498. copy_tensor_by_name(opt->adam.v, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS);
  499. copy_tensor_by_name(opt->adam.pf, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES);
  500. } else if (opt_type == LLM_KV_OPTIMIZER_TYPE_LBFGS) {
  501. opt->params.type = GGML_OPT_LBFGS;
  502. GGUF_GET_KEY(fctx, opt->params.lbfgs.m, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT);
  503. GGUF_GET_KEY(fctx, opt->lbfgs.fx_best, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS);
  504. GGUF_GET_KEY(fctx, opt->lbfgs.step, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP);
  505. GGUF_GET_KEY(fctx, opt->lbfgs.j, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J);
  506. GGUF_GET_KEY(fctx, opt->lbfgs.k, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K);
  507. GGUF_GET_KEY(fctx, opt->lbfgs.end, gguf_get_val_i32, GGUF_TYPE_INT32, true, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END);
  508. GGUF_GET_KEY(fctx, opt->lbfgs.n_no_improvement, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT);
  509. ggml_opt_init(opt->ctx, opt, opt->params, opt->nx);
  510. copy_tensor_by_name(opt->lbfgs.x, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS);
  511. copy_tensor_by_name(opt->lbfgs.xp, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS);
  512. copy_tensor_by_name(opt->lbfgs.g, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS);
  513. copy_tensor_by_name(opt->lbfgs.gp, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS);
  514. copy_tensor_by_name(opt->lbfgs.d, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION);
  515. copy_tensor_by_name(opt->lbfgs.pf, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES);
  516. copy_tensor_by_name(opt->lbfgs.lmal, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA);
  517. copy_tensor_by_name(opt->lbfgs.lmys, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS);
  518. copy_tensor_by_name(opt->lbfgs.lms, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S);
  519. copy_tensor_by_name(opt->lbfgs.lmy, f_ggml_ctx, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y);
  520. } else {
  521. die("unknown optimizer type\n");
  522. }
  523. }
  524. void save_opt_context_gguf(struct gguf_context * fctx, struct ggml_opt_context * opt) {
  525. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_FILE_VERSION, 0);
  526. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_CONVERGENCE_PAST_COUNT, opt->params.past);
  527. gguf_set_val_u64(fctx, LLM_KV_OPTIMIZER_PARAMETER_COUNT, (uint64_t) opt->nx);
  528. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_ITERATION_COUNT, opt->iter);
  529. gguf_set_val_bool(fctx, LLM_KV_OPTIMIZER_JUST_INITIALIZED, opt->just_initialized);
  530. switch (opt->params.type) {
  531. case GGML_OPT_ADAM:
  532. {
  533. gguf_set_val_str(fctx, LLM_KV_OPTIMIZER_TYPE, LLM_KV_OPTIMIZER_TYPE_ADAM);
  534. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_ADAM_BEST_LOSS, opt->adam.fx_best);
  535. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_ADAM_PREVIOUS_LOSS, opt->adam.fx_prev);
  536. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_ADAM_NO_IMPROVEMENT_COUNT, opt->adam.n_no_improvement);
  537. ggml_set_name(opt->adam.m, LLM_TENSOR_OPTIMIZER_ADAM_FIRST_MOMENTS);
  538. ggml_set_name(opt->adam.v, LLM_TENSOR_OPTIMIZER_ADAM_SECOND_MOMENTS);
  539. if (opt->adam.pf) {
  540. ggml_set_name(opt->adam.pf, LLM_TENSOR_OPTIMIZER_ADAM_PAST_LOSS_VALUES);
  541. }
  542. gguf_add_tensor(fctx, opt->adam.m);
  543. gguf_add_tensor(fctx, opt->adam.v);
  544. if (opt->adam.pf) {
  545. gguf_add_tensor(fctx, opt->adam.pf);
  546. }
  547. } break;
  548. case GGML_OPT_LBFGS:
  549. {
  550. gguf_set_val_str(fctx, LLM_KV_OPTIMIZER_TYPE, LLM_KV_OPTIMIZER_TYPE_LBFGS);
  551. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_LBFGS_APPROX_HESSIAN_COUNT, opt->params.lbfgs.m);
  552. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_LBFGS_BEST_LOSS, opt->lbfgs.fx_best);
  553. gguf_set_val_f32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_STEP, opt->lbfgs.step);
  554. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_J, opt->lbfgs.j);
  555. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_K, opt->lbfgs.k);
  556. gguf_set_val_i32(fctx, LLM_KV_OPTIMIZER_LBFGS_LINE_SEARCH_END, opt->lbfgs.end);
  557. gguf_set_val_u32(fctx, LLM_KV_OPTIMIZER_LBFGS_NO_IMPROVEMENT_COUNT, opt->lbfgs.n_no_improvement);
  558. ggml_set_name(opt->lbfgs.x, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_PARAMETERS);
  559. ggml_set_name(opt->lbfgs.xp, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_PARAMETERS);
  560. ggml_set_name(opt->lbfgs.g, LLM_TENSOR_OPTIMIZER_LBFGS_CURRENT_GRADIENTS);
  561. ggml_set_name(opt->lbfgs.gp, LLM_TENSOR_OPTIMIZER_LBFGS_PREVIOUS_GRADIENTS);
  562. ggml_set_name(opt->lbfgs.d, LLM_TENSOR_OPTIMIZER_LBFGS_SEARCH_DIRECTION);
  563. if (opt->lbfgs.pf) {
  564. ggml_set_name(opt->lbfgs.pf, LLM_TENSOR_OPTIMIZER_LBFGS_PAST_LOSS_VALUES);
  565. }
  566. ggml_set_name(opt->lbfgs.lmal, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_ALPHA);
  567. ggml_set_name(opt->lbfgs.lmys, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_YS);
  568. ggml_set_name(opt->lbfgs.lms, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_S);
  569. ggml_set_name(opt->lbfgs.lmy, LLM_TENSOR_OPTIMIZER_LBFGS_MEMORY_Y);
  570. gguf_add_tensor(fctx, opt->lbfgs.x);
  571. gguf_add_tensor(fctx, opt->lbfgs.xp);
  572. gguf_add_tensor(fctx, opt->lbfgs.g);
  573. gguf_add_tensor(fctx, opt->lbfgs.gp);
  574. gguf_add_tensor(fctx, opt->lbfgs.d);
  575. if (opt->lbfgs.pf) {
  576. gguf_add_tensor(fctx, opt->lbfgs.pf);
  577. }
  578. gguf_add_tensor(fctx, opt->lbfgs.lmal);
  579. gguf_add_tensor(fctx, opt->lbfgs.lmys);
  580. gguf_add_tensor(fctx, opt->lbfgs.lms);
  581. gguf_add_tensor(fctx, opt->lbfgs.lmy);
  582. } break;
  583. }
  584. }
  585. bool load_train_state_gguf(struct gguf_context * fctx, struct ggml_context * f_ggml_ctx, struct train_state * train) {
  586. if (gguf_find_key(fctx, LLM_KV_TRAINING_FILE_VERSION) < 0) {
  587. return false;
  588. }
  589. uint32_t file_version;
  590. GGUF_GET_KEY(fctx, file_version, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_FILE_VERSION);
  591. GGML_ASSERT(file_version <= 1);
  592. if (file_version == 0) {
  593. GGUF_GET_KEY(fctx, train->train_its, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_ITERATION_COUNT);
  594. GGUF_GET_KEY(fctx, train->train_samples, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_SAMPLE_COUNT);
  595. GGUF_GET_KEY(fctx, train->train_tokens, gguf_get_val_u32, GGUF_TYPE_UINT32, true, LLM_KV_TRAINING_TOKEN_COUNT);
  596. } else if (file_version == 1) {
  597. GGUF_GET_KEY(fctx, train->train_its, gguf_get_val_u64, GGUF_TYPE_UINT64, true, LLM_KV_TRAINING_ITERATION_COUNT);
  598. GGUF_GET_KEY(fctx, train->train_samples, gguf_get_val_u64, GGUF_TYPE_UINT64, true, LLM_KV_TRAINING_SAMPLE_COUNT);
  599. GGUF_GET_KEY(fctx, train->train_tokens, gguf_get_val_u64, GGUF_TYPE_UINT64, true, LLM_KV_TRAINING_TOKEN_COUNT);
  600. GGUF_GET_KEY(fctx, train->train_epochs, gguf_get_val_u64, GGUF_TYPE_UINT64, true, LLM_KV_TRAINING_EPOCH_COUNT);
  601. GGUF_GET_KEY(fctx, train->shuffle_samples_hash, gguf_get_val_u64, GGUF_TYPE_UINT64, false, LLM_KV_TRAINING_SHUFFLE_SAMPLES_HASH);
  602. GGUF_GET_KEY(fctx, train->shuffle_rng_state_current, gguf_get_val_str, GGUF_TYPE_STRING, false, LLM_KV_TRAINING_SHUFFLE_RNG_STATE);
  603. GGUF_GET_KEY(fctx, train->shuffle_sample_count, gguf_get_val_u64, GGUF_TYPE_UINT64, false, LLM_KV_TRAINING_SHUFFLE_SAMPLE_COUNT);
  604. GGUF_GET_KEY(fctx, train->shuffle_next_sample, gguf_get_val_u64, GGUF_TYPE_UINT64, false, LLM_KV_TRAINING_SHUFFLE_NEXT_SAMPLE);
  605. }
  606. load_opt_context_gguf(fctx, f_ggml_ctx, train->opt);
  607. return true;
  608. }
  609. void save_train_state_gguf(struct gguf_context * fctx, struct train_state * train) {
  610. gguf_set_val_u32(fctx, LLM_KV_TRAINING_FILE_VERSION, 1);
  611. gguf_set_val_u64(fctx, LLM_KV_TRAINING_ITERATION_COUNT, train->train_its);
  612. gguf_set_val_u64(fctx, LLM_KV_TRAINING_SAMPLE_COUNT, train->train_samples);
  613. gguf_set_val_u64(fctx, LLM_KV_TRAINING_TOKEN_COUNT, train->train_tokens);
  614. gguf_set_val_u64(fctx, LLM_KV_TRAINING_EPOCH_COUNT, train->train_epochs);
  615. gguf_set_val_u64(fctx, LLM_KV_TRAINING_SHUFFLE_SAMPLES_HASH, (uint64_t) train->shuffle_samples_hash);
  616. gguf_set_val_str(fctx, LLM_KV_TRAINING_SHUFFLE_RNG_STATE, train->shuffle_rng_state_current.c_str());
  617. gguf_set_val_u64(fctx, LLM_KV_TRAINING_SHUFFLE_SAMPLE_COUNT, (uint64_t) train->shuffle_sample_count);
  618. gguf_set_val_u64(fctx, LLM_KV_TRAINING_SHUFFLE_NEXT_SAMPLE, (uint64_t) train->shuffle_next_sample);
  619. save_opt_context_gguf(fctx, train->opt);
  620. }
  621. struct llama_file {
  622. // use FILE * so we don't have to re-open the file to mmap
  623. FILE * fp;
  624. size_t size;
  625. llama_file(const char * fname, const char * mode) {
  626. fp = std::fopen(fname, mode);
  627. if (fp == NULL) {
  628. size = 0;
  629. } else {
  630. seek(0, SEEK_END);
  631. size = tell();
  632. seek(0, SEEK_SET);
  633. }
  634. }
  635. size_t tell() const {
  636. #ifdef _WIN32
  637. __int64 ret = _ftelli64(fp);
  638. #else
  639. long ret = std::ftell(fp);
  640. #endif
  641. GGML_ASSERT(ret != -1); // this really shouldn't fail
  642. return (size_t) ret;
  643. }
  644. void seek(size_t offset, int whence) {
  645. #ifdef _WIN32
  646. int ret = _fseeki64(fp, (__int64) offset, whence);
  647. #else
  648. int ret = std::fseek(fp, (long) offset, whence);
  649. #endif
  650. GGML_ASSERT(ret == 0); // same
  651. }
  652. void read_raw(void * ptr, size_t size) {
  653. if (size == 0) {
  654. return;
  655. }
  656. errno = 0;
  657. std::size_t ret = std::fread(ptr, size, 1, fp);
  658. if (ferror(fp)) {
  659. die_fmt("read error: %s", strerror(errno));
  660. }
  661. if (ret != 1) {
  662. die("unexpectedly reached end of file");
  663. }
  664. }
  665. std::uint32_t read_u32() {
  666. std::uint32_t ret;
  667. read_raw(&ret, sizeof(ret));
  668. return ret;
  669. }
  670. std::string read_string(std::uint32_t len) {
  671. std::vector<char> chars(len);
  672. read_raw(chars.data(), len);
  673. return std::string(chars.data(), len);
  674. }
  675. void write_raw(const void * ptr, size_t size) {
  676. if (size == 0) {
  677. return;
  678. }
  679. errno = 0;
  680. size_t ret = std::fwrite(ptr, size, 1, fp);
  681. if (ret != 1) {
  682. die_fmt("write error: %s", strerror(errno));
  683. }
  684. }
  685. void write_u32(std::uint32_t val) {
  686. write_raw(&val, sizeof(val));
  687. }
  688. ~llama_file() {
  689. if (fp) {
  690. std::fclose(fp);
  691. }
  692. }
  693. };
  694. static size_t utf8_len(char src) {
  695. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  696. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  697. return lookup[highbits];
  698. }
  699. // mark each byte with its utf8 unit number.
  700. // returns the number of utf8 characters.
  701. // e.g. when bytes == '\x61\xD0\xB0\x62',
  702. // then utf8_units will become [0,0,1,0]
  703. // utf8_nunits will become [1,2,2,1] and 3 is returned.
  704. // bytes where utf8_units is zero, are the begin of an utf8 character.
  705. static size_t mark_utf8_units(const char* bytes, int * utf8_units, int * utf8_nunits, size_t count) {
  706. size_t offs = 0;
  707. size_t count_utf8 = 0;
  708. while(offs < count) {
  709. int len = (int) utf8_len(bytes[offs]);
  710. for (int i=0; i<len; ++i) {
  711. utf8_units[offs+i] = i;
  712. utf8_nunits[offs+i] = len;
  713. }
  714. offs += len;
  715. ++count_utf8;
  716. }
  717. return count_utf8;
  718. }
  719. size_t tokenize_file(
  720. struct llama_context * lctx,
  721. const char * filename,
  722. const std::string & sample_start,
  723. bool include_sample_start,
  724. bool overlapping_samples,
  725. unsigned context_length,
  726. std::vector<llama_token> & out_tokens,
  727. std::vector<size_t> & out_samples_begin,
  728. std::vector<size_t> & out_samples_size) {
  729. struct llama_file f(filename, "rb");
  730. if (f.size == 0) {
  731. out_tokens.clear();
  732. out_samples_begin.clear();
  733. out_samples_size.clear();
  734. printf("%s: warning: empty or not existing training data file '%s'\n",
  735. __func__, filename);
  736. return out_tokens.size();
  737. }
  738. // account for possible leading whitespace that will be added by tokenizer
  739. // e.g. '\t' will be tokenized by llama spm tokenizer to [29871, 12]
  740. const int n_max_tokens_overhead = 1;
  741. std::vector<char> buf;
  742. buf.resize(f.size);
  743. f.read_raw(buf.data(), f.size);
  744. std::vector<int> utf8_units;
  745. std::vector<int> utf8_nunits;
  746. utf8_units.resize(buf.size());
  747. utf8_nunits.resize(buf.size());
  748. mark_utf8_units(buf.data(), utf8_units.data(), utf8_nunits.data(), buf.size());
  749. if (sample_start.size() == 0) {
  750. // tokenize all data at once
  751. out_tokens.resize(buf.size() + n_max_tokens_overhead);
  752. int n_tokens = llama_tokenize(
  753. llama_get_model(lctx),
  754. buf.data(),
  755. (int) buf.size(),
  756. out_tokens.data(),
  757. (int) out_tokens.size(),
  758. false, false);
  759. if (n_tokens < 0) {
  760. out_tokens.resize(-n_tokens);
  761. n_tokens = llama_tokenize(
  762. llama_get_model(lctx),
  763. buf.data(),
  764. (int) buf.size(),
  765. out_tokens.data(),
  766. (int) out_tokens.size(),
  767. false, false);
  768. }
  769. if (n_tokens >= 0) {
  770. out_tokens.resize(n_tokens);
  771. }
  772. // generate sample starts at all token positions
  773. out_samples_begin.clear();
  774. out_samples_begin.push_back(0);
  775. out_samples_size.push_back(std::min((size_t) context_length, out_tokens.size()));
  776. size_t end = (out_tokens.size() >= context_length) ? (out_tokens.size() - context_length) : 0;
  777. for (size_t sample_begin = 1; sample_begin < end; ++sample_begin) {
  778. out_samples_begin.push_back(sample_begin);
  779. out_samples_size.push_back(context_length);
  780. }
  781. } else {
  782. // split data into samples and tokenize each sample
  783. std::string data_str(buf.data(), buf.size());
  784. out_samples_begin.clear();
  785. out_samples_size.clear();
  786. out_tokens.clear();
  787. // find all positions of pattern sample_start
  788. size_t sample_begin = data_str.find(sample_start, 0);
  789. while (sample_begin != std::string::npos) {
  790. out_samples_begin.push_back(sample_begin);
  791. const size_t search_start = sample_begin + sample_start.size();
  792. sample_begin = data_str.find(sample_start, search_start);
  793. }
  794. if (out_samples_begin.size() == 0) {
  795. printf("%s: warning: sample start pattern '%s' not found. inserting single sample at data begin\n",
  796. __func__, sample_start.c_str());
  797. out_samples_begin.push_back(0);
  798. }
  799. out_samples_size.resize(out_samples_begin.size(), 0);
  800. std::vector<char> buf_sample;
  801. std::vector<llama_token> tok_sample;
  802. const size_t sample_begin_offset = (include_sample_start ? 0 : sample_start.size());
  803. size_t found_too_big_sample = 0;
  804. size_t found_too_small_sample = 0;
  805. size_t found_empty_sample = 0;
  806. size_t found_min_sample_size = SIZE_MAX;
  807. size_t found_max_sample_size = 0;
  808. size_t max_token_text_size = 0;
  809. int n_vocab = llama_n_vocab(llama_get_model(lctx));
  810. for (llama_token token=0; token < n_vocab; ++token) {
  811. max_token_text_size = std::max(
  812. max_token_text_size,
  813. strlen(llama_token_get_text(llama_get_model(lctx), token)));
  814. }
  815. // upper bound of context byte length.
  816. // strings with this byte length should always tokenize to at least context_length tokens.
  817. size_t context_byte_len = max_token_text_size*context_length;
  818. for (unsigned i=0; i<out_samples_begin.size(); ++i) {
  819. // determine sample begin and end from pattern positions
  820. size_t sample_begin = out_samples_begin[i] + sample_begin_offset;
  821. size_t sample_end = overlapping_samples
  822. ? std::min(
  823. data_str.size(),
  824. sample_begin + context_byte_len)
  825. : (i+1 < out_samples_begin.size()
  826. ? out_samples_begin[i+1]
  827. : data_str.size());
  828. if (sample_end < utf8_units.size() && utf8_units[sample_end] > 0) {
  829. // sample end is in the middle of an utf8 character.
  830. // advance sample_end to the begin of the next utf8 character.
  831. sample_end += utf8_nunits[sample_end] - utf8_units[sample_end];
  832. }
  833. size_t sample_size = sample_end - sample_begin;
  834. if (sample_size == 0) {
  835. ++found_empty_sample;
  836. }
  837. if (sample_size > 0) {
  838. // llama_tokenize expects zero terminated string,
  839. // copy sample into buffer and zero terminate it.
  840. buf_sample.resize(sample_size);
  841. memcpy(buf_sample.data(), data_str.data() + sample_begin, sample_size);
  842. // printf("sample: '%s'\n", buf_sample.data());
  843. // tokenize the sample
  844. tok_sample.resize(buf_sample.size() + n_max_tokens_overhead);
  845. int n_tokens = llama_tokenize(llama_get_model(lctx),
  846. buf_sample.data(),
  847. (int) buf_sample.size(),
  848. tok_sample.data(),
  849. (int) tok_sample.size(),
  850. false, false);
  851. if (n_tokens < 0) {
  852. tok_sample.resize(-n_tokens);
  853. n_tokens = llama_tokenize(llama_get_model(lctx),
  854. buf_sample.data(),
  855. (int) buf_sample.size(),
  856. tok_sample.data(),
  857. (int) tok_sample.size(),
  858. false, false);
  859. GGML_ASSERT(n_tokens >= 0);
  860. }
  861. GGML_ASSERT(n_tokens <= (int) tok_sample.size());
  862. if ((size_t) n_tokens > context_length) {
  863. ++found_too_big_sample;
  864. } else if ((size_t) n_tokens < context_length) {
  865. ++found_too_small_sample;
  866. }
  867. found_max_sample_size = std::max(found_max_sample_size, (size_t) n_tokens);
  868. found_min_sample_size = std::min(found_min_sample_size, (size_t) n_tokens);
  869. // write out tokens, start and size of sample
  870. // overwrite the string start position with the token start position
  871. out_samples_begin[i] = out_tokens.size();
  872. out_samples_size[i] = (size_t) n_tokens;
  873. out_tokens.insert(out_tokens.end(), tok_sample.begin(), tok_sample.begin() + n_tokens);
  874. } else {
  875. out_samples_begin[i] = out_tokens.size();
  876. out_samples_size[i] = 0;
  877. }
  878. }
  879. if (found_too_big_sample > 0) {
  880. printf("%s: warning: found %zu samples (max length %zu) that exceed context length of %u. samples will be cut off.\n",
  881. __func__, found_too_big_sample, found_max_sample_size, context_length);
  882. }
  883. if (found_too_small_sample > 0) {
  884. printf("%s: warning: found %zu samples (min length %zu) that are shorter than context length of %u.\n",
  885. __func__, found_too_small_sample, found_min_sample_size, context_length);
  886. }
  887. if (found_empty_sample) {
  888. printf("%s: warning: found %zu empty samples.\n",
  889. __func__, found_empty_sample);
  890. }
  891. }
  892. printf("%s: total number of samples: %zu\n",
  893. __func__, out_samples_begin.size());
  894. GGML_ASSERT(out_samples_begin.size() == out_samples_size.size());
  895. return out_tokens.size();
  896. }
  897. std::string get_train_filename(const char * filename, const char * pattern_it, const char * latest, int64_t iteration) {
  898. std::string sit = (iteration >= 0) ? std::to_string(iteration) : std::string(latest);
  899. return replace_str(filename, pattern_it, sit.c_str());
  900. }
  901. struct train_params_common get_default_train_params_common() {
  902. struct train_params_common params;
  903. params.fn_train_data = "shakespeare.txt";
  904. params.fn_checkpoint_in = "checkpoint.gguf";
  905. params.fn_checkpoint_out = "checkpoint-ITERATION.gguf";
  906. params.pattern_fn_it = "ITERATION";
  907. params.fn_latest = "LATEST";
  908. params.print_usage = false;
  909. params.save_every = 10;
  910. params.seed = -1;
  911. params.n_ctx = 128;
  912. params.n_threads = 6;
  913. params.n_batch = 8;
  914. params.n_gradient_accumulation = 1;
  915. params.n_epochs = -1;
  916. params.n_gpu_layers = 0;
  917. params.custom_n_ctx = false;
  918. params.use_flash = true;
  919. params.use_checkpointing = true;
  920. params.sample_start = "";
  921. params.include_sample_start = false;
  922. params.escape = false;
  923. params.overlapping_samples = false;
  924. params.fill_with_next_samples = false;
  925. params.separate_with_eos = false;
  926. params.separate_with_bos = true;
  927. params.sample_random_offsets = false;
  928. params.force_reshuffle = false;
  929. params.opt_past = 0;
  930. params.opt_delta = 1e-5f;
  931. params.opt_max_no_improvement = 0;
  932. params.warmup = 100;
  933. params.cos_decay_steps = 1000;
  934. params.cos_decay_restart = 1.1f;
  935. params.cos_decay_min = 0.1f;
  936. params.enable_restart = false;
  937. params.adam_n_iter = 256;
  938. params.adam_alpha = 1e-3f;
  939. params.adam_min_alpha = 0;
  940. params.adam_decay = 1e-1f;
  941. params.adam_decay_min_ndim = 2;
  942. params.adam_beta1 = 0.9f;
  943. params.adam_beta2 = 0.999f;
  944. params.adam_gclip = 1.0f;
  945. params.adam_eps_f = 0.0f;
  946. return params;
  947. }
  948. void print_common_train_usage(int /*argc*/, char ** /*argv*/, const struct train_params_common * params) {
  949. // fprintf(stderr, "usage: %s [options]\n", argv[0]);
  950. // fprintf(stderr, "\n");
  951. // fprintf(stderr, "options:\n");
  952. // fprintf(stderr, " -h, --help show this help message and exit\n");
  953. fprintf(stderr, " --train-data FNAME path from which to load training data (default '%s')\n", params->fn_train_data);
  954. fprintf(stderr, " --checkpoint-in FNAME path from which to load training checkpoint (default '%s')\n", params->fn_checkpoint_in);
  955. fprintf(stderr, " --checkpoint-out FNAME path to save training checkpoint (default '%s')\n", params->fn_checkpoint_out);
  956. fprintf(stderr, " --pattern-fn-it STR pattern in output filenames to be replaced by iteration number (default '%s')\n", params->pattern_fn_it);
  957. fprintf(stderr, " --fn-latest STR string to use instead of iteration number for saving latest output (default '%s')\n", params->fn_latest);
  958. fprintf(stderr, " --save-every N save checkpoint and lora every N iterations. Disabled when N <= 0. (default '%d')\n", params->save_every);
  959. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for -1)\n");
  960. fprintf(stderr, " -c N, --ctx N Context size used during training (default %d)\n", params->n_ctx);
  961. fprintf(stderr, " -t N, --threads N Number of threads (default %d)\n", params->n_threads);
  962. fprintf(stderr, " -b N, --batch N Parallel batch size (default %d)\n", params->n_batch);
  963. fprintf(stderr, " --grad-acc N Number of gradient accumulation steps (simulates larger batch size of batch*gradacc) (default %d)\n", params->n_gradient_accumulation);
  964. fprintf(stderr, " --sample-start STR Sets the starting point for samples after the specified pattern. If empty use every token position as sample start. (default '%s')\n", params->sample_start.c_str());
  965. fprintf(stderr, " --include-sample-start Include the sample start in the samples. (default off)\n");
  966. fprintf(stderr, " --escape process sample start escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  967. fprintf(stderr, " --overlapping-samples Samples my overlap, will include sample-start of second and following samples. When off, samples will end at begin of next sample. (default off)\n");
  968. fprintf(stderr, " --fill-with-next-samples Samples shorter than context length will be followed by the next (shuffled) samples. (default off)\n");
  969. fprintf(stderr, " --separate-with-eos When fill-with-next-samples, insert end-of-sequence token between samples.%s\n", params->separate_with_eos ? " (default)" : "");
  970. fprintf(stderr, " --separate-with-bos When fill-with-next-samples, insert begin-of-sequence token between samples.%s\n", params->separate_with_bos ? " (default)" : "");
  971. fprintf(stderr, " --no-separate-with-eos When fill-with-next-samples, don't insert end-of-sequence token between samples.%s\n", !params->separate_with_eos ? " (default)" : "");
  972. fprintf(stderr, " --no-separate-with-bos When fill-with-next-samples, don't insert begin-of-sequence token between samples.%s\n", !params->separate_with_bos ? " (default)" : "");
  973. fprintf(stderr, " --sample-random-offsets Use samples beginning at random offsets. Together with fill-with-next-samples this may help for training endless text generation.%s\n", params->sample_random_offsets ? " (default)" : "");
  974. fprintf(stderr, " --force-reshuffle Force a reshuffling of data at program start, otherwise the shuffling of loaded checkpoint is resumed.\n");
  975. fprintf(stderr, " --no-flash Don't use flash attention \n");
  976. fprintf(stderr, " --use-flash Use flash attention (default)\n");
  977. fprintf(stderr, " --no-checkpointing Don't use gradient checkpointing\n");
  978. fprintf(stderr, " --use-checkpointing Use gradient checkpointing (default)\n");
  979. fprintf(stderr, " --warmup N Only for Adam optimizer. Number of warmup steps (default %d)\n", params->warmup);
  980. fprintf(stderr, " --cos-decay-steps N Only for Adam optimizer. Number of cosine decay steps (default %d)\n", params->cos_decay_steps);
  981. fprintf(stderr, " --cos-decay-restart N Only for Adam optimizer. Increase of cosine decay steps after restart (default %f)\n", params->cos_decay_restart);
  982. fprintf(stderr, " --cos-decay-min N Only for Adam optimizer. Cosine decay minimum (default %f)\n", params->cos_decay_min);
  983. fprintf(stderr, " --enable-restart N Only for Adam optimizer. Enable restarts of cos-decay %s\n", params->enable_restart ? "(default)" : "");
  984. fprintf(stderr, " --disable-restart N Only for Adam optimizer. Disable restarts of cos-decay %s\n", !params->enable_restart ? "(default)" : "");
  985. fprintf(stderr, " --opt-past N Number of optimization iterations to track for delta convergence test. Disabled when zero. (default %d)\n", params->opt_past);
  986. fprintf(stderr, " --opt-delta N Maximum delta for delta convergence test. Disabled when <= zero. (default %f)\n", params->opt_delta);
  987. fprintf(stderr, " --opt-max-no-improvement N Maximum number of optimization iterations with no improvement. Disabled when <= zero. (default %d)\n", params->opt_max_no_improvement);
  988. fprintf(stderr, " --epochs N Maximum number epochs to process. (default %d)\n", params->n_epochs);
  989. fprintf(stderr, " --adam-iter N Maximum number of Adam optimization iterations for each batch (default %d)\n", params->adam_n_iter);
  990. fprintf(stderr, " --adam-alpha N Adam learning rate alpha (default %f)\n", params->adam_alpha);
  991. fprintf(stderr, " --adam-min-alpha N Adam minimum learning rate alpha - including warmup phase (default %f)\n", params->adam_min_alpha);
  992. fprintf(stderr, " --adam-decay N AdamW weight decay. Values greater zero enable AdamW instead of regular Adam. (default %f)\n", params->adam_decay);
  993. fprintf(stderr, " --adam-decay-min-ndim N Minimum number of tensor dimensions to apply AdamW weight decay. Weight decay is not applied to tensors with less n_dims. (default %d)\n", params->adam_decay_min_ndim);
  994. fprintf(stderr, " --adam-beta1 N AdamW beta1 in interval [0,1). How much to smooth the first moment of gradients. (default %f)\n", params->adam_beta1);
  995. fprintf(stderr, " --adam-beta2 N AdamW beta2 in interval [0,1). How much to smooth the second moment of gradients. (default %f)\n", params->adam_beta2);
  996. fprintf(stderr, " --adam-gclip N AdamW gradient clipping. Disabled when zero. (default %f)\n", params->adam_gclip);
  997. fprintf(stderr, " --adam-epsf N AdamW epsilon for convergence test. Disabled when <= zero. (default %f)\n", params->adam_eps_f);
  998. fprintf(stderr, " -ngl N, --n-gpu-layers N Number of model layers to offload to GPU (default %d)", params->n_gpu_layers);
  999. fprintf(stderr, "\n");
  1000. }
  1001. bool consume_common_train_arg(
  1002. int argc, char ** argv, int * idx, struct train_params_common * params, bool * invalid_param
  1003. ) {
  1004. int& i = *idx;
  1005. std::string arg = argv[i];
  1006. const std::string arg_prefix = "--";
  1007. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  1008. std::replace(arg.begin(), arg.end(), '_', '-');
  1009. }
  1010. if (arg == "--train-data") {
  1011. if (++i >= argc) {
  1012. *invalid_param = true;
  1013. return true;
  1014. }
  1015. params->fn_train_data = argv[i];
  1016. } else if (arg == "--checkpoint-in") {
  1017. if (++i >= argc) {
  1018. *invalid_param = true;
  1019. return true;
  1020. }
  1021. params->fn_checkpoint_in = argv[i];
  1022. } else if (arg == "--checkpoint-out") {
  1023. if (++i >= argc) {
  1024. *invalid_param = true;
  1025. return true;
  1026. }
  1027. params->fn_checkpoint_out = argv[i];
  1028. } else if (arg == "--pattern-fn-it") {
  1029. if (++i >= argc) {
  1030. *invalid_param = true;
  1031. return true;
  1032. }
  1033. params->pattern_fn_it = argv[i];
  1034. } else if (arg == "--fn-latest") {
  1035. if (++i >= argc) {
  1036. *invalid_param = true;
  1037. return true;
  1038. }
  1039. params->fn_latest = argv[i];
  1040. } else if (arg == "--save-every") {
  1041. if (++i >= argc) {
  1042. *invalid_param = true;
  1043. return true;
  1044. }
  1045. params->save_every = std::stoi(argv[i]);
  1046. } else if (arg == "-s" || arg == "--seed") {
  1047. if (++i >= argc) {
  1048. *invalid_param = true;
  1049. return true;
  1050. }
  1051. params->seed = std::stoi(argv[i]);
  1052. } else if (arg == "-c" || arg == "--ctx") {
  1053. if (++i >= argc) {
  1054. *invalid_param = true;
  1055. return true;
  1056. }
  1057. params->n_ctx = std::stoi(argv[i]);
  1058. params->custom_n_ctx = true;
  1059. } else if (arg == "-t" || arg == "--threads") {
  1060. if (++i >= argc) {
  1061. *invalid_param = true;
  1062. return true;
  1063. }
  1064. params->n_threads = std::stoi(argv[i]);
  1065. } else if (arg == "-b" || arg == "--batch") {
  1066. if (++i >= argc) {
  1067. *invalid_param = true;
  1068. return true;
  1069. }
  1070. params->n_batch = std::stoi(argv[i]);
  1071. } else if (arg == "--grad-acc") {
  1072. if (++i >= argc) {
  1073. *invalid_param = true;
  1074. return true;
  1075. }
  1076. params->n_gradient_accumulation = std::max(1, std::stoi(argv[i]));
  1077. } else if (arg == "--sample-start") {
  1078. if (++i >= argc) {
  1079. *invalid_param = true;
  1080. return true;
  1081. }
  1082. params->sample_start = std::string(argv[i]);
  1083. } else if (arg == "--escape") {
  1084. params->escape = true;
  1085. } else if (arg == "--include-sample-start") {
  1086. params->include_sample_start = true;
  1087. } else if (arg == "--overlapping-samples") {
  1088. params->overlapping_samples = true;
  1089. } else if (arg == "--fill-with-next-samples") {
  1090. params->fill_with_next_samples = true;
  1091. } else if (arg == "--separate-with-eos") {
  1092. params->separate_with_eos = true;
  1093. } else if (arg == "--separate-with-bos") {
  1094. params->separate_with_bos = true;
  1095. } else if (arg == "--no-separate-with-eos") {
  1096. params->separate_with_eos = false;
  1097. } else if (arg == "--no-separate-with-bos") {
  1098. params->separate_with_bos = false;
  1099. } else if (arg == "--sample-random-offsets") {
  1100. params->sample_random_offsets = true;
  1101. } else if (arg == "--force-reshuffle") {
  1102. params->force_reshuffle = true;
  1103. } else if (arg == "--no-flash") {
  1104. params->use_flash = false;
  1105. } else if (arg == "--use-flash") {
  1106. params->use_flash = true;
  1107. } else if (arg == "--no-checkpointing") {
  1108. params->use_checkpointing = false;
  1109. } else if (arg == "--use-checkpointing") {
  1110. params->use_checkpointing = true;
  1111. } else if (arg == "--warmup") {
  1112. if (++i >= argc) {
  1113. *invalid_param = true;
  1114. return true;
  1115. }
  1116. params->warmup = std::stoi(argv[i]);
  1117. } else if (arg == "--cos-decay-steps") {
  1118. if (++i >= argc) {
  1119. *invalid_param = true;
  1120. return true;
  1121. }
  1122. params->cos_decay_steps = std::stoi(argv[i]);
  1123. } else if (arg == "--cos-decay-restart") {
  1124. if (++i >= argc) {
  1125. *invalid_param = true;
  1126. return true;
  1127. }
  1128. params->cos_decay_restart = std::stof(argv[i]);
  1129. } else if (arg == "--cos-decay-min") {
  1130. if (++i >= argc) {
  1131. *invalid_param = true;
  1132. return true;
  1133. }
  1134. params->cos_decay_min = std::stof(argv[i]);
  1135. } else if (arg == "--enable-restart") {
  1136. params->enable_restart = true;
  1137. } else if (arg == "--disable-restart") {
  1138. params->enable_restart = false;
  1139. } else if (arg == "--opt-past") {
  1140. if (++i >= argc) {
  1141. *invalid_param = true;
  1142. return true;
  1143. }
  1144. params->opt_past = std::stoi(argv[i]);
  1145. } else if (arg == "--opt-delta") {
  1146. if (++i >= argc) {
  1147. *invalid_param = true;
  1148. return true;
  1149. }
  1150. params->opt_delta = std::stof(argv[i]);
  1151. } else if (arg == "--opt-max-no-improvement") {
  1152. if (++i >= argc) {
  1153. *invalid_param = true;
  1154. return true;
  1155. }
  1156. params->opt_max_no_improvement = std::stoi(argv[i]);
  1157. } else if (arg == "--adam-epsf") {
  1158. if (++i >= argc) {
  1159. *invalid_param = true;
  1160. return true;
  1161. }
  1162. params->adam_eps_f = std::stof(argv[i]);
  1163. } else if (arg == "--epochs") {
  1164. if (++i >= argc) {
  1165. *invalid_param = true;
  1166. return true;
  1167. }
  1168. params->n_epochs = std::stoi(argv[i]);
  1169. } else if (arg == "--adam-iter") {
  1170. if (++i >= argc) {
  1171. *invalid_param = true;
  1172. return true;
  1173. }
  1174. params->adam_n_iter = std::stoi(argv[i]);
  1175. } else if (arg == "--adam-alpha") {
  1176. if (++i >= argc) {
  1177. *invalid_param = true;
  1178. return true;
  1179. }
  1180. params->adam_alpha = std::stof(argv[i]);
  1181. } else if (arg == "--adam-min-alpha") {
  1182. if (++i >= argc) {
  1183. *invalid_param = true;
  1184. return true;
  1185. }
  1186. params->adam_min_alpha = std::stof(argv[i]);
  1187. } else if (arg == "--adam-decay") {
  1188. if (++i >= argc) {
  1189. *invalid_param = true;
  1190. return true;
  1191. }
  1192. params->adam_decay = std::stof(argv[i]);
  1193. } else if (arg == "--adam-decay-min-ndim") {
  1194. if (++i >= argc) {
  1195. *invalid_param = true;
  1196. return true;
  1197. }
  1198. params->adam_decay_min_ndim = std::stoi(argv[i]);
  1199. } else if (arg == "--adam-beta1") {
  1200. if (++i >= argc) {
  1201. *invalid_param = true;
  1202. return true;
  1203. }
  1204. params->adam_beta1 = std::stof(argv[i]);
  1205. } else if (arg == "--adam-beta2") {
  1206. if (++i >= argc) {
  1207. *invalid_param = true;
  1208. return true;
  1209. }
  1210. params->adam_beta2 = std::stof(argv[i]);
  1211. } else if (arg == "--adam-gclip") {
  1212. if (++i >= argc) {
  1213. *invalid_param = true;
  1214. return true;
  1215. }
  1216. params->adam_gclip = std::stof(argv[i]);
  1217. } else if (arg == "-ngl" || arg == "--n-gpu-layers") {
  1218. if (++i >= argc) {
  1219. *invalid_param = true;
  1220. return true;
  1221. }
  1222. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  1223. params->n_gpu_layers = std::stoi(argv[i]);
  1224. #else
  1225. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  1226. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  1227. #endif
  1228. } else if (arg == "-h" || arg == "--help") {
  1229. params->print_usage = true;
  1230. return true;
  1231. } else {
  1232. return false;
  1233. }
  1234. return true;
  1235. }
  1236. void finish_processing_train_args(struct train_params_common * params) {
  1237. if (params->escape) {
  1238. process_escapes(params->sample_start);
  1239. }
  1240. }
  1241. void train_opt_callback(void * vdata, int accum_step, float * sched, bool * cancel) {
  1242. struct train_opt_callback_data * data = (struct train_opt_callback_data *) vdata;
  1243. struct train_params_common * params = data->params;
  1244. struct train_state * train = data->train;
  1245. struct ggml_opt_context * opt = train->opt;
  1246. int n_batch = params->n_batch;
  1247. int n_ctx = params->n_ctx;
  1248. if (accum_step == 0) {
  1249. // time measurement
  1250. int64_t now = ggml_time_ms();
  1251. if (now > data->last_time && opt->iter > data->first_iter) {
  1252. double dt = (double) (now - data->last_time);
  1253. if (data->millis_per_iter == 0.0) {
  1254. data->millis_per_iter = dt;
  1255. } else {
  1256. const double gain = 0.7;
  1257. data->millis_per_iter = data->millis_per_iter*(1.0-gain) + dt*gain;
  1258. }
  1259. }
  1260. double remaining_millis = 0.0;
  1261. if (data->millis_per_iter > 0.0) {
  1262. const int n_iter = params->adam_n_iter;
  1263. const int done_iter = opt->iter - data->first_iter;
  1264. const int remaining_iter = n_iter - done_iter;
  1265. remaining_millis = remaining_iter * data->millis_per_iter;
  1266. }
  1267. // file saving
  1268. const bool save_now = (params->save_every > 0) && (opt->iter - data->last_save_iter >= params->save_every);
  1269. if (save_now) {
  1270. int new_iters = opt->iter - data->last_save_iter;
  1271. train->train_its += new_iters;
  1272. train->train_tokens += new_iters * opt->params.n_gradient_accumulation * n_batch * n_ctx;
  1273. if (data->save_cb) {
  1274. data->save_cb(data->save_data, train);
  1275. }
  1276. data->last_save_iter = opt->iter;
  1277. }
  1278. // exclude file saving from time measurement, by measuring last_time after saving
  1279. data->last_time = ggml_time_ms();
  1280. *sched = learning_schedule(
  1281. opt->iter,
  1282. params->warmup,
  1283. params->cos_decay_steps,
  1284. params->adam_alpha,
  1285. params->adam_min_alpha,
  1286. params->cos_decay_min,
  1287. params->cos_decay_restart,
  1288. params->enable_restart);
  1289. int impr_plot = -(int)(1 + (opt->loss_before - opt->loss_after) * 10.0f + 0.5f);
  1290. if (impr_plot > 0) impr_plot = 0;
  1291. if (std::isnan(opt->loss_before) || std::isnan(opt->loss_after)) impr_plot = 0;
  1292. printf("%s: iter=%6d sample=%zu/%zu sched=%f loss=%f",
  1293. __func__, opt->iter, std::min(1+train->shuffle_next_sample, train->shuffle_sample_count), train->shuffle_sample_count,
  1294. *sched, opt->loss_after);
  1295. if (data->millis_per_iter > 0) {
  1296. printf(" dt=");
  1297. print_duration(data->millis_per_iter);
  1298. printf(" eta=");
  1299. print_duration(remaining_millis);
  1300. }
  1301. float improvement = opt->loss_before - opt->loss_after;
  1302. const float plot_scale = 10.0f;
  1303. int bar_len = (int)(1 + improvement*plot_scale + 0.5);
  1304. printf(" |");
  1305. for (int i=0; i<bar_len; ++i) {
  1306. printf("-");
  1307. }
  1308. printf(">");
  1309. printf("\n");
  1310. }
  1311. int64_t used_samples = get_example_targets_batch(
  1312. data->lctx,
  1313. data->tokens_input,
  1314. data->target_probs,
  1315. train->shuffle_next_sample,
  1316. data->shuffled_samples_offs,
  1317. data->shuffled_samples_begin,
  1318. data->shuffled_samples_size,
  1319. data->samples_count,
  1320. data->tokens_data,
  1321. data->tokens_size,
  1322. params->separate_with_eos,
  1323. params->separate_with_bos,
  1324. params->fill_with_next_samples,
  1325. params->sample_random_offsets);
  1326. train->train_samples += used_samples;
  1327. train->shuffle_next_sample += used_samples;
  1328. if (train->shuffle_next_sample >= train->shuffle_sample_count) {
  1329. ++train->train_epochs;
  1330. printf("%s: reshuffle samples. completed epochs: %llu\n", __func__, (long long unsigned) train->train_epochs);
  1331. // note: we may have used some samples from the current shuffling more than once
  1332. train->shuffle_rng_state_current = train->shuffle_rng_state_next;
  1333. train->shuffle_rng_state_next = shuffle_samples(
  1334. train->shuffle_rng_state_current,
  1335. data->shuffled_samples_offs,
  1336. data->shuffled_samples_begin,
  1337. data->shuffled_samples_size,
  1338. data->samples_begin,
  1339. data->samples_size,
  1340. data->samples_count);
  1341. train->shuffle_next_sample = 0;
  1342. }
  1343. const bool last_epoch_reached = (params->n_epochs > 0 && (int64_t) train->train_epochs - data->first_epoch >= params->n_epochs);
  1344. if (last_epoch_reached) {
  1345. // allow optimization iteration at last epoch to be completed before canceling
  1346. if (data->iter_at_last_epoch < 0) {
  1347. data->iter_at_last_epoch = opt->iter;
  1348. } else if (opt->iter > data->iter_at_last_epoch) {
  1349. *cancel = true;
  1350. }
  1351. }
  1352. }