| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640 |
- #include "ggml.h"
- #include "train.h"
- #include <vector>
- #include <cassert>
- #include <cstdlib>
- #include <cstring>
- #include <random>
- #include <vector>
- #if defined(_MSC_VER)
- #pragma warning(disable: 4244 4267) // possible loss of data
- #endif
- #ifdef LLAMA_DEFAULT_RMS_EPS
- constexpr float rms_norm_eps = LLAMA_DEFAULT_RMS_EPS;
- #else
- constexpr float rms_norm_eps = 5e-6f;
- #endif
- static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
- struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
- if (plan.work_size > 0) {
- buf.resize(plan.work_size);
- plan.work_data = buf.data();
- }
- ggml_graph_compute(graph, &plan);
- }
- static struct ggml_tensor * randomize_tensor(
- struct ggml_tensor * tensor, int ndims, const int64_t ne[], float fmin, float fmax
- ) {
- switch (ndims) {
- case 1:
- for (int i0 = 0; i0 < ne[0]; i0++) {
- ((float *)tensor->data)[i0] = frand()*(fmax - fmin) + fmin;
- }
- break;
- case 2:
- for (int i1 = 0; i1 < ne[1]; i1++) {
- for (int i0 = 0; i0 < ne[0]; i0++) {
- ((float *)tensor->data)[i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
- }
- }
- break;
- case 3:
- for (int i2 = 0; i2 < ne[2]; i2++) {
- for (int i1 = 0; i1 < ne[1]; i1++) {
- for (int i0 = 0; i0 < ne[0]; i0++) {
- ((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
- }
- }
- }
- break;
- case 4:
- for (int i3 = 0; i3 < ne[3]; i3++) {
- for (int i2 = 0; i2 < ne[2]; i2++) {
- for (int i1 = 0; i1 < ne[1]; i1++) {
- for (int i0 = 0; i0 < ne[0]; i0++) {
- ((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
- }
- }
- }
- }
- break;
- default:
- assert(false);
- }
- return tensor;
- }
- struct llama_hparams {
- uint32_t n_vocab = 32000;
- uint32_t n_ctx = 512; // this is provided as user input?
- uint32_t n_embd = 4096;
- uint32_t n_mult = 4;
- uint32_t n_head = 32;
- uint32_t n_layer = 32;
- uint32_t n_rot = 64;
- bool operator!=(const llama_hparams & other) const {
- return memcmp(this, &other, sizeof(llama_hparams));
- }
- };
- static uint32_t get_n_ff(const struct llama_hparams* hparams) {
- const uint32_t n_ff = ((2*(4*hparams->n_embd)/3 + hparams->n_mult - 1)/hparams->n_mult)*hparams->n_mult;
- return n_ff;
- }
- struct llama_hparams_lora {
- uint32_t n_vocab = 32000;
- uint32_t n_ctx = 512; // this is provided as user input?
- uint32_t n_embd = 4096;
- uint32_t n_mult = 4;
- uint32_t n_head = 32;
- uint32_t n_layer = 32;
- uint32_t n_rot = 64;
- uint32_t n_lora = 64;
- bool operator!=(const llama_hparams_lora & other) const {
- return memcmp(this, &other, sizeof(llama_hparams_lora)) != 0;
- }
- };
- struct llama_layer {
- // normalization
- struct ggml_tensor * attention_norm;
- // attention
- struct ggml_tensor * wq;
- struct ggml_tensor * wk;
- struct ggml_tensor * wv;
- struct ggml_tensor * wo;
- // normalization
- struct ggml_tensor * ffn_norm;
- // ff
- struct ggml_tensor * w1;
- struct ggml_tensor * w2;
- struct ggml_tensor * w3;
- };
- struct llama_layer_lora {
- // normalization
- struct ggml_tensor * attention_norm;
- // attention
- struct ggml_tensor * wqa;
- struct ggml_tensor * wqb;
- struct ggml_tensor * wka;
- struct ggml_tensor * wkb;
- struct ggml_tensor * wva;
- struct ggml_tensor * wvb;
- struct ggml_tensor * woa;
- struct ggml_tensor * wob;
- // normalization
- struct ggml_tensor * ffn_norm;
- // ff
- struct ggml_tensor * w1;
- struct ggml_tensor * w2;
- struct ggml_tensor * w3;
- };
- struct llama_kv_cache {
- struct ggml_context * ctx = NULL;
- struct ggml_tensor * k;
- struct ggml_tensor * v;
- // llama_ctx_buffer buf;
- int n; // number of tokens currently in the cache
- };
- struct llama_model {
- struct ggml_context * ctx = NULL;
- llama_hparams hparams;
- struct ggml_tensor * tok_embeddings;
- struct ggml_tensor * norm;
- struct ggml_tensor * output;
- std::vector<llama_layer> layers;
- };
- struct llama_model_lora {
- struct ggml_context * ctx = NULL;
- llama_hparams_lora hparams;
- struct ggml_tensor * tok_embeddings;
- struct ggml_tensor * norm;
- struct ggml_tensor * outputa;
- struct ggml_tensor * outputb;
- std::vector<llama_layer_lora> layers;
- };
- static void init_model(struct llama_model * model) {
- const auto & hparams = model->hparams;
- const uint32_t n_embd = hparams.n_embd;
- const uint32_t n_layer = hparams.n_layer;
- const uint32_t n_vocab = hparams.n_vocab;
- const uint32_t n_ff = get_n_ff(&hparams);
- struct ggml_context * ctx = model->ctx;
- model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
- model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
- model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("output.weight", {n_embd, n_vocab});
- model->layers.resize(n_layer);
- for (uint32_t i = 0; i < n_layer; ++i) {
- auto & layer = model->layers[i];
- // std::string layers_i = "layers." + std::to_string(i);
- layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
- layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
- layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
- layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
- layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
- layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
- layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
- layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
- layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
- }
- }
- static void init_model_lora(struct llama_model_lora * model) {
- const auto & hparams = model->hparams;
- const uint32_t n_embd = hparams.n_embd;
- const uint32_t n_mult = hparams.n_mult;
- const uint32_t n_layer = hparams.n_layer;
- const uint32_t n_vocab = hparams.n_vocab;
- const uint32_t n_lora = hparams.n_lora;
- const uint32_t n_ff = ((2*(4*n_embd)/3 + n_mult - 1)/n_mult)*n_mult;
- struct ggml_context * ctx = model->ctx;
- model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
- model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
- model->outputa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_vocab); // ("output.weight", {n_embd, n_vocab});
- model->outputb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // ("output.weight", {n_embd, n_vocab});
- model->layers.resize(n_layer);
- for (uint32_t i = 0; i < n_layer; ++i) {
- auto & layer = model->layers[i];
- // std::string layers_i = "layers." + std::to_string(i);
- layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
- layer.wqa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
- layer.wqb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
- layer.wka = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
- layer.wkb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
- layer.wva = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
- layer.wvb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
- layer.woa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
- layer.wob = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
- layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
- layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
- layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
- layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
- }
- }
- static void set_param_model(struct llama_model * model) {
- const auto& hparams = model->hparams;
- const uint32_t n_layer = hparams.n_layer;
- struct ggml_context* ctx = model->ctx;
- ggml_set_param(ctx, model->tok_embeddings);
- ggml_set_param(ctx, model->norm);
- ggml_set_param(ctx, model->output);
- for (uint32_t i = 0; i < n_layer; ++i) {
- auto & layer = model->layers[i];
- ggml_set_param(ctx, layer.attention_norm);
- ggml_set_param(ctx, layer.wq);
- ggml_set_param(ctx, layer.wk);
- ggml_set_param(ctx, layer.wv);
- ggml_set_param(ctx, layer.wo);
- ggml_set_param(ctx, layer.ffn_norm);
- ggml_set_param(ctx, layer.w1);
- ggml_set_param(ctx, layer.w2);
- ggml_set_param(ctx, layer.w3);
- }
- }
- static void set_param_model_lora(struct llama_model_lora * model) {
- const auto& hparams = model->hparams;
- const uint32_t n_layer = hparams.n_layer;
- struct ggml_context* ctx = model->ctx;
- ggml_set_param(ctx, model->tok_embeddings);
- ggml_set_param(ctx, model->norm);
- ggml_set_param(ctx, model->outputa);
- ggml_set_param(ctx, model->outputb);
- for (uint32_t i = 0; i < n_layer; ++i) {
- auto & layer = model->layers[i];
- ggml_set_param(ctx, layer.attention_norm);
- ggml_set_param(ctx, layer.wqa);
- ggml_set_param(ctx, layer.wqb);
- ggml_set_param(ctx, layer.wka);
- ggml_set_param(ctx, layer.wkb);
- ggml_set_param(ctx, layer.wva);
- ggml_set_param(ctx, layer.wvb);
- ggml_set_param(ctx, layer.woa);
- ggml_set_param(ctx, layer.wob);
- ggml_set_param(ctx, layer.ffn_norm);
- ggml_set_param(ctx, layer.w1);
- ggml_set_param(ctx, layer.w2);
- ggml_set_param(ctx, layer.w3);
- }
- }
- static void randomize_model(struct llama_model * model, int seed, float mean, float std, float min, float max) {
- const auto & hparams = model->hparams;
- const uint32_t n_layer = hparams.n_layer;
- struct random_normal_distribution * rnd = init_random_normal_distribution(seed, mean, std, min, max);
- randomize_tensor_normal(model->tok_embeddings , rnd);
- randomize_tensor_normal(model->norm , rnd);
- randomize_tensor_normal(model->output , rnd);
- for (uint32_t i = 0; i < n_layer; ++i) {
- auto & layer = model->layers[i];
- randomize_tensor_normal(layer.attention_norm, rnd);
- randomize_tensor_normal(layer.wq, rnd);
- randomize_tensor_normal(layer.wk, rnd);
- randomize_tensor_normal(layer.wv, rnd);
- randomize_tensor_normal(layer.wo, rnd);
- randomize_tensor_normal(layer.ffn_norm, rnd);
- randomize_tensor_normal(layer.w1, rnd);
- randomize_tensor_normal(layer.w2, rnd);
- randomize_tensor_normal(layer.w3, rnd);
- }
- free_random_normal_distribution(rnd);
- }
- static void randomize_model_lora(
- struct llama_model_lora * model, int seed, float mean, float std, float min, float max
- ) {
- const auto & hparams = model->hparams;
- const uint32_t n_layer = hparams.n_layer;
- struct random_normal_distribution * rnd = init_random_normal_distribution(seed, mean, std, min, max);
- randomize_tensor_normal(model->tok_embeddings, rnd);
- randomize_tensor_normal(model->norm , rnd);
- randomize_tensor_normal(model->outputa , rnd);
- randomize_tensor_normal(model->outputb , rnd);
- for (uint32_t i = 0; i < n_layer; ++i) {
- auto & layer = model->layers[i];
- randomize_tensor_normal(layer.attention_norm, rnd);
- randomize_tensor_normal(layer.wqa, rnd);
- randomize_tensor_normal(layer.wqb, rnd);
- randomize_tensor_normal(layer.wka, rnd);
- randomize_tensor_normal(layer.wkb, rnd);
- randomize_tensor_normal(layer.wva, rnd);
- randomize_tensor_normal(layer.wvb, rnd);
- randomize_tensor_normal(layer.woa, rnd);
- randomize_tensor_normal(layer.wob, rnd);
- randomize_tensor_normal(layer.ffn_norm, rnd);
- randomize_tensor_normal(layer.w1, rnd);
- randomize_tensor_normal(layer.w2, rnd);
- randomize_tensor_normal(layer.w3, rnd);
- }
- free_random_normal_distribution(rnd);
- }
- static void init_kv_cache(struct llama_kv_cache* cache, struct llama_model * model, int n_batch) {
- const auto & hparams = model->hparams;
- const uint32_t n_ctx = hparams.n_ctx;
- const uint32_t n_embd = hparams.n_embd;
- const uint32_t n_layer = hparams.n_layer;
- const int64_t n_mem = n_layer*n_ctx*n_batch;
- const int64_t n_elements = n_embd*n_mem;
- // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
- // struct ggml_init_params params;
- // params.mem_size = cache.buf.size;
- // params.mem_buffer = cache.buf.addr;
- // params.no_alloc = false;
- if (!cache->ctx) {
- struct ggml_init_params params;
- params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
- params.mem_buffer = NULL;
- params.no_alloc = false;
- cache->ctx = ggml_init(params);
- if (!cache->ctx) {
- fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
- exit(1);
- }
- }
- cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
- cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
- }
- static bool init_kv_cache_lora(struct llama_kv_cache* cache, struct llama_model_lora * model, int n_batch) {
- const auto & hparams = model->hparams;
- const uint32_t n_ctx = hparams.n_ctx;
- const uint32_t n_embd = hparams.n_embd;
- const uint32_t n_layer = hparams.n_layer;
- const int64_t n_mem = n_layer*n_ctx*n_batch;
- const int64_t n_elements = n_embd*n_mem;
- // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
- // struct ggml_init_params params;
- // params.mem_size = cache.buf.size;
- // params.mem_buffer = cache.buf.addr;
- // params.no_alloc = false;
- if (!cache->ctx) {
- struct ggml_init_params params;
- params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
- params.mem_buffer = NULL;
- params.no_alloc = false;
- cache->ctx = ggml_init(params);
- if (!cache->ctx) {
- fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
- return false;
- }
- }
- cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
- cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
- return true;
- }
- static struct ggml_tensor * forward(
- struct llama_model * model,
- struct llama_kv_cache * cache,
- struct ggml_context * ctx0,
- struct ggml_cgraph * gf,
- struct ggml_tensor * tokens_input,
- const int n_tokens,
- const int n_past
- ) {
- const int N = n_tokens;
- struct llama_kv_cache& kv_self = *cache;
- const auto & hparams = model->hparams;
- const int n_ctx = hparams.n_ctx;
- const int n_embd = hparams.n_embd;
- const int n_layer = hparams.n_layer;
- const int n_head = hparams.n_head;
- const int n_rot = hparams.n_rot;
- struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
- memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
- struct ggml_tensor * kc = kv_self.k;
- struct ggml_tensor * vc = kv_self.v;
- struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
- {
- int * data = (int *) KQ_pos->data;
- for (int i = 0; i < N; ++i) {
- data[i] = n_past + i;
- }
- }
- // inpL shape [n_embd,N,1,1]
- struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
- for (int il = 0; il < n_layer; ++il) {
- struct ggml_tensor * inpSA = inpL;
- struct ggml_tensor * cur;
- // lctx.use_buf(ctx0, 0);
- // norm
- {
- // cur shape [n_embd,N,1,1]
- cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
- // cur = attention_norm*cur
- cur = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
- cur);
- }
- // self-attention
- {
- // compute Q and K and RoPE them
- // wq shape [n_embd, n_embd, 1, 1]
- // wk shape [n_embd, n_embd, 1, 1]
- // Qcur shape [n_embd/n_head, n_head, N, 1]
- // Kcur shape [n_embd/n_head, n_head, N, 1]
- 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);
- 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);
- // store key and value to memory
- {
- // compute the transposed [N, n_embd] V matrix
- // wv shape [n_embd, n_embd, 1, 1]
- // Vcur shape [n_embd, N, 1, 1]
- 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)));
- // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
- // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
- // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
- // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
- /* {
- 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));
- struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
- ( n_ctx)*ggml_element_size(kv_self.v),
- (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
- // important: storing RoPE-ed version of K in the KV cache!
- ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
- ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
- } //*/
- 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));
- vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
- (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
- }
- // Qcur shape [n_embd/n_head, n_head, N, 1]
- // Q shape [n_embd/n_head, N, n_head, 1]
- struct ggml_tensor * Q =
- ggml_permute(ctx0,
- Qcur,
- 0, 2, 1, 3);
- // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
- // K shape [n_embd/n_head, n_past + N, n_head, 1]
- struct ggml_tensor * K =
- ggml_permute(ctx0,
- ggml_reshape_3d(ctx0,
- ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
- n_embd/n_head, n_head, n_past + N),
- 0, 2, 1, 3);
- // K * Q
- // KQ shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
- // KQ_scaled = KQ / sqrt(n_embd/n_head)
- // KQ_scaled shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
- // KQ_masked = mask_past(KQ_scaled)
- // KQ_masked shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
- // KQ = soft_max(KQ_masked)
- // KQ_soft_max shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
- // split cached V into n_head heads
- //// V shape [n_past + N, n_embd/n_head, n_head, 1]
- // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
- struct ggml_tensor * V =
- ggml_view_3d(ctx0, vc,
- n_past + N, n_embd/n_head, n_head,
- n_ctx*ggml_element_size(vc),
- n_ctx*ggml_element_size(vc)*n_embd/n_head,
- il*n_ctx*ggml_element_size(vc)*n_embd);
- // KQV shape [n_embd/n_head, N, n_head, 1]
- struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
- // KQV_merged = KQV.permute(0, 2, 1, 3)
- // KQV_merged shape [n_embd/n_head, n_head, N, 1]
- struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
- // KQV_merged shape
- // cur = KQV_merged.contiguous().view(n_embd, N)
- // cur shape [n_embd,N,1,1]
- cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
- // cur = ggml_cpy(ctx0,
- // KQV_merged,
- // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
- // projection (no bias)
- // cur shape [n_embd,N,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].wo,
- cur);
- }
- // lctx.use_buf(ctx0, 1);
- // inpFF shape [n_embd,N,1,1]
- struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
- // feed-forward network
- {
- // norm
- {
- // cur shape [n_embd,N,1,1]
- cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
- // cur = ffn_norm*cur
- // cur shape [n_embd,N,1,1]
- cur = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
- cur);
- }
- // tmp shape [n_ff,N,1,1]
- struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
- model->layers[il].w3,
- cur);
- // cur shape [n_ff,N,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].w1,
- cur);
- // SILU activation
- // cur shape [n_ff,N,1,1]
- cur = ggml_silu(ctx0, cur);
- // cur shape [n_ff,N,1,1]
- cur = ggml_mul(ctx0, cur, tmp);
- // cur shape [n_embd,N,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].w2,
- cur);
- }
- // cur shape [n_embd,N,1,1]
- cur = ggml_add(ctx0, cur, inpFF);
- // input for next layer
- // inpL shape [n_embd,N,1,1]
- inpL = cur;
- }
- // norm
- {
- // inpL shape [n_embd,N,1,1]
- inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
- // inpL = norm*inpL
- // inpL shape [n_embd,N,1,1]
- inpL = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->norm, inpL),
- inpL);
- //embeddings = inpL;
- }
- // lm_head
- // inpL shape [n_vocab,N,1,1]
- inpL = ggml_mul_mat(ctx0, model->output, inpL);
- // run the computation
- ggml_build_forward_expand(gf, inpL);
- return inpL;
- }
- static struct ggml_tensor * forward_batch(
- struct llama_model * model,
- struct llama_kv_cache * cache,
- struct ggml_context * ctx0,
- struct ggml_cgraph * gf,
- struct ggml_tensor * tokens_input,
- const int n_tokens,
- const int n_past,
- const int n_batch
- ) {
- const int N = n_tokens;
- struct llama_kv_cache& kv_self = *cache;
- const auto & hparams = model->hparams;
- const int n_ctx = hparams.n_ctx;
- const int n_vocab = hparams.n_vocab;
- const int n_embd = hparams.n_embd;
- const int n_layer = hparams.n_layer;
- const int n_head = hparams.n_head;
- const int n_rot = hparams.n_rot;
- const int n_ff = get_n_ff(&hparams);
- struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
- memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
- struct ggml_tensor * kc = kv_self.k;
- struct ggml_tensor * vc = kv_self.v;
- struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
- {
- int * data = (int *) KQ_pos->data;
- for (int i = 0; i < N; ++i) {
- data[i] = n_past + i;
- }
- }
- // inpL shape [n_embd,N*n_batch,1]
- struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
- assert_shape_2d(inpL, n_embd, N*n_batch);
- for (int il = 0; il < n_layer; ++il) {
- struct ggml_tensor * inpSA = inpL;
- struct ggml_tensor * cur;
- // lctx.use_buf(ctx0, 0);
- // norm
- {
- // cur shape [n_embd,N*n_batch,1,1]
- cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
- assert_shape_2d(cur, n_embd, N*n_batch);
- // cur = attention_norm*cur
- cur = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
- cur);
- assert_shape_2d(cur, n_embd, N*n_batch);
- }
- // self-attention
- {
- // compute Q and K and RoPE them
- // wq shape [n_embd, n_embd, 1, 1]
- // wk shape [n_embd, n_embd, 1, 1]
- // Qcur shape [n_embd/n_head, n_head, N, n_batch]
- // Kcur shape [n_embd/n_head, n_head, N, n_batch]
- 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);
- 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);
- assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
- assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
- // store key and value to memory
- {
- // compute the transposed [N, n_embd] V matrix
- // wv shape [n_embd, n_embd, 1, 1]
- // Vcur shape [N, n_embd, n_batch, 1]
- struct ggml_tensor * Vcur = ggml_cont(ctx0,
- ggml_permute(ctx0,
- ggml_reshape_3d(ctx0,
- ggml_mul_mat(ctx0,
- model->layers[il].wv,
- cur),
- n_embd, N, n_batch),
- 1, 0, 2, 3));
- assert_shape_3d(Vcur, N, n_embd, n_batch);
- // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
- // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
- // k shape [n_embd * N, n_batch] == kv_self.k[:,n_past:n_past+N,:,il]
- // v shape [N, n_embd, n_batch, 1] == kv_self.v[:,n_past:n_past+N,:,il]
- /* {
- 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));
- struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
- ( n_ctx)*ggml_element_size(kv_self.v),
- (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
- // important: storing RoPE-ed version of K in the KV cache!
- ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
- ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
- } //*/
- kc = ggml_set_2d(ctx0, kc,
- ggml_reshape_2d(ctx0, Kcur, n_embd*N, n_batch),
- ggml_element_size(kc)*n_embd*n_ctx,
- (ggml_element_size(kc)*n_embd)*(il*n_batch*n_ctx + n_past));
- vc = ggml_set_2d(ctx0, vc,
- ggml_reshape_2d(ctx0, Vcur, N*n_embd, n_batch),
- ggml_element_size(vc)*n_ctx*n_embd,
- ggml_element_size(vc)*(n_past + il*n_embd*n_batch*n_ctx));
- assert_shape_1d(kc, n_embd * n_ctx * n_batch * n_layer);
- assert_shape_1d(vc, n_embd * n_ctx * n_batch * n_layer);
- }
- // Qcur shape [n_embd/n_head, n_head, N, n_batch]
- // Q shape [n_embd/n_head, N, n_head, n_batch]
- struct ggml_tensor * Q =
- ggml_permute(ctx0,
- Qcur,
- 0, 2, 1, 3);
- assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
- // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
- // K shape [n_embd/n_head, n_past + N, n_head, n_batch]
- struct ggml_tensor * K =
- ggml_permute(ctx0,
- ggml_reshape_4d(ctx0,
- ggml_view_3d(ctx0,
- kc,
- n_embd,
- (n_past + N),
- n_batch,
- n_embd*ggml_element_size(kc),
- n_ctx*n_embd*ggml_element_size(kc),
- il*n_batch*n_ctx*n_embd*ggml_element_size(kc)),
- n_embd/n_head, n_head, n_past + N, n_batch),
- 0, 2, 1, 3);
- assert_shape_4d(K, n_embd/n_head, n_past + N, n_head, n_batch);
- // K * Q
- // KQ shape [n_past + N, N, n_head, n_batch]
- struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
- assert_shape_4d(KQ, n_past + N, N, n_head, n_batch);
- // KQ_scaled = KQ / sqrt(n_embd/n_head)
- // KQ_scaled shape [n_past + N, N, n_head, n_batch]
- struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
- assert_shape_4d(KQ_scaled, n_past + N, N, n_head, n_batch);
- // KQ_masked = mask_past(KQ_scaled)
- // KQ_masked shape [n_past + N, N, n_head, n_batch]
- struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
- assert_shape_4d(KQ_masked, n_past + N, N, n_head, n_batch);
- // KQ = soft_max(KQ_masked)
- // KQ_soft_max shape [n_past + N, N, n_head, n_batch]
- struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
- assert_shape_4d(KQ_soft_max, n_past + N, N, n_head, n_batch);
- // split cached V into n_head heads
- // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
- // V shape [n_past + N, n_embd/n_head, n_head, n_batch] == kv_self.v[:(n_past+N),:,:,il]
- struct ggml_tensor * V =
- ggml_view_4d(ctx0, vc,
- n_past + N, n_embd/n_head, n_head, n_batch,
- ggml_element_size(vc)*n_ctx,
- ggml_element_size(vc)*n_ctx*n_embd/n_head,
- ggml_element_size(vc)*n_ctx*n_embd,
- il*n_batch*n_ctx*n_embd*ggml_element_size(vc));
- assert_shape_4d(V, n_past + N, n_embd/n_head, n_head, n_batch);
- // KQV shape [n_embd/n_head, N, n_head, n_batch]
- struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
- assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
- // KQV_merged = KQV.permute(0, 2, 1, 3)
- // KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
- struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
- assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
- // KQV_merged shape
- // cur = KQV_merged.contiguous().view(n_embd, N)
- // cur shape [n_embd,N*n_batch,1,1]
- cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
- assert_shape_2d(cur, n_embd, N*n_batch);
- // cur = ggml_cpy(ctx0,
- // KQV_merged,
- // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
- // projection (no bias)
- // cur shape [n_embd,N*n_batch,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].wo,
- cur);
- assert_shape_2d(cur, n_embd, N*n_batch);
- }
- // lctx.use_buf(ctx0, 1);
- // inpFF shape [n_embd,N*n_batch,1,1]
- struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
- assert_shape_2d(inpFF, n_embd, N*n_batch);
- // feed-forward network
- {
- // norm
- {
- // cur shape [n_embd,N*n_batch,1,1]
- cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
- assert_shape_2d(cur, n_embd, N*n_batch);
- // cur = ffn_norm*cur
- // cur shape [n_embd,N*n_batch,1,1]
- cur = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
- cur);
- assert_shape_2d(cur, n_embd, N*n_batch);
- }
- // tmp shape [n_ff,N*n_batch,1,1]
- struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
- model->layers[il].w3,
- cur);
- assert_shape_2d(tmp, n_ff, N*n_batch);
- // cur shape [n_ff,N*n_batch,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].w1,
- cur);
- assert_shape_2d(cur, n_ff, N*n_batch);
- // SILU activation
- // cur shape [n_ff,N*n_batch,1,1]
- cur = ggml_silu(ctx0, cur);
- assert_shape_2d(cur, n_ff, N*n_batch);
- // cur shape [n_ff,N*n_batch,1,1]
- cur = ggml_mul(ctx0, cur, tmp);
- assert_shape_2d(cur, n_ff, N*n_batch);
- // cur shape [n_embd,N*n_batch,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].w2,
- cur);
- assert_shape_2d(cur, n_embd, N*n_batch);
- }
- // cur shape [n_embd,N*n_batch,1,1]
- cur = ggml_add(ctx0, cur, inpFF);
- assert_shape_2d(cur, n_embd, N*n_batch);
- // input for next layer
- // inpL shape [n_embd,N*n_batch,1,1]
- inpL = cur;
- assert_shape_2d(inpL, n_embd, N*n_batch);
- }
- // norm
- {
- // inpL shape [n_embd,N*n_batch,1,1]
- inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
- assert_shape_2d(inpL, n_embd, N*n_batch);
- // inpL = norm*inpL
- // inpL shape [n_embd,N*n_batch,1,1]
- inpL = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->norm, inpL),
- inpL);
- assert_shape_2d(inpL, n_embd, N*n_batch);
- //embeddings = inpL;
- }
- // lm_head
- // inpL shape [n_vocab,N*n_batch,1,1]
- inpL = ggml_mul_mat(ctx0, model->output, inpL);
- assert_shape_2d(inpL, n_vocab, N*n_batch);
- {
- // inpL shape [n_vocab,N,n_batch,1]
- inpL = ggml_reshape_3d(ctx0,
- inpL,
- n_vocab, N, n_batch);
- assert_shape_3d(inpL, n_vocab, N, n_batch);
- }
- // run the computation
- ggml_build_forward_expand(gf, inpL);
- return inpL;
- }
- static struct ggml_tensor * forward_lora(
- struct llama_model_lora * model,
- struct llama_kv_cache * cache,
- struct ggml_context * ctx0,
- struct ggml_cgraph * gf,
- struct ggml_tensor * tokens_input,
- const int n_tokens,
- const int n_past
- ) {
- const int N = n_tokens;
- struct llama_kv_cache& kv_self = *cache;
- const auto & hparams = model->hparams;
- const int n_ctx = hparams.n_ctx;
- const int n_embd = hparams.n_embd;
- const int n_layer = hparams.n_layer;
- const int n_head = hparams.n_head;
- const int n_rot = hparams.n_rot;
- struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
- memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
- struct ggml_tensor * kc = kv_self.k;
- struct ggml_tensor * vc = kv_self.v;
- struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
- {
- int * data = (int *) KQ_pos->data;
- for (int i = 0; i < N; ++i) {
- data[i] = n_past + i;
- }
- }
- // inpL shape [n_embd,N,1,1]
- struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
- for (int il = 0; il < n_layer; ++il) {
- struct ggml_tensor * inpSA = inpL;
- struct ggml_tensor * cur;
- // norm
- {
- // cur shape [n_embd,N,1,1]
- cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
- // cur = attention_norm*cur
- cur = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
- cur);
- }
- // self-attention
- {
- // compute Q and K and RoPE them
- // wq shape [n_embd, n_embd, 1, 1]
- // wk shape [n_embd, n_embd, 1, 1]
- // Qcur shape [n_embd/n_head, n_head, N, 1]
- // Kcur shape [n_embd/n_head, n_head, N, 1]
- struct ggml_tensor * Qcur = ggml_rope(ctx0,
- ggml_reshape_3d(ctx0,
- ggml_mul_mat(ctx0,
- model->layers[il].wqa,
- ggml_mul_mat(ctx0,
- model->layers[il].wqb,
- cur)),
- n_embd/n_head, n_head, N),
- KQ_pos, n_rot, 0, 0);
- struct ggml_tensor * Kcur = ggml_rope(ctx0,
- ggml_reshape_3d(ctx0,
- ggml_mul_mat(ctx0,
- model->layers[il].wka,
- ggml_mul_mat(ctx0,
- model->layers[il].wkb,
- cur)),
- n_embd/n_head, n_head, N),
- KQ_pos, n_rot, 0, 0);
- // store key and value to memory
- {
- // compute the transposed [N, n_embd] V matrix
- // wv shape [n_embd, n_embd, 1, 1]
- // Vcur shape [n_embd, N, 1, 1]
- struct ggml_tensor * Vcur = ggml_cont(ctx0,
- ggml_transpose(ctx0,
- ggml_reshape_2d(ctx0,
- ggml_mul_mat(ctx0,
- model->layers[il].wva,
- ggml_mul_mat(ctx0,
- model->layers[il].wvb,
- cur)),
- n_embd, N)));
- // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
- // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
- // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
- // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
- /* {
- 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));
- struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
- ( n_ctx)*ggml_element_size(kv_self.v),
- (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
- // important: storing RoPE-ed version of K in the KV cache!
- ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
- ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
- } //*/
- 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));
- vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
- (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
- }
- // Qcur shape [n_embd/n_head, n_head, N, 1]
- // Q shape [n_embd/n_head, N, n_head, 1]
- struct ggml_tensor * Q =
- ggml_permute(ctx0,
- Qcur,
- 0, 2, 1, 3);
- // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
- // K shape [n_embd/n_head, n_past + N, n_head, 1]
- struct ggml_tensor * K =
- ggml_permute(ctx0,
- ggml_reshape_3d(ctx0,
- ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
- n_embd/n_head, n_head, n_past + N),
- 0, 2, 1, 3);
- // K * Q
- // KQ shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
- // KQ_scaled = KQ / sqrt(n_embd/n_head)
- // KQ_scaled shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, 1.0f/sqrtf(float(n_embd)/n_head));
- // KQ_masked = mask_past(KQ_scaled)
- // KQ_masked shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
- // KQ = soft_max(KQ_masked)
- // KQ_soft_max shape [n_past + N, N, n_head, 1]
- struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
- // split cached V into n_head heads
- //// V shape [n_past + N, n_embd/n_head, n_head, 1]
- // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
- struct ggml_tensor * V =
- ggml_view_3d(ctx0, vc,
- n_past + N, n_embd/n_head, n_head,
- n_ctx*ggml_element_size(vc),
- n_ctx*ggml_element_size(vc)*n_embd/n_head,
- il*n_ctx*ggml_element_size(vc)*n_embd);
- // KQV shape [n_embd/n_head, N, n_head, 1]
- struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
- // KQV_merged = KQV.permute(0, 2, 1, 3)
- // KQV_merged shape [n_embd/n_head, n_head, N, 1]
- struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
- // KQV_merged shape
- // cur = KQV_merged.contiguous().view(n_embd, N)
- // cur shape [n_embd,N,1,1]
- cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
- // cur = ggml_cpy(ctx0,
- // KQV_merged,
- // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
- // projection (no bias)
- // cur shape [n_embd,N,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].woa,
- ggml_mul_mat(ctx0,
- model->layers[il].wob,
- cur));
- }
- // inpFF shape [n_embd,N,1,1]
- struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
- // feed-forward network
- {
- // norm
- {
- // cur shape [n_embd,N,1,1]
- cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
- // cur = ffn_norm*cur
- // cur shape [n_embd,N,1,1]
- cur = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
- cur);
- }
- // tmp shape [n_ff,N,1,1]
- struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
- model->layers[il].w3,
- cur);
- // cur shape [n_ff,N,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].w1,
- cur);
- // SILU activation
- // cur shape [n_ff,N,1,1]
- cur = ggml_silu(ctx0, cur);
- // cur shape [n_ff,N,1,1]
- cur = ggml_mul(ctx0, cur, tmp);
- // cur shape [n_embd,N,1,1]
- cur = ggml_mul_mat(ctx0,
- model->layers[il].w2,
- cur);
- }
- // cur shape [n_embd,N,1,1]
- cur = ggml_add(ctx0, cur, inpFF);
- // input for next layer
- // inpL shape [n_embd,N,1,1]
- inpL = cur;
- }
- // norm
- {
- // inpL shape [n_embd,N,1,1]
- inpL = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
- // inpL = norm*inpL
- // inpL shape [n_embd,N,1,1]
- inpL = ggml_mul(ctx0,
- ggml_repeat(ctx0, model->norm, inpL),
- inpL);
- //embeddings = inpL;
- }
- // lm_head
- // inpL shape [n_vocab,N,1,1]
- inpL = ggml_mul_mat(ctx0,
- model->outputa,
- ggml_mul_mat(ctx0,
- model->outputb,
- inpL));
- // ggml_set_scratch(ctx0, { 0, 0, nullptr, });
- // run the computation
- ggml_build_forward_expand(gf, inpL);
- return inpL;
- }
- static void sample_softmax(struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
- assert(ggml_is_matrix(logits));
- assert(ggml_is_matrix(probs));
- assert(ggml_is_vector(best_samples));
- assert(logits->ne[1] == best_samples->ne[0]);
- assert(logits->ne[0] == probs->ne[0]);
- assert(logits->ne[1] == probs->ne[1]);
- for (int i = 0; i < logits->ne[1]; ++i) {
- float max_logit = ggml_get_f32_1d(logits, i * logits->ne[0]);
- ggml_set_i32_1d(best_samples, i, 0);
- for (int k = 0; k < logits->ne[0]; ++k) {
- float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
- if (logit > max_logit) {
- max_logit = logit;
- ggml_set_i32_1d(best_samples, i, k);
- }
- }
- float psum = 0;
- for (int k = 0; k < logits->ne[0]; ++k) {
- float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
- float p = (logit == -INFINITY) ? 0 : expf(logit - max_logit);
- psum += p;
- ggml_set_f32_1d(probs, i * probs->ne[0] + k, p);
- }
- for (int k = 0; k < logits->ne[0]; ++k) {
- float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
- ggml_set_f32_1d(probs, i * probs->ne[0] + k, p / psum);
- }
- }
- }
- static void sample_softmax_batch(
- struct ggml_context * ctx, struct ggml_tensor * logits, struct ggml_tensor * probs,
- struct ggml_tensor * best_samples
- ) {
- GGML_ASSERT(ggml_is_matrix(best_samples));
- GGML_ASSERT(ggml_is_3d(logits));
- GGML_ASSERT(ggml_is_3d(probs));
- int n_tokens = best_samples->ne[0];
- int n_batch = best_samples->ne[1];
- int n_vocab = logits->ne[0];
- GGML_ASSERT(n_tokens == logits->ne[1]);
- GGML_ASSERT(n_batch == logits->ne[2]);
- GGML_ASSERT(n_vocab == probs->ne[0]);
- GGML_ASSERT(n_tokens == probs->ne[1]);
- GGML_ASSERT(n_batch == probs->ne[2]);
- for (int k = 0; k < n_batch; ++k) {
- struct ggml_tensor * best_samples_k = ggml_view_1d(ctx,
- best_samples,
- best_samples->ne[0],
- k*best_samples->nb[1]);
- struct ggml_tensor * logits_k = ggml_view_2d(ctx,
- logits,
- logits->ne[0],
- logits->ne[1],
- logits->nb[1],
- k*logits->nb[2]);
- struct ggml_tensor * probs_k = ggml_view_2d(ctx,
- probs,
- probs->ne[0],
- probs->ne[1],
- probs->nb[1],
- k*probs->nb[2]);
- sample_softmax(logits_k, probs_k, best_samples_k);
- }
- }
- static void print_row(struct ggml_tensor * probs, int i) {
- for (int k = 0; k < probs->ne[0]; ++k) {
- float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
- printf(" %.2f", p);
- }
- printf("\n");
- }
- static void print_matrix(struct ggml_tensor * probs) {
- assert(ggml_is_matrix(probs));
- for (int i = 0; i < probs->ne[1]; ++i) {
- for (int k = 0; k < probs->ne[0]; ++k) {
- float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
- printf(" %.2f", p);
- }
- printf("\n");
- }
- }
- static void print_token(int token, int n_vocab) {
- for (int k = 0; k < token; ++k) {
- printf(" ");
- }
- printf("X");
- for (int k = token+1; k < n_vocab; ++k) {
- printf(" ");
- }
- printf("\n");
- }
- static void print_tokens(struct ggml_tensor * tokens, int n_vocab) {
- for (int i=0; i<tokens->ne[0]; ++i) {
- int token = ggml_get_i32_1d(tokens, i);
- print_token(token, n_vocab);
- }
- }
- static void get_example_targets(int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
- int n_tokens = tokens_input->ne[0];
- int n_vocab = targets->ne[0];
- float randomness = 0.0f;
- // ggml_set_zero(targets);
- ggml_set_f32(targets, -1.0f);
- ggml_set_i32_1d(tokens_input, 0, 0);
- for (int i=1; i<n_tokens+1; ++i) {
- float x = example_id + i * 3.14159f * 2.0f * 1.0f * 0.5f / n_tokens;
- float y = sinf(x);//*cosf(x*1.1f+1.0f);
- float z = (y+1.0f)*0.5f; // scale to [0..1]
- z += (frand()-0.5f)*(randomness/n_vocab);
- z = (z < 0.0f) ? 0.0f : (z > 1.0f) ? 1.0f : z; // clamp to [0..1]
- int token = std::max(1,std::min(1+(int)(z*(float)(n_vocab-1)), n_vocab-1));
- ggml_set_f32_1d(targets, (i-1)*n_vocab + token, +1.0f);
- if (i<n_tokens) {
- ggml_set_i32_1d(tokens_input, i, token);
- }
- }
- }
- static void get_example_targets_batch(
- struct ggml_context * ctx, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets
- ) {
- GGML_ASSERT(ggml_is_matrix(tokens_input));
- GGML_ASSERT(ggml_is_3d(targets));
- int n_tokens = tokens_input->ne[0];
- int n_batch = tokens_input->ne[1];
- GGML_ASSERT(n_tokens == targets->ne[1]);
- GGML_ASSERT(n_batch == targets->ne[2]);
- for (int k=0; k<n_batch; ++k) {
- struct ggml_tensor * tokens_input_k = ggml_view_1d(ctx,
- tokens_input,
- tokens_input->ne[0],
- k*tokens_input->nb[1]);
- struct ggml_tensor * targets_k = ggml_view_2d(ctx,
- targets,
- targets->ne[0],
- targets->ne[1],
- targets->nb[1],
- k*targets->nb[2]);
- get_example_targets(example_id*n_batch + k, tokens_input_k, targets_k);
- }
- }
- static void lshift_examples(struct ggml_tensor * tokens_input, struct ggml_tensor * targets, int n_shift) {
- int n_tokens = tokens_input->ne[0];
- int n_vocab = targets->ne[0];
- for (int i=0; i<n_tokens-n_shift; ++i) {
- ggml_set_i32_1d(tokens_input, i, ggml_get_i32_1d(tokens_input, i + n_shift));
- for (int k=0; k<n_vocab; ++k) {
- ggml_set_f32_1d(targets, i*n_vocab + k, ggml_get_f32_1d(targets, (i + n_shift)*n_vocab + k));
- }
- }
- }
- static struct ggml_tensor * square_error_loss(
- struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b
- ) {
- // todo: instead of a-b: a[1:]-b[:-1]
- return ggml_sum(ctx, ggml_sqr(ctx, ggml_sub(ctx, a, b)));
- }
- static struct ggml_tensor * cross_entropy_loss(
- struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b
- ) {
- const float eps = 1e-3f;
- return
- ggml_sum(ctx,
- ggml_neg(ctx,
- ggml_sum_rows(ctx,
- ggml_mul(ctx,
- ggml_soft_max(ctx, a),
- ggml_log(ctx,
- ggml_add1(ctx,
- ggml_soft_max(ctx, b),
- ggml_new_f32(ctx, eps)))))));
- }
- int main(int argc, char ** argv) {
- if (argc < 1) {
- fprintf(stderr, "usage: %s\n", argv[0]);
- return 1;
- }
- struct ggml_init_params lcparams;
- lcparams.mem_size = 1024ll*1024ll*1024ll;
- lcparams.mem_buffer = NULL;
- lcparams.no_alloc = false;
- struct llama_model model;
- model.hparams.n_vocab = 8;
- model.hparams.n_ctx = 8;
- model.hparams.n_embd = 32;
- model.hparams.n_mult = 2;
- model.hparams.n_head = 8;
- model.hparams.n_layer = 1;
- model.hparams.n_rot = std::min(16u, model.hparams.n_embd / model.hparams.n_head);
- // model.hparams.n_embd = 32;
- // model.hparams.n_mult = 2;
- // model.hparams.n_head = 4;
- // model.hparams.n_layer = 8;
- // model.hparams.n_rot = 8;
- model.ctx = ggml_init(lcparams);
- printf("init model\n");
- init_model(&model);
- set_param_model(&model);
- randomize_model(&model, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
- /*
- struct llama_model_lora model_lora;
- // model.hparams.n_vocab = 6;
- // model.hparams.n_ctx = 64;
- // model.hparams.n_embd = 128;
- // model.hparams.n_mult = 2;
- // model.hparams.n_head = 8;
- // model.hparams.n_layer = 6;
- // model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
- model_lora.hparams.n_vocab = 16;
- model_lora.hparams.n_ctx = 32;
- model_lora.hparams.n_embd = 256;
- model_lora.hparams.n_mult = 2;
- model_lora.hparams.n_head = 16;
- model_lora.hparams.n_layer = 1;
- model_lora.hparams.n_lora = 64;
- model_lora.hparams.n_rot = MIN(16, model_lora.hparams.n_embd / model_lora.hparams.n_head);
- // model.hparams.n_rot = (model.hparams.n_embd / model.hparams.n_head) / 2;
- // model.hparams.n_embd = 32;
- // model.hparams.n_mult = 2;
- // model.hparams.n_head = 4;
- // model.hparams.n_layer = 8;
- // model.hparams.n_rot = 8;
- model_lora.ctx = ggml_init(lcparams);
- printf("init model_lora\n");
- init_model_lora(&model_lora);
- set_param_model_lora(&model_lora);
- randomize_model_lora(&model_lora, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
- */
- int n_batch = 8;
- // key + value cache for the self attention
- struct llama_kv_cache kv_self;
- printf("init_kv_cache\n");
- kv_self.ctx = model.ctx;
- init_kv_cache(&kv_self, &model, n_batch);
- //init_kv_cache_lora(&kv_self, &model_lora);
- size_t compute_size = 1024ll*1024ll*1024ll;
- uint8_t * compute_addr = new uint8_t[compute_size];
- int n_examples = 256;
- int n_tokens = model.hparams.n_ctx;
- int n_vocab = model.hparams.n_vocab;
- std::vector<uint8_t> work_buffer;
- for (int ex=0; ex<n_examples; ++ex) {
- struct ggml_init_params params = {
- /*.mem_size =*/ compute_size,
- /*.mem_buffer =*/ compute_addr,
- /*.no_alloc =*/ false,
- };
- struct ggml_context * ctx0 = ggml_init(params);
- struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
- struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
- struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
- struct ggml_tensor * targets = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
- int n_past = 0;
- struct ggml_cgraph * gf = NULL;
- gf = ggml_new_graph_custom(ctx0, LLAMA_TRAIN_MAX_NODES, true);
- get_example_targets_batch(ctx0, 64*ex+0, tokens_input, targets);
- struct ggml_tensor * logits = forward_batch(&model, &kv_self, ctx0, gf, tokens_input, n_tokens, n_past, n_batch);
- // struct ggml_tensor * e = cross_entropy_loss(ctx0, targets, logits);
- struct ggml_tensor * e = square_error_loss(ctx0, targets, logits);
- ggml_build_forward_expand(gf, e);
- ggml_graph_compute_helper(work_buffer, gf, /*n_threads*/ 1);
- float error_before_opt = ggml_get_f32_1d(e, 0);
- struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_TYPE_LBFGS);
- opt_params_lbfgs.print_forward_graph = false;
- opt_params_lbfgs.print_backward_graph = false;
- opt_params_lbfgs.lbfgs.n_iter = 16;
- ggml_opt(ctx0, opt_params_lbfgs, e);
- //
- ggml_build_forward_expand(gf, e);
- ggml_graph_compute_helper(work_buffer, gf, /*n_threads*/ 1);
- float error_after_opt = ggml_get_f32_1d(e, 0);
- if (ex % 8 == 0) {
- printf("Example %d\n", (ex+1));
- printf("error_before_opt: %.2f\n", error_before_opt);
- printf("error_after_opt: %.2f\n", error_after_opt);
- }
- if (ex % 64 == 0) {
- sample_softmax_batch(ctx0, logits, after_opt_probs, after_opt_best_samples);
- // printf("probabilities after optimization:\n");
- // print_matrix(after_opt_probs);
- printf("best samples after optimization:\n");
- print_tokens(after_opt_best_samples, n_vocab);
- }
- ggml_free(ctx0);
- }
- {
- int n_gen = 128;
- int sample_ctx = n_tokens-n_tokens/8;
- printf("Generating %d tokens.\n", n_gen);
- struct ggml_tensor * tokens_input = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, n_tokens);
- struct ggml_tensor * targets = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, n_vocab, n_tokens);
- get_example_targets(137, tokens_input, targets);
- for (int i=sample_ctx; i<n_tokens; ++i) {
- ggml_set_i32_1d(tokens_input, i, n_vocab/2);
- }
- for (int i=0; i<sample_ctx-1; ++i) {
- print_token(ggml_get_i32_1d(tokens_input, i), n_vocab);
- }
- printf("---\n");
- for (int i=0; i<n_gen; ++i) {
- struct ggml_init_params params = {
- /*.mem_size =*/ compute_size,
- /*.mem_buffer =*/ compute_addr,
- /*.no_alloc =*/ false,
- };
- struct ggml_context * ctx0 = ggml_init(params);
- struct ggml_cgraph * gf = NULL;
- gf = ggml_new_graph_custom(ctx0, LLAMA_TRAIN_MAX_NODES, true);
- int n_past = 0;
- struct ggml_tensor * logits = forward(&model, &kv_self, ctx0, gf, tokens_input, sample_ctx, n_past);
- ggml_build_forward_expand(gf, logits);
- ggml_graph_compute_helper(work_buffer, gf, /*n_threads*/ 1);
- struct ggml_tensor * best_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sample_ctx);
- struct ggml_tensor * probs = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab, sample_ctx);
- sample_softmax(logits, probs, best_samples);
- // int sample_at = n_tokens-1;
- int token = ggml_get_i32_1d(best_samples, sample_ctx-1);
- // print_row(probs, sample_at);
- print_token(token, n_vocab);
- lshift_examples(tokens_input, targets, 1);
- ggml_set_i32_1d(tokens_input, 0, 0);
- ggml_set_i32_1d(tokens_input, sample_ctx-1, token);
- ggml_free(ctx0);
- }
- }
- print_matrix(model.tok_embeddings);
- printf("done\n");
- // ggml_free(kv_self.ctx);
- // ggml_free(model_lora.ctx);
- ggml_free(model.ctx);
- return 0;
- }
|