baby-llama.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  1. #include "ggml.h"
  2. #include "train.h"
  3. #include <vector>
  4. #include <cassert>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <random>
  8. #include <vector>
  9. #if defined(_MSC_VER)
  10. #pragma warning(disable: 4244 4267) // possible loss of data
  11. #endif
  12. #ifdef LLAMA_DEFAULT_RMS_EPS
  13. constexpr float rms_norm_eps = LLAMA_DEFAULT_RMS_EPS;
  14. #else
  15. constexpr float rms_norm_eps = 5e-6f;
  16. #endif
  17. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  18. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  19. if (plan.work_size > 0) {
  20. buf.resize(plan.work_size);
  21. plan.work_data = buf.data();
  22. }
  23. ggml_graph_compute(graph, &plan);
  24. }
  25. static struct ggml_tensor * randomize_tensor(
  26. struct ggml_tensor * tensor, int ndims, const int64_t ne[], float fmin, float fmax
  27. ) {
  28. switch (ndims) {
  29. case 1:
  30. for (int i0 = 0; i0 < ne[0]; i0++) {
  31. ((float *)tensor->data)[i0] = frand()*(fmax - fmin) + fmin;
  32. }
  33. break;
  34. case 2:
  35. for (int i1 = 0; i1 < ne[1]; i1++) {
  36. for (int i0 = 0; i0 < ne[0]; i0++) {
  37. ((float *)tensor->data)[i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
  38. }
  39. }
  40. break;
  41. case 3:
  42. for (int i2 = 0; i2 < ne[2]; i2++) {
  43. for (int i1 = 0; i1 < ne[1]; i1++) {
  44. for (int i0 = 0; i0 < ne[0]; i0++) {
  45. ((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
  46. }
  47. }
  48. }
  49. break;
  50. case 4:
  51. for (int i3 = 0; i3 < ne[3]; i3++) {
  52. for (int i2 = 0; i2 < ne[2]; i2++) {
  53. for (int i1 = 0; i1 < ne[1]; i1++) {
  54. for (int i0 = 0; i0 < ne[0]; i0++) {
  55. ((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
  56. }
  57. }
  58. }
  59. }
  60. break;
  61. default:
  62. assert(false);
  63. }
  64. return tensor;
  65. }
  66. struct llama_hparams {
  67. uint32_t n_vocab = 32000;
  68. uint32_t n_ctx = 512; // this is provided as user input?
  69. uint32_t n_embd = 4096;
  70. uint32_t n_mult = 4;
  71. uint32_t n_head = 32;
  72. uint32_t n_layer = 32;
  73. uint32_t n_rot = 64;
  74. bool operator!=(const llama_hparams & other) const {
  75. return memcmp(this, &other, sizeof(llama_hparams));
  76. }
  77. };
  78. static uint32_t get_n_ff(const struct llama_hparams* hparams) {
  79. const uint32_t n_ff = ((2*(4*hparams->n_embd)/3 + hparams->n_mult - 1)/hparams->n_mult)*hparams->n_mult;
  80. return n_ff;
  81. }
  82. struct llama_hparams_lora {
  83. uint32_t n_vocab = 32000;
  84. uint32_t n_ctx = 512; // this is provided as user input?
  85. uint32_t n_embd = 4096;
  86. uint32_t n_mult = 4;
  87. uint32_t n_head = 32;
  88. uint32_t n_layer = 32;
  89. uint32_t n_rot = 64;
  90. uint32_t n_lora = 64;
  91. bool operator!=(const llama_hparams_lora & other) const {
  92. return memcmp(this, &other, sizeof(llama_hparams_lora)) != 0;
  93. }
  94. };
  95. struct llama_layer {
  96. // normalization
  97. struct ggml_tensor * attention_norm;
  98. // attention
  99. struct ggml_tensor * wq;
  100. struct ggml_tensor * wk;
  101. struct ggml_tensor * wv;
  102. struct ggml_tensor * wo;
  103. // normalization
  104. struct ggml_tensor * ffn_norm;
  105. // ff
  106. struct ggml_tensor * w1;
  107. struct ggml_tensor * w2;
  108. struct ggml_tensor * w3;
  109. };
  110. struct llama_layer_lora {
  111. // normalization
  112. struct ggml_tensor * attention_norm;
  113. // attention
  114. struct ggml_tensor * wqa;
  115. struct ggml_tensor * wqb;
  116. struct ggml_tensor * wka;
  117. struct ggml_tensor * wkb;
  118. struct ggml_tensor * wva;
  119. struct ggml_tensor * wvb;
  120. struct ggml_tensor * woa;
  121. struct ggml_tensor * wob;
  122. // normalization
  123. struct ggml_tensor * ffn_norm;
  124. // ff
  125. struct ggml_tensor * w1;
  126. struct ggml_tensor * w2;
  127. struct ggml_tensor * w3;
  128. };
  129. struct llama_kv_cache {
  130. struct ggml_context * ctx = NULL;
  131. struct ggml_tensor * k;
  132. struct ggml_tensor * v;
  133. // llama_ctx_buffer buf;
  134. int n; // number of tokens currently in the cache
  135. };
  136. struct llama_model {
  137. struct ggml_context * ctx = NULL;
  138. llama_hparams hparams;
  139. struct ggml_tensor * tok_embeddings;
  140. struct ggml_tensor * norm;
  141. struct ggml_tensor * output;
  142. std::vector<llama_layer> layers;
  143. };
  144. struct llama_model_lora {
  145. struct ggml_context * ctx = NULL;
  146. llama_hparams_lora hparams;
  147. struct ggml_tensor * tok_embeddings;
  148. struct ggml_tensor * norm;
  149. struct ggml_tensor * outputa;
  150. struct ggml_tensor * outputb;
  151. std::vector<llama_layer_lora> layers;
  152. };
  153. static void init_model(struct llama_model * model) {
  154. const auto & hparams = model->hparams;
  155. const uint32_t n_embd = hparams.n_embd;
  156. const uint32_t n_layer = hparams.n_layer;
  157. const uint32_t n_vocab = hparams.n_vocab;
  158. const uint32_t n_ff = get_n_ff(&hparams);
  159. struct ggml_context * ctx = model->ctx;
  160. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
  161. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
  162. model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("output.weight", {n_embd, n_vocab});
  163. model->layers.resize(n_layer);
  164. for (uint32_t i = 0; i < n_layer; ++i) {
  165. auto & layer = model->layers[i];
  166. // std::string layers_i = "layers." + std::to_string(i);
  167. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
  168. layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
  169. layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
  170. layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
  171. layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
  172. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
  173. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
  174. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
  175. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
  176. }
  177. }
  178. static void init_model_lora(struct llama_model_lora * model) {
  179. const auto & hparams = model->hparams;
  180. const uint32_t n_embd = hparams.n_embd;
  181. const uint32_t n_mult = hparams.n_mult;
  182. const uint32_t n_layer = hparams.n_layer;
  183. const uint32_t n_vocab = hparams.n_vocab;
  184. const uint32_t n_lora = hparams.n_lora;
  185. const uint32_t n_ff = ((2*(4*n_embd)/3 + n_mult - 1)/n_mult)*n_mult;
  186. struct ggml_context * ctx = model->ctx;
  187. model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
  188. model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
  189. model->outputa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_vocab); // ("output.weight", {n_embd, n_vocab});
  190. model->outputb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // ("output.weight", {n_embd, n_vocab});
  191. model->layers.resize(n_layer);
  192. for (uint32_t i = 0; i < n_layer; ++i) {
  193. auto & layer = model->layers[i];
  194. // std::string layers_i = "layers." + std::to_string(i);
  195. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
  196. layer.wqa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
  197. layer.wqb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
  198. layer.wka = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
  199. layer.wkb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
  200. layer.wva = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
  201. layer.wvb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
  202. layer.woa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
  203. layer.wob = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
  204. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
  205. layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
  206. layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
  207. layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
  208. }
  209. }
  210. static void set_param_model(struct llama_model * model) {
  211. const auto& hparams = model->hparams;
  212. const uint32_t n_layer = hparams.n_layer;
  213. struct ggml_context* ctx = model->ctx;
  214. ggml_set_param(ctx, model->tok_embeddings);
  215. ggml_set_param(ctx, model->norm);
  216. ggml_set_param(ctx, model->output);
  217. for (uint32_t i = 0; i < n_layer; ++i) {
  218. auto & layer = model->layers[i];
  219. ggml_set_param(ctx, layer.attention_norm);
  220. ggml_set_param(ctx, layer.wq);
  221. ggml_set_param(ctx, layer.wk);
  222. ggml_set_param(ctx, layer.wv);
  223. ggml_set_param(ctx, layer.wo);
  224. ggml_set_param(ctx, layer.ffn_norm);
  225. ggml_set_param(ctx, layer.w1);
  226. ggml_set_param(ctx, layer.w2);
  227. ggml_set_param(ctx, layer.w3);
  228. }
  229. }
  230. static void set_param_model_lora(struct llama_model_lora * model) {
  231. const auto& hparams = model->hparams;
  232. const uint32_t n_layer = hparams.n_layer;
  233. struct ggml_context* ctx = model->ctx;
  234. ggml_set_param(ctx, model->tok_embeddings);
  235. ggml_set_param(ctx, model->norm);
  236. ggml_set_param(ctx, model->outputa);
  237. ggml_set_param(ctx, model->outputb);
  238. for (uint32_t i = 0; i < n_layer; ++i) {
  239. auto & layer = model->layers[i];
  240. ggml_set_param(ctx, layer.attention_norm);
  241. ggml_set_param(ctx, layer.wqa);
  242. ggml_set_param(ctx, layer.wqb);
  243. ggml_set_param(ctx, layer.wka);
  244. ggml_set_param(ctx, layer.wkb);
  245. ggml_set_param(ctx, layer.wva);
  246. ggml_set_param(ctx, layer.wvb);
  247. ggml_set_param(ctx, layer.woa);
  248. ggml_set_param(ctx, layer.wob);
  249. ggml_set_param(ctx, layer.ffn_norm);
  250. ggml_set_param(ctx, layer.w1);
  251. ggml_set_param(ctx, layer.w2);
  252. ggml_set_param(ctx, layer.w3);
  253. }
  254. }
  255. static void randomize_model(struct llama_model * model, int seed, float mean, float std, float min, float max) {
  256. const auto & hparams = model->hparams;
  257. const uint32_t n_layer = hparams.n_layer;
  258. struct random_normal_distribution * rnd = init_random_normal_distribution(seed, mean, std, min, max);
  259. randomize_tensor_normal(model->tok_embeddings , rnd);
  260. randomize_tensor_normal(model->norm , rnd);
  261. randomize_tensor_normal(model->output , rnd);
  262. for (uint32_t i = 0; i < n_layer; ++i) {
  263. auto & layer = model->layers[i];
  264. randomize_tensor_normal(layer.attention_norm, rnd);
  265. randomize_tensor_normal(layer.wq, rnd);
  266. randomize_tensor_normal(layer.wk, rnd);
  267. randomize_tensor_normal(layer.wv, rnd);
  268. randomize_tensor_normal(layer.wo, rnd);
  269. randomize_tensor_normal(layer.ffn_norm, rnd);
  270. randomize_tensor_normal(layer.w1, rnd);
  271. randomize_tensor_normal(layer.w2, rnd);
  272. randomize_tensor_normal(layer.w3, rnd);
  273. }
  274. free_random_normal_distribution(rnd);
  275. }
  276. static void randomize_model_lora(
  277. struct llama_model_lora * model, int seed, float mean, float std, float min, float max
  278. ) {
  279. const auto & hparams = model->hparams;
  280. const uint32_t n_layer = hparams.n_layer;
  281. struct random_normal_distribution * rnd = init_random_normal_distribution(seed, mean, std, min, max);
  282. randomize_tensor_normal(model->tok_embeddings, rnd);
  283. randomize_tensor_normal(model->norm , rnd);
  284. randomize_tensor_normal(model->outputa , rnd);
  285. randomize_tensor_normal(model->outputb , rnd);
  286. for (uint32_t i = 0; i < n_layer; ++i) {
  287. auto & layer = model->layers[i];
  288. randomize_tensor_normal(layer.attention_norm, rnd);
  289. randomize_tensor_normal(layer.wqa, rnd);
  290. randomize_tensor_normal(layer.wqb, rnd);
  291. randomize_tensor_normal(layer.wka, rnd);
  292. randomize_tensor_normal(layer.wkb, rnd);
  293. randomize_tensor_normal(layer.wva, rnd);
  294. randomize_tensor_normal(layer.wvb, rnd);
  295. randomize_tensor_normal(layer.woa, rnd);
  296. randomize_tensor_normal(layer.wob, rnd);
  297. randomize_tensor_normal(layer.ffn_norm, rnd);
  298. randomize_tensor_normal(layer.w1, rnd);
  299. randomize_tensor_normal(layer.w2, rnd);
  300. randomize_tensor_normal(layer.w3, rnd);
  301. }
  302. free_random_normal_distribution(rnd);
  303. }
  304. static void init_kv_cache(struct llama_kv_cache* cache, struct llama_model * model, int n_batch) {
  305. const auto & hparams = model->hparams;
  306. const uint32_t n_ctx = hparams.n_ctx;
  307. const uint32_t n_embd = hparams.n_embd;
  308. const uint32_t n_layer = hparams.n_layer;
  309. const int64_t n_mem = n_layer*n_ctx*n_batch;
  310. const int64_t n_elements = n_embd*n_mem;
  311. // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  312. // struct ggml_init_params params;
  313. // params.mem_size = cache.buf.size;
  314. // params.mem_buffer = cache.buf.addr;
  315. // params.no_alloc = false;
  316. if (!cache->ctx) {
  317. struct ggml_init_params params;
  318. params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
  319. params.mem_buffer = NULL;
  320. params.no_alloc = false;
  321. cache->ctx = ggml_init(params);
  322. if (!cache->ctx) {
  323. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  324. exit(1);
  325. }
  326. }
  327. cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  328. cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  329. }
  330. static bool init_kv_cache_lora(struct llama_kv_cache* cache, struct llama_model_lora * model, int n_batch) {
  331. const auto & hparams = model->hparams;
  332. const uint32_t n_ctx = hparams.n_ctx;
  333. const uint32_t n_embd = hparams.n_embd;
  334. const uint32_t n_layer = hparams.n_layer;
  335. const int64_t n_mem = n_layer*n_ctx*n_batch;
  336. const int64_t n_elements = n_embd*n_mem;
  337. // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  338. // struct ggml_init_params params;
  339. // params.mem_size = cache.buf.size;
  340. // params.mem_buffer = cache.buf.addr;
  341. // params.no_alloc = false;
  342. if (!cache->ctx) {
  343. struct ggml_init_params params;
  344. params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
  345. params.mem_buffer = NULL;
  346. params.no_alloc = false;
  347. cache->ctx = ggml_init(params);
  348. if (!cache->ctx) {
  349. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  350. return false;
  351. }
  352. }
  353. cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  354. cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
  355. return true;
  356. }
  357. static struct ggml_tensor * forward(
  358. struct llama_model * model,
  359. struct llama_kv_cache * cache,
  360. struct ggml_context * ctx0,
  361. struct ggml_cgraph * gf,
  362. struct ggml_tensor * tokens_input,
  363. const int n_tokens,
  364. const int n_past
  365. ) {
  366. const int N = n_tokens;
  367. struct llama_kv_cache& kv_self = *cache;
  368. const auto & hparams = model->hparams;
  369. const int n_ctx = hparams.n_ctx;
  370. const int n_embd = hparams.n_embd;
  371. const int n_layer = hparams.n_layer;
  372. const int n_head = hparams.n_head;
  373. const int n_rot = hparams.n_rot;
  374. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  375. memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
  376. struct ggml_tensor * kc = kv_self.k;
  377. struct ggml_tensor * vc = kv_self.v;
  378. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  379. {
  380. int * data = (int *) KQ_pos->data;
  381. for (int i = 0; i < N; ++i) {
  382. data[i] = n_past + i;
  383. }
  384. }
  385. // inpL shape [n_embd,N,1,1]
  386. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  387. for (int il = 0; il < n_layer; ++il) {
  388. struct ggml_tensor * inpSA = inpL;
  389. struct ggml_tensor * cur;
  390. // lctx.use_buf(ctx0, 0);
  391. // norm
  392. {
  393. // cur shape [n_embd,N,1,1]
  394. cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  395. // cur = attention_norm*cur
  396. cur = ggml_mul(ctx0,
  397. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  398. cur);
  399. }
  400. // self-attention
  401. {
  402. // compute Q and K and RoPE them
  403. // wq shape [n_embd, n_embd, 1, 1]
  404. // wk shape [n_embd, n_embd, 1, 1]
  405. // Qcur shape [n_embd/n_head, n_head, N, 1]
  406. // Kcur shape [n_embd/n_head, n_head, N, 1]
  407. struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wq, cur), n_embd/n_head, n_head, N), KQ_pos, n_rot, 0, 0);
  408. struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wk, cur), n_embd/n_head, n_head, N), KQ_pos, n_rot, 0, 0);
  409. // store key and value to memory
  410. {
  411. // compute the transposed [N, n_embd] V matrix
  412. // wv shape [n_embd, n_embd, 1, 1]
  413. // Vcur shape [n_embd, N, 1, 1]
  414. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wv, cur), n_embd, N)));
  415. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  416. // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
  417. // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
  418. // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
  419. /* {
  420. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  421. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  422. ( n_ctx)*ggml_element_size(kv_self.v),
  423. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  424. // important: storing RoPE-ed version of K in the KV cache!
  425. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  426. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  427. } //*/
  428. kc = ggml_set_1d(ctx0, kc, ggml_reshape_1d(ctx0, Kcur, n_embd*N), (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  429. vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
  430. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  431. }
  432. // Qcur shape [n_embd/n_head, n_head, N, 1]
  433. // Q shape [n_embd/n_head, N, n_head, 1]
  434. struct ggml_tensor * Q =
  435. ggml_permute(ctx0,
  436. Qcur,
  437. 0, 2, 1, 3);
  438. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  439. // K shape [n_embd/n_head, n_past + N, n_head, 1]
  440. struct ggml_tensor * K =
  441. ggml_permute(ctx0,
  442. ggml_reshape_3d(ctx0,
  443. ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
  444. n_embd/n_head, n_head, n_past + N),
  445. 0, 2, 1, 3);
  446. // K * Q
  447. // KQ shape [n_past + N, N, n_head, 1]
  448. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  449. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  450. // KQ_scaled shape [n_past + N, N, n_head, 1]
  451. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
  452. // KQ_masked = mask_past(KQ_scaled)
  453. // KQ_masked shape [n_past + N, N, n_head, 1]
  454. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  455. // KQ = soft_max(KQ_masked)
  456. // KQ_soft_max shape [n_past + N, N, n_head, 1]
  457. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  458. // split cached V into n_head heads
  459. //// V shape [n_past + N, n_embd/n_head, n_head, 1]
  460. // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
  461. struct ggml_tensor * V =
  462. ggml_view_3d(ctx0, vc,
  463. n_past + N, n_embd/n_head, n_head,
  464. n_ctx*ggml_element_size(vc),
  465. n_ctx*ggml_element_size(vc)*n_embd/n_head,
  466. il*n_ctx*ggml_element_size(vc)*n_embd);
  467. // KQV shape [n_embd/n_head, N, n_head, 1]
  468. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  469. // KQV_merged = KQV.permute(0, 2, 1, 3)
  470. // KQV_merged shape [n_embd/n_head, n_head, N, 1]
  471. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  472. // KQV_merged shape
  473. // cur = KQV_merged.contiguous().view(n_embd, N)
  474. // cur shape [n_embd,N,1,1]
  475. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
  476. // cur = ggml_cpy(ctx0,
  477. // KQV_merged,
  478. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  479. // projection (no bias)
  480. // cur shape [n_embd,N,1,1]
  481. cur = ggml_mul_mat(ctx0,
  482. model->layers[il].wo,
  483. cur);
  484. }
  485. // lctx.use_buf(ctx0, 1);
  486. // inpFF shape [n_embd,N,1,1]
  487. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  488. // feed-forward network
  489. {
  490. // norm
  491. {
  492. // cur shape [n_embd,N,1,1]
  493. cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
  494. // cur = ffn_norm*cur
  495. // cur shape [n_embd,N,1,1]
  496. cur = ggml_mul(ctx0,
  497. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  498. cur);
  499. }
  500. // tmp shape [n_ff,N,1,1]
  501. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  502. model->layers[il].w3,
  503. cur);
  504. // cur shape [n_ff,N,1,1]
  505. cur = ggml_mul_mat(ctx0,
  506. model->layers[il].w1,
  507. cur);
  508. // SILU activation
  509. // cur shape [n_ff,N,1,1]
  510. cur = ggml_silu(ctx0, cur);
  511. // cur shape [n_ff,N,1,1]
  512. cur = ggml_mul(ctx0, cur, tmp);
  513. // cur shape [n_embd,N,1,1]
  514. cur = ggml_mul_mat(ctx0,
  515. model->layers[il].w2,
  516. cur);
  517. }
  518. // cur shape [n_embd,N,1,1]
  519. cur = ggml_add(ctx0, cur, inpFF);
  520. // input for next layer
  521. // inpL shape [n_embd,N,1,1]
  522. inpL = cur;
  523. }
  524. // norm
  525. {
  526. // inpL shape [n_embd,N,1,1]
  527. inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  528. // inpL = norm*inpL
  529. // inpL shape [n_embd,N,1,1]
  530. inpL = ggml_mul(ctx0,
  531. ggml_repeat(ctx0, model->norm, inpL),
  532. inpL);
  533. //embeddings = inpL;
  534. }
  535. // lm_head
  536. // inpL shape [n_vocab,N,1,1]
  537. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  538. // run the computation
  539. ggml_build_forward_expand(gf, inpL);
  540. return inpL;
  541. }
  542. static struct ggml_tensor * forward_batch(
  543. struct llama_model * model,
  544. struct llama_kv_cache * cache,
  545. struct ggml_context * ctx0,
  546. struct ggml_cgraph * gf,
  547. struct ggml_tensor * tokens_input,
  548. const int n_tokens,
  549. const int n_past,
  550. const int n_batch
  551. ) {
  552. const int N = n_tokens;
  553. struct llama_kv_cache& kv_self = *cache;
  554. const auto & hparams = model->hparams;
  555. const int n_ctx = hparams.n_ctx;
  556. const int n_vocab = hparams.n_vocab;
  557. const int n_embd = hparams.n_embd;
  558. const int n_layer = hparams.n_layer;
  559. const int n_head = hparams.n_head;
  560. const int n_rot = hparams.n_rot;
  561. const int n_ff = get_n_ff(&hparams);
  562. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
  563. memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
  564. struct ggml_tensor * kc = kv_self.k;
  565. struct ggml_tensor * vc = kv_self.v;
  566. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  567. {
  568. int * data = (int *) KQ_pos->data;
  569. for (int i = 0; i < N; ++i) {
  570. data[i] = n_past + i;
  571. }
  572. }
  573. // inpL shape [n_embd,N*n_batch,1]
  574. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  575. assert_shape_2d(inpL, n_embd, N*n_batch);
  576. for (int il = 0; il < n_layer; ++il) {
  577. struct ggml_tensor * inpSA = inpL;
  578. struct ggml_tensor * cur;
  579. // lctx.use_buf(ctx0, 0);
  580. // norm
  581. {
  582. // cur shape [n_embd,N*n_batch,1,1]
  583. cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  584. assert_shape_2d(cur, n_embd, N*n_batch);
  585. // cur = attention_norm*cur
  586. cur = ggml_mul(ctx0,
  587. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  588. cur);
  589. assert_shape_2d(cur, n_embd, N*n_batch);
  590. }
  591. // self-attention
  592. {
  593. // compute Q and K and RoPE them
  594. // wq shape [n_embd, n_embd, 1, 1]
  595. // wk shape [n_embd, n_embd, 1, 1]
  596. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  597. // Kcur shape [n_embd/n_head, n_head, N, n_batch]
  598. struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wq, cur), n_embd/n_head, n_head, N, n_batch), KQ_pos, n_rot, 0, 0);
  599. struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wk, cur), n_embd/n_head, n_head, N, n_batch), KQ_pos, n_rot, 0, 0);
  600. assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
  601. assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
  602. // store key and value to memory
  603. {
  604. // compute the transposed [N, n_embd] V matrix
  605. // wv shape [n_embd, n_embd, 1, 1]
  606. // Vcur shape [N, n_embd, n_batch, 1]
  607. struct ggml_tensor * Vcur = ggml_cont(ctx0,
  608. ggml_permute(ctx0,
  609. ggml_reshape_3d(ctx0,
  610. ggml_mul_mat(ctx0,
  611. model->layers[il].wv,
  612. cur),
  613. n_embd, N, n_batch),
  614. 1, 0, 2, 3));
  615. assert_shape_3d(Vcur, N, n_embd, n_batch);
  616. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  617. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  618. // k shape [n_embd * N, n_batch] == kv_self.k[:,n_past:n_past+N,:,il]
  619. // v shape [N, n_embd, n_batch, 1] == kv_self.v[:,n_past:n_past+N,:,il]
  620. /* {
  621. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  622. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  623. ( n_ctx)*ggml_element_size(kv_self.v),
  624. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  625. // important: storing RoPE-ed version of K in the KV cache!
  626. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  627. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  628. } //*/
  629. kc = ggml_set_2d(ctx0, kc,
  630. ggml_reshape_2d(ctx0, Kcur, n_embd*N, n_batch),
  631. ggml_element_size(kc)*n_embd*n_ctx,
  632. (ggml_element_size(kc)*n_embd)*(il*n_batch*n_ctx + n_past));
  633. vc = ggml_set_2d(ctx0, vc,
  634. ggml_reshape_2d(ctx0, Vcur, N*n_embd, n_batch),
  635. ggml_element_size(vc)*n_ctx*n_embd,
  636. ggml_element_size(vc)*(n_past + il*n_embd*n_batch*n_ctx));
  637. assert_shape_1d(kc, n_embd * n_ctx * n_batch * n_layer);
  638. assert_shape_1d(vc, n_embd * n_ctx * n_batch * n_layer);
  639. }
  640. // Qcur shape [n_embd/n_head, n_head, N, n_batch]
  641. // Q shape [n_embd/n_head, N, n_head, n_batch]
  642. struct ggml_tensor * Q =
  643. ggml_permute(ctx0,
  644. Qcur,
  645. 0, 2, 1, 3);
  646. assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
  647. // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
  648. // K shape [n_embd/n_head, n_past + N, n_head, n_batch]
  649. struct ggml_tensor * K =
  650. ggml_permute(ctx0,
  651. ggml_reshape_4d(ctx0,
  652. ggml_view_3d(ctx0,
  653. kc,
  654. n_embd,
  655. (n_past + N),
  656. n_batch,
  657. n_embd*ggml_element_size(kc),
  658. n_ctx*n_embd*ggml_element_size(kc),
  659. il*n_batch*n_ctx*n_embd*ggml_element_size(kc)),
  660. n_embd/n_head, n_head, n_past + N, n_batch),
  661. 0, 2, 1, 3);
  662. assert_shape_4d(K, n_embd/n_head, n_past + N, n_head, n_batch);
  663. // K * Q
  664. // KQ shape [n_past + N, N, n_head, n_batch]
  665. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  666. assert_shape_4d(KQ, n_past + N, N, n_head, n_batch);
  667. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  668. // KQ_scaled shape [n_past + N, N, n_head, n_batch]
  669. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
  670. assert_shape_4d(KQ_scaled, n_past + N, N, n_head, n_batch);
  671. // KQ_masked = mask_past(KQ_scaled)
  672. // KQ_masked shape [n_past + N, N, n_head, n_batch]
  673. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  674. assert_shape_4d(KQ_masked, n_past + N, N, n_head, n_batch);
  675. // KQ = soft_max(KQ_masked)
  676. // KQ_soft_max shape [n_past + N, N, n_head, n_batch]
  677. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  678. assert_shape_4d(KQ_soft_max, n_past + N, N, n_head, n_batch);
  679. // split cached V into n_head heads
  680. // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
  681. // V shape [n_past + N, n_embd/n_head, n_head, n_batch] == kv_self.v[:(n_past+N),:,:,il]
  682. struct ggml_tensor * V =
  683. ggml_view_4d(ctx0, vc,
  684. n_past + N, n_embd/n_head, n_head, n_batch,
  685. ggml_element_size(vc)*n_ctx,
  686. ggml_element_size(vc)*n_ctx*n_embd/n_head,
  687. ggml_element_size(vc)*n_ctx*n_embd,
  688. il*n_batch*n_ctx*n_embd*ggml_element_size(vc));
  689. assert_shape_4d(V, n_past + N, n_embd/n_head, n_head, n_batch);
  690. // KQV shape [n_embd/n_head, N, n_head, n_batch]
  691. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  692. assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
  693. // KQV_merged = KQV.permute(0, 2, 1, 3)
  694. // KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
  695. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  696. assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
  697. // KQV_merged shape
  698. // cur = KQV_merged.contiguous().view(n_embd, N)
  699. // cur shape [n_embd,N*n_batch,1,1]
  700. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
  701. assert_shape_2d(cur, n_embd, N*n_batch);
  702. // cur = ggml_cpy(ctx0,
  703. // KQV_merged,
  704. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  705. // projection (no bias)
  706. // cur shape [n_embd,N*n_batch,1,1]
  707. cur = ggml_mul_mat(ctx0,
  708. model->layers[il].wo,
  709. cur);
  710. assert_shape_2d(cur, n_embd, N*n_batch);
  711. }
  712. // lctx.use_buf(ctx0, 1);
  713. // inpFF shape [n_embd,N*n_batch,1,1]
  714. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  715. assert_shape_2d(inpFF, n_embd, N*n_batch);
  716. // feed-forward network
  717. {
  718. // norm
  719. {
  720. // cur shape [n_embd,N*n_batch,1,1]
  721. cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
  722. assert_shape_2d(cur, n_embd, N*n_batch);
  723. // cur = ffn_norm*cur
  724. // cur shape [n_embd,N*n_batch,1,1]
  725. cur = ggml_mul(ctx0,
  726. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  727. cur);
  728. assert_shape_2d(cur, n_embd, N*n_batch);
  729. }
  730. // tmp shape [n_ff,N*n_batch,1,1]
  731. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  732. model->layers[il].w3,
  733. cur);
  734. assert_shape_2d(tmp, n_ff, N*n_batch);
  735. // cur shape [n_ff,N*n_batch,1,1]
  736. cur = ggml_mul_mat(ctx0,
  737. model->layers[il].w1,
  738. cur);
  739. assert_shape_2d(cur, n_ff, N*n_batch);
  740. // SILU activation
  741. // cur shape [n_ff,N*n_batch,1,1]
  742. cur = ggml_silu(ctx0, cur);
  743. assert_shape_2d(cur, n_ff, N*n_batch);
  744. // cur shape [n_ff,N*n_batch,1,1]
  745. cur = ggml_mul(ctx0, cur, tmp);
  746. assert_shape_2d(cur, n_ff, N*n_batch);
  747. // cur shape [n_embd,N*n_batch,1,1]
  748. cur = ggml_mul_mat(ctx0,
  749. model->layers[il].w2,
  750. cur);
  751. assert_shape_2d(cur, n_embd, N*n_batch);
  752. }
  753. // cur shape [n_embd,N*n_batch,1,1]
  754. cur = ggml_add(ctx0, cur, inpFF);
  755. assert_shape_2d(cur, n_embd, N*n_batch);
  756. // input for next layer
  757. // inpL shape [n_embd,N*n_batch,1,1]
  758. inpL = cur;
  759. assert_shape_2d(inpL, n_embd, N*n_batch);
  760. }
  761. // norm
  762. {
  763. // inpL shape [n_embd,N*n_batch,1,1]
  764. inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  765. assert_shape_2d(inpL, n_embd, N*n_batch);
  766. // inpL = norm*inpL
  767. // inpL shape [n_embd,N*n_batch,1,1]
  768. inpL = ggml_mul(ctx0,
  769. ggml_repeat(ctx0, model->norm, inpL),
  770. inpL);
  771. assert_shape_2d(inpL, n_embd, N*n_batch);
  772. //embeddings = inpL;
  773. }
  774. // lm_head
  775. // inpL shape [n_vocab,N*n_batch,1,1]
  776. inpL = ggml_mul_mat(ctx0, model->output, inpL);
  777. assert_shape_2d(inpL, n_vocab, N*n_batch);
  778. {
  779. // inpL shape [n_vocab,N,n_batch,1]
  780. inpL = ggml_reshape_3d(ctx0,
  781. inpL,
  782. n_vocab, N, n_batch);
  783. assert_shape_3d(inpL, n_vocab, N, n_batch);
  784. }
  785. // run the computation
  786. ggml_build_forward_expand(gf, inpL);
  787. return inpL;
  788. }
  789. static struct ggml_tensor * forward_lora(
  790. struct llama_model_lora * model,
  791. struct llama_kv_cache * cache,
  792. struct ggml_context * ctx0,
  793. struct ggml_cgraph * gf,
  794. struct ggml_tensor * tokens_input,
  795. const int n_tokens,
  796. const int n_past
  797. ) {
  798. const int N = n_tokens;
  799. struct llama_kv_cache& kv_self = *cache;
  800. const auto & hparams = model->hparams;
  801. const int n_ctx = hparams.n_ctx;
  802. const int n_embd = hparams.n_embd;
  803. const int n_layer = hparams.n_layer;
  804. const int n_head = hparams.n_head;
  805. const int n_rot = hparams.n_rot;
  806. struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  807. memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
  808. struct ggml_tensor * kc = kv_self.k;
  809. struct ggml_tensor * vc = kv_self.v;
  810. struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  811. {
  812. int * data = (int *) KQ_pos->data;
  813. for (int i = 0; i < N; ++i) {
  814. data[i] = n_past + i;
  815. }
  816. }
  817. // inpL shape [n_embd,N,1,1]
  818. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
  819. for (int il = 0; il < n_layer; ++il) {
  820. struct ggml_tensor * inpSA = inpL;
  821. struct ggml_tensor * cur;
  822. // norm
  823. {
  824. // cur shape [n_embd,N,1,1]
  825. cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  826. // cur = attention_norm*cur
  827. cur = ggml_mul(ctx0,
  828. ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
  829. cur);
  830. }
  831. // self-attention
  832. {
  833. // compute Q and K and RoPE them
  834. // wq shape [n_embd, n_embd, 1, 1]
  835. // wk shape [n_embd, n_embd, 1, 1]
  836. // Qcur shape [n_embd/n_head, n_head, N, 1]
  837. // Kcur shape [n_embd/n_head, n_head, N, 1]
  838. struct ggml_tensor * Qcur = ggml_rope(ctx0,
  839. ggml_reshape_3d(ctx0,
  840. ggml_mul_mat(ctx0,
  841. model->layers[il].wqa,
  842. ggml_mul_mat(ctx0,
  843. model->layers[il].wqb,
  844. cur)),
  845. n_embd/n_head, n_head, N),
  846. KQ_pos, n_rot, 0, 0);
  847. struct ggml_tensor * Kcur = ggml_rope(ctx0,
  848. ggml_reshape_3d(ctx0,
  849. ggml_mul_mat(ctx0,
  850. model->layers[il].wka,
  851. ggml_mul_mat(ctx0,
  852. model->layers[il].wkb,
  853. cur)),
  854. n_embd/n_head, n_head, N),
  855. KQ_pos, n_rot, 0, 0);
  856. // store key and value to memory
  857. {
  858. // compute the transposed [N, n_embd] V matrix
  859. // wv shape [n_embd, n_embd, 1, 1]
  860. // Vcur shape [n_embd, N, 1, 1]
  861. struct ggml_tensor * Vcur = ggml_cont(ctx0,
  862. ggml_transpose(ctx0,
  863. ggml_reshape_2d(ctx0,
  864. ggml_mul_mat(ctx0,
  865. model->layers[il].wva,
  866. ggml_mul_mat(ctx0,
  867. model->layers[il].wvb,
  868. cur)),
  869. n_embd, N)));
  870. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  871. // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
  872. // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
  873. // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
  874. /* {
  875. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  876. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  877. ( n_ctx)*ggml_element_size(kv_self.v),
  878. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  879. // important: storing RoPE-ed version of K in the KV cache!
  880. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  881. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  882. } //*/
  883. kc = ggml_set_1d(ctx0, kc, ggml_reshape_1d(ctx0, Kcur, n_embd*N), (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  884. vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
  885. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  886. }
  887. // Qcur shape [n_embd/n_head, n_head, N, 1]
  888. // Q shape [n_embd/n_head, N, n_head, 1]
  889. struct ggml_tensor * Q =
  890. ggml_permute(ctx0,
  891. Qcur,
  892. 0, 2, 1, 3);
  893. // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
  894. // K shape [n_embd/n_head, n_past + N, n_head, 1]
  895. struct ggml_tensor * K =
  896. ggml_permute(ctx0,
  897. ggml_reshape_3d(ctx0,
  898. ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
  899. n_embd/n_head, n_head, n_past + N),
  900. 0, 2, 1, 3);
  901. // K * Q
  902. // KQ shape [n_past + N, N, n_head, 1]
  903. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  904. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  905. // KQ_scaled shape [n_past + N, N, n_head, 1]
  906. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
  907. // KQ_masked = mask_past(KQ_scaled)
  908. // KQ_masked shape [n_past + N, N, n_head, 1]
  909. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  910. // KQ = soft_max(KQ_masked)
  911. // KQ_soft_max shape [n_past + N, N, n_head, 1]
  912. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  913. // split cached V into n_head heads
  914. //// V shape [n_past + N, n_embd/n_head, n_head, 1]
  915. // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
  916. struct ggml_tensor * V =
  917. ggml_view_3d(ctx0, vc,
  918. n_past + N, n_embd/n_head, n_head,
  919. n_ctx*ggml_element_size(vc),
  920. n_ctx*ggml_element_size(vc)*n_embd/n_head,
  921. il*n_ctx*ggml_element_size(vc)*n_embd);
  922. // KQV shape [n_embd/n_head, N, n_head, 1]
  923. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  924. // KQV_merged = KQV.permute(0, 2, 1, 3)
  925. // KQV_merged shape [n_embd/n_head, n_head, N, 1]
  926. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  927. // KQV_merged shape
  928. // cur = KQV_merged.contiguous().view(n_embd, N)
  929. // cur shape [n_embd,N,1,1]
  930. cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
  931. // cur = ggml_cpy(ctx0,
  932. // KQV_merged,
  933. // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  934. // projection (no bias)
  935. // cur shape [n_embd,N,1,1]
  936. cur = ggml_mul_mat(ctx0,
  937. model->layers[il].woa,
  938. ggml_mul_mat(ctx0,
  939. model->layers[il].wob,
  940. cur));
  941. }
  942. // inpFF shape [n_embd,N,1,1]
  943. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  944. // feed-forward network
  945. {
  946. // norm
  947. {
  948. // cur shape [n_embd,N,1,1]
  949. cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
  950. // cur = ffn_norm*cur
  951. // cur shape [n_embd,N,1,1]
  952. cur = ggml_mul(ctx0,
  953. ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
  954. cur);
  955. }
  956. // tmp shape [n_ff,N,1,1]
  957. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  958. model->layers[il].w3,
  959. cur);
  960. // cur shape [n_ff,N,1,1]
  961. cur = ggml_mul_mat(ctx0,
  962. model->layers[il].w1,
  963. cur);
  964. // SILU activation
  965. // cur shape [n_ff,N,1,1]
  966. cur = ggml_silu(ctx0, cur);
  967. // cur shape [n_ff,N,1,1]
  968. cur = ggml_mul(ctx0, cur, tmp);
  969. // cur shape [n_embd,N,1,1]
  970. cur = ggml_mul_mat(ctx0,
  971. model->layers[il].w2,
  972. cur);
  973. }
  974. // cur shape [n_embd,N,1,1]
  975. cur = ggml_add(ctx0, cur, inpFF);
  976. // input for next layer
  977. // inpL shape [n_embd,N,1,1]
  978. inpL = cur;
  979. }
  980. // norm
  981. {
  982. // inpL shape [n_embd,N,1,1]
  983. inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  984. // inpL = norm*inpL
  985. // inpL shape [n_embd,N,1,1]
  986. inpL = ggml_mul(ctx0,
  987. ggml_repeat(ctx0, model->norm, inpL),
  988. inpL);
  989. //embeddings = inpL;
  990. }
  991. // lm_head
  992. // inpL shape [n_vocab,N,1,1]
  993. inpL = ggml_mul_mat(ctx0,
  994. model->outputa,
  995. ggml_mul_mat(ctx0,
  996. model->outputb,
  997. inpL));
  998. // ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  999. // run the computation
  1000. ggml_build_forward_expand(gf, inpL);
  1001. return inpL;
  1002. }
  1003. static void sample_softmax(struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
  1004. assert(ggml_is_matrix(logits));
  1005. assert(ggml_is_matrix(probs));
  1006. assert(ggml_is_vector(best_samples));
  1007. assert(logits->ne[1] == best_samples->ne[0]);
  1008. assert(logits->ne[0] == probs->ne[0]);
  1009. assert(logits->ne[1] == probs->ne[1]);
  1010. for (int i = 0; i < logits->ne[1]; ++i) {
  1011. float max_logit = ggml_get_f32_1d(logits, i * logits->ne[0]);
  1012. ggml_set_i32_1d(best_samples, i, 0);
  1013. for (int k = 0; k < logits->ne[0]; ++k) {
  1014. float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
  1015. if (logit > max_logit) {
  1016. max_logit = logit;
  1017. ggml_set_i32_1d(best_samples, i, k);
  1018. }
  1019. }
  1020. float psum = 0;
  1021. for (int k = 0; k < logits->ne[0]; ++k) {
  1022. float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
  1023. float p = (logit == -INFINITY) ? 0 : expf(logit - max_logit);
  1024. psum += p;
  1025. ggml_set_f32_1d(probs, i * probs->ne[0] + k, p);
  1026. }
  1027. for (int k = 0; k < logits->ne[0]; ++k) {
  1028. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1029. ggml_set_f32_1d(probs, i * probs->ne[0] + k, p / psum);
  1030. }
  1031. }
  1032. }
  1033. static void sample_softmax_batch(
  1034. struct ggml_context * ctx, struct ggml_tensor * logits, struct ggml_tensor * probs,
  1035. struct ggml_tensor * best_samples
  1036. ) {
  1037. GGML_ASSERT(ggml_is_matrix(best_samples));
  1038. GGML_ASSERT(ggml_is_3d(logits));
  1039. GGML_ASSERT(ggml_is_3d(probs));
  1040. int n_tokens = best_samples->ne[0];
  1041. int n_batch = best_samples->ne[1];
  1042. int n_vocab = logits->ne[0];
  1043. GGML_ASSERT(n_tokens == logits->ne[1]);
  1044. GGML_ASSERT(n_batch == logits->ne[2]);
  1045. GGML_ASSERT(n_vocab == probs->ne[0]);
  1046. GGML_ASSERT(n_tokens == probs->ne[1]);
  1047. GGML_ASSERT(n_batch == probs->ne[2]);
  1048. for (int k = 0; k < n_batch; ++k) {
  1049. struct ggml_tensor * best_samples_k = ggml_view_1d(ctx,
  1050. best_samples,
  1051. best_samples->ne[0],
  1052. k*best_samples->nb[1]);
  1053. struct ggml_tensor * logits_k = ggml_view_2d(ctx,
  1054. logits,
  1055. logits->ne[0],
  1056. logits->ne[1],
  1057. logits->nb[1],
  1058. k*logits->nb[2]);
  1059. struct ggml_tensor * probs_k = ggml_view_2d(ctx,
  1060. probs,
  1061. probs->ne[0],
  1062. probs->ne[1],
  1063. probs->nb[1],
  1064. k*probs->nb[2]);
  1065. sample_softmax(logits_k, probs_k, best_samples_k);
  1066. }
  1067. }
  1068. static void print_row(struct ggml_tensor * probs, int i) {
  1069. for (int k = 0; k < probs->ne[0]; ++k) {
  1070. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1071. printf(" %.2f", p);
  1072. }
  1073. printf("\n");
  1074. }
  1075. static void print_matrix(struct ggml_tensor * probs) {
  1076. assert(ggml_is_matrix(probs));
  1077. for (int i = 0; i < probs->ne[1]; ++i) {
  1078. for (int k = 0; k < probs->ne[0]; ++k) {
  1079. float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
  1080. printf(" %.2f", p);
  1081. }
  1082. printf("\n");
  1083. }
  1084. }
  1085. static void print_token(int token, int n_vocab) {
  1086. for (int k = 0; k < token; ++k) {
  1087. printf(" ");
  1088. }
  1089. printf("X");
  1090. for (int k = token+1; k < n_vocab; ++k) {
  1091. printf(" ");
  1092. }
  1093. printf("\n");
  1094. }
  1095. static void print_tokens(struct ggml_tensor * tokens, int n_vocab) {
  1096. for (int i=0; i<tokens->ne[0]; ++i) {
  1097. int token = ggml_get_i32_1d(tokens, i);
  1098. print_token(token, n_vocab);
  1099. }
  1100. }
  1101. static void get_example_targets(int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
  1102. int n_tokens = tokens_input->ne[0];
  1103. int n_vocab = targets->ne[0];
  1104. float randomness = 0.0f;
  1105. // ggml_set_zero(targets);
  1106. ggml_set_f32(targets, -1.0f);
  1107. ggml_set_i32_1d(tokens_input, 0, 0);
  1108. for (int i=1; i<n_tokens+1; ++i) {
  1109. float x = example_id + i * 3.14159f * 2.0f * 1.0f * 0.5f / n_tokens;
  1110. float y = sinf(x);//*cosf(x*1.1f+1.0f);
  1111. float z = (y+1.0f)*0.5f; // scale to [0..1]
  1112. z += (frand()-0.5f)*(randomness/n_vocab);
  1113. z = (z < 0.0f) ? 0.0f : (z > 1.0f) ? 1.0f : z; // clamp to [0..1]
  1114. int token = std::max(1,std::min(1+(int)(z*(float)(n_vocab-1)), n_vocab-1));
  1115. ggml_set_f32_1d(targets, (i-1)*n_vocab + token, +1.0f);
  1116. if (i<n_tokens) {
  1117. ggml_set_i32_1d(tokens_input, i, token);
  1118. }
  1119. }
  1120. }
  1121. static void get_example_targets_batch(
  1122. struct ggml_context * ctx, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets
  1123. ) {
  1124. GGML_ASSERT(ggml_is_matrix(tokens_input));
  1125. GGML_ASSERT(ggml_is_3d(targets));
  1126. int n_tokens = tokens_input->ne[0];
  1127. int n_batch = tokens_input->ne[1];
  1128. GGML_ASSERT(n_tokens == targets->ne[1]);
  1129. GGML_ASSERT(n_batch == targets->ne[2]);
  1130. for (int k=0; k<n_batch; ++k) {
  1131. struct ggml_tensor * tokens_input_k = ggml_view_1d(ctx,
  1132. tokens_input,
  1133. tokens_input->ne[0],
  1134. k*tokens_input->nb[1]);
  1135. struct ggml_tensor * targets_k = ggml_view_2d(ctx,
  1136. targets,
  1137. targets->ne[0],
  1138. targets->ne[1],
  1139. targets->nb[1],
  1140. k*targets->nb[2]);
  1141. get_example_targets(example_id*n_batch + k, tokens_input_k, targets_k);
  1142. }
  1143. }
  1144. static void lshift_examples(struct ggml_tensor * tokens_input, struct ggml_tensor * targets, int n_shift) {
  1145. int n_tokens = tokens_input->ne[0];
  1146. int n_vocab = targets->ne[0];
  1147. for (int i=0; i<n_tokens-n_shift; ++i) {
  1148. ggml_set_i32_1d(tokens_input, i, ggml_get_i32_1d(tokens_input, i + n_shift));
  1149. for (int k=0; k<n_vocab; ++k) {
  1150. ggml_set_f32_1d(targets, i*n_vocab + k, ggml_get_f32_1d(targets, (i + n_shift)*n_vocab + k));
  1151. }
  1152. }
  1153. }
  1154. static struct ggml_tensor * square_error_loss(
  1155. struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b
  1156. ) {
  1157. // todo: instead of a-b: a[1:]-b[:-1]
  1158. return ggml_sum(ctx, ggml_sqr(ctx, ggml_sub(ctx, a, b)));
  1159. }
  1160. static struct ggml_tensor * cross_entropy_loss(
  1161. struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b
  1162. ) {
  1163. const float eps = 1e-3f;
  1164. return
  1165. ggml_sum(ctx,
  1166. ggml_neg(ctx,
  1167. ggml_sum_rows(ctx,
  1168. ggml_mul(ctx,
  1169. ggml_soft_max(ctx, a),
  1170. ggml_log(ctx,
  1171. ggml_add1(ctx,
  1172. ggml_soft_max(ctx, b),
  1173. ggml_new_f32(ctx, eps)))))));
  1174. }
  1175. int main(int argc, char ** argv) {
  1176. if (argc < 1) {
  1177. fprintf(stderr, "usage: %s\n", argv[0]);
  1178. return 1;
  1179. }
  1180. struct ggml_init_params lcparams;
  1181. lcparams.mem_size = 1024ll*1024ll*1024ll;
  1182. lcparams.mem_buffer = NULL;
  1183. lcparams.no_alloc = false;
  1184. struct llama_model model;
  1185. model.hparams.n_vocab = 8;
  1186. model.hparams.n_ctx = 8;
  1187. model.hparams.n_embd = 32;
  1188. model.hparams.n_mult = 2;
  1189. model.hparams.n_head = 8;
  1190. model.hparams.n_layer = 1;
  1191. model.hparams.n_rot = std::min(16u, model.hparams.n_embd / model.hparams.n_head);
  1192. // model.hparams.n_embd = 32;
  1193. // model.hparams.n_mult = 2;
  1194. // model.hparams.n_head = 4;
  1195. // model.hparams.n_layer = 8;
  1196. // model.hparams.n_rot = 8;
  1197. model.ctx = ggml_init(lcparams);
  1198. printf("init model\n");
  1199. init_model(&model);
  1200. set_param_model(&model);
  1201. randomize_model(&model, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
  1202. /*
  1203. struct llama_model_lora model_lora;
  1204. // model.hparams.n_vocab = 6;
  1205. // model.hparams.n_ctx = 64;
  1206. // model.hparams.n_embd = 128;
  1207. // model.hparams.n_mult = 2;
  1208. // model.hparams.n_head = 8;
  1209. // model.hparams.n_layer = 6;
  1210. // model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
  1211. model_lora.hparams.n_vocab = 16;
  1212. model_lora.hparams.n_ctx = 32;
  1213. model_lora.hparams.n_embd = 256;
  1214. model_lora.hparams.n_mult = 2;
  1215. model_lora.hparams.n_head = 16;
  1216. model_lora.hparams.n_layer = 1;
  1217. model_lora.hparams.n_lora = 64;
  1218. model_lora.hparams.n_rot = MIN(16, model_lora.hparams.n_embd / model_lora.hparams.n_head);
  1219. // model.hparams.n_rot = (model.hparams.n_embd / model.hparams.n_head) / 2;
  1220. // model.hparams.n_embd = 32;
  1221. // model.hparams.n_mult = 2;
  1222. // model.hparams.n_head = 4;
  1223. // model.hparams.n_layer = 8;
  1224. // model.hparams.n_rot = 8;
  1225. model_lora.ctx = ggml_init(lcparams);
  1226. printf("init model_lora\n");
  1227. init_model_lora(&model_lora);
  1228. set_param_model_lora(&model_lora);
  1229. randomize_model_lora(&model_lora, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
  1230. */
  1231. int n_batch = 8;
  1232. // key + value cache for the self attention
  1233. struct llama_kv_cache kv_self;
  1234. printf("init_kv_cache\n");
  1235. kv_self.ctx = model.ctx;
  1236. init_kv_cache(&kv_self, &model, n_batch);
  1237. //init_kv_cache_lora(&kv_self, &model_lora);
  1238. size_t compute_size = 1024ll*1024ll*1024ll;
  1239. uint8_t * compute_addr = new uint8_t[compute_size];
  1240. int n_examples = 256;
  1241. int n_tokens = model.hparams.n_ctx;
  1242. int n_vocab = model.hparams.n_vocab;
  1243. std::vector<uint8_t> work_buffer;
  1244. for (int ex=0; ex<n_examples; ++ex) {
  1245. struct ggml_init_params params = {
  1246. /*.mem_size =*/ compute_size,
  1247. /*.mem_buffer =*/ compute_addr,
  1248. /*.no_alloc =*/ false,
  1249. };
  1250. struct ggml_context * ctx0 = ggml_init(params);
  1251. struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1252. struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1253. struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
  1254. struct ggml_tensor * targets = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
  1255. int n_past = 0;
  1256. struct ggml_cgraph * gf = NULL;
  1257. gf = ggml_new_graph_custom(ctx0, LLAMA_TRAIN_MAX_NODES, true);
  1258. get_example_targets_batch(ctx0, 64*ex+0, tokens_input, targets);
  1259. struct ggml_tensor * logits = forward_batch(&model, &kv_self, ctx0, gf, tokens_input, n_tokens, n_past, n_batch);
  1260. // struct ggml_tensor * e = cross_entropy_loss(ctx0, targets, logits);
  1261. struct ggml_tensor * e = square_error_loss(ctx0, targets, logits);
  1262. ggml_build_forward_expand(gf, e);
  1263. ggml_graph_compute_helper(work_buffer, gf, /*n_threads*/ 1);
  1264. float error_before_opt = ggml_get_f32_1d(e, 0);
  1265. struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_TYPE_LBFGS);
  1266. opt_params_lbfgs.print_forward_graph = false;
  1267. opt_params_lbfgs.print_backward_graph = false;
  1268. opt_params_lbfgs.lbfgs.n_iter = 16;
  1269. ggml_opt(ctx0, opt_params_lbfgs, e);
  1270. //
  1271. ggml_build_forward_expand(gf, e);
  1272. ggml_graph_compute_helper(work_buffer, gf, /*n_threads*/ 1);
  1273. float error_after_opt = ggml_get_f32_1d(e, 0);
  1274. if (ex % 8 == 0) {
  1275. printf("Example %d\n", (ex+1));
  1276. printf("error_before_opt: %.2f\n", error_before_opt);
  1277. printf("error_after_opt: %.2f\n", error_after_opt);
  1278. }
  1279. if (ex % 64 == 0) {
  1280. sample_softmax_batch(ctx0, logits, after_opt_probs, after_opt_best_samples);
  1281. // printf("probabilities after optimization:\n");
  1282. // print_matrix(after_opt_probs);
  1283. printf("best samples after optimization:\n");
  1284. print_tokens(after_opt_best_samples, n_vocab);
  1285. }
  1286. ggml_free(ctx0);
  1287. }
  1288. {
  1289. int n_gen = 128;
  1290. int sample_ctx = n_tokens-n_tokens/8;
  1291. printf("Generating %d tokens.\n", n_gen);
  1292. struct ggml_tensor * tokens_input = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, n_tokens);
  1293. struct ggml_tensor * targets = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, n_vocab, n_tokens);
  1294. get_example_targets(137, tokens_input, targets);
  1295. for (int i=sample_ctx; i<n_tokens; ++i) {
  1296. ggml_set_i32_1d(tokens_input, i, n_vocab/2);
  1297. }
  1298. for (int i=0; i<sample_ctx-1; ++i) {
  1299. print_token(ggml_get_i32_1d(tokens_input, i), n_vocab);
  1300. }
  1301. printf("---\n");
  1302. for (int i=0; i<n_gen; ++i) {
  1303. struct ggml_init_params params = {
  1304. /*.mem_size =*/ compute_size,
  1305. /*.mem_buffer =*/ compute_addr,
  1306. /*.no_alloc =*/ false,
  1307. };
  1308. struct ggml_context * ctx0 = ggml_init(params);
  1309. struct ggml_cgraph * gf = NULL;
  1310. gf = ggml_new_graph_custom(ctx0, LLAMA_TRAIN_MAX_NODES, true);
  1311. int n_past = 0;
  1312. struct ggml_tensor * logits = forward(&model, &kv_self, ctx0, gf, tokens_input, sample_ctx, n_past);
  1313. ggml_build_forward_expand(gf, logits);
  1314. ggml_graph_compute_helper(work_buffer, gf, /*n_threads*/ 1);
  1315. struct ggml_tensor * best_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sample_ctx);
  1316. struct ggml_tensor * probs = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab, sample_ctx);
  1317. sample_softmax(logits, probs, best_samples);
  1318. // int sample_at = n_tokens-1;
  1319. int token = ggml_get_i32_1d(best_samples, sample_ctx-1);
  1320. // print_row(probs, sample_at);
  1321. print_token(token, n_vocab);
  1322. lshift_examples(tokens_input, targets, 1);
  1323. ggml_set_i32_1d(tokens_input, 0, 0);
  1324. ggml_set_i32_1d(tokens_input, sample_ctx-1, token);
  1325. ggml_free(ctx0);
  1326. }
  1327. }
  1328. print_matrix(model.tok_embeddings);
  1329. printf("done\n");
  1330. // ggml_free(kv_self.ctx);
  1331. // ggml_free(model_lora.ctx);
  1332. ggml_free(model.ctx);
  1333. return 0;
  1334. }