baby-llama.cpp 65 KB

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