baby-llama.cpp 61 KB

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