llama.cpp 386 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113
  1. #include "llama-impl.h"
  2. #include "llama-chat.h"
  3. #include "llama-mmap.h"
  4. #include "llama-context.h"
  5. #include "llama-vocab.h"
  6. #include "llama-sampling.h"
  7. #include "llama-kv-cache.h"
  8. #include "llama-model-loader.h"
  9. #include "llama-model.h"
  10. #include "ggml.h"
  11. #include "ggml-alloc.h"
  12. #include "ggml-backend.h"
  13. #include "ggml-cpp.h"
  14. #include <algorithm>
  15. #include <array>
  16. #include <cassert>
  17. #include <cfloat>
  18. #include <cmath>
  19. #include <cstddef>
  20. #include <cstdint>
  21. #include <cstdio>
  22. #include <cstring>
  23. #include <ctime>
  24. #include <functional>
  25. #if defined(_MSC_VER)
  26. #pragma warning(disable: 4244 4267) // possible loss of data
  27. #endif
  28. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  29. static int llama_model_load(const std::string & fname, std::vector<std::string> & splits, llama_model & model, llama_model_params & params) {
  30. // loading time will be recalculated after the first eval, so
  31. // we take page faults deferred by mmap() into consideration
  32. model.t_load_us = 0;
  33. time_meas tm(model.t_load_us);
  34. model.t_start_us = tm.t_start_us;
  35. try {
  36. llama_model_loader ml(fname, splits, params.use_mmap, params.check_tensors, params.kv_overrides);
  37. ml.print_info();
  38. model.hparams.vocab_only = params.vocab_only;
  39. try {
  40. model.load_arch(ml);
  41. } catch(const std::exception & e) {
  42. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  43. }
  44. try {
  45. model.load_hparams(ml);
  46. } catch(const std::exception & e) {
  47. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  48. }
  49. try {
  50. model.load_vocab(ml);
  51. } catch(const std::exception & e) {
  52. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  53. }
  54. model.load_stats(ml);
  55. model.print_info();
  56. if (params.vocab_only) {
  57. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  58. return 0;
  59. }
  60. if (!model.load_tensors(ml)) {
  61. return -2;
  62. }
  63. } catch (const std::exception & err) {
  64. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  65. return -1;
  66. }
  67. return 0;
  68. }
  69. //
  70. // llm_build
  71. //
  72. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  73. enum llm_ffn_op_type {
  74. LLM_FFN_SILU,
  75. LLM_FFN_GELU,
  76. LLM_FFN_RELU,
  77. LLM_FFN_RELU_SQR,
  78. LLM_FFN_SWIGLU,
  79. };
  80. enum llm_ffn_gate_type {
  81. LLM_FFN_SEQ,
  82. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  83. };
  84. enum llm_norm_type {
  85. LLM_NORM,
  86. LLM_NORM_RMS,
  87. LLM_NORM_GROUP,
  88. };
  89. static struct ggml_tensor * llm_build_inp_embd(
  90. struct ggml_context * ctx,
  91. struct llama_context & lctx,
  92. const llama_hparams & hparams,
  93. const llama_ubatch & ubatch,
  94. struct ggml_tensor * tok_embd,
  95. const llm_build_cb & cb) {
  96. const int64_t n_embd = hparams.n_embd;
  97. struct ggml_tensor * inpL;
  98. if (ubatch.token) {
  99. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, ubatch.n_tokens);
  100. cb(lctx.inp_tokens, "inp_tokens", -1);
  101. ggml_set_input(lctx.inp_tokens);
  102. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  103. // apply lora for embedding tokens if needed
  104. for (auto & it : lctx.lora) {
  105. struct llama_adapter_lora_weight * lw = it.first->get_weight(tok_embd);
  106. if (lw == nullptr) {
  107. continue;
  108. }
  109. const float adapter_scale = it.second;
  110. const float scale = lw->get_scale(it.first->alpha, adapter_scale);
  111. struct ggml_tensor * inpL_delta = ggml_scale(ctx, ggml_mul_mat(
  112. ctx, lw->b, // non-transposed lora_b
  113. ggml_get_rows(ctx, lw->a, lctx.inp_tokens)
  114. ), scale);
  115. inpL = ggml_add(ctx, inpL, inpL_delta);
  116. }
  117. } else {
  118. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, ubatch.n_tokens);
  119. inpL = lctx.inp_embd;
  120. ggml_set_input(lctx.inp_embd);
  121. }
  122. // For Granite architecture
  123. if (hparams.f_embedding_scale != 0.0f) {
  124. inpL = ggml_scale(ctx, inpL, hparams.f_embedding_scale);
  125. }
  126. cb(inpL, "inp_embd", -1);
  127. return inpL;
  128. }
  129. static void llm_build_kv_store(
  130. struct ggml_context * ctx,
  131. const llama_hparams & hparams,
  132. const llama_cparams & cparams,
  133. const llama_kv_cache & kv,
  134. struct ggml_cgraph * graph,
  135. struct ggml_tensor * k_cur,
  136. struct ggml_tensor * v_cur,
  137. int32_t n_tokens,
  138. int32_t kv_head,
  139. const llm_build_cb & cb,
  140. int64_t il) {
  141. const int64_t n_ctx = cparams.n_ctx;
  142. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  143. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  144. GGML_ASSERT(kv.size == n_ctx);
  145. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa, ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa)*kv_head);
  146. cb(k_cache_view, "k_cache_view", il);
  147. // note: storing RoPE-ed version of K in the KV cache
  148. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  149. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  150. struct ggml_tensor * v_cache_view = nullptr;
  151. if (cparams.flash_attn) {
  152. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa, ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa)*kv_head);
  153. } else {
  154. // note: the V cache is transposed when not using flash attention
  155. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  156. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  157. (kv_head)*ggml_element_size(kv.v_l[il]));
  158. v_cur = ggml_transpose(ctx, v_cur);
  159. }
  160. cb(v_cache_view, "v_cache_view", il);
  161. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  162. }
  163. // do mat_mul, while optionally apply lora
  164. static struct ggml_tensor * llm_build_lora_mm(
  165. struct llama_context & lctx,
  166. struct ggml_context * ctx0,
  167. struct ggml_tensor * w,
  168. struct ggml_tensor * cur) {
  169. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  170. for (auto & it : lctx.lora) {
  171. struct llama_adapter_lora_weight * lw = it.first->get_weight(w);
  172. if (lw == nullptr) {
  173. continue;
  174. }
  175. const float adapter_scale = it.second;
  176. const float scale = lw->get_scale(it.first->alpha, adapter_scale);
  177. struct ggml_tensor * ab_cur = ggml_mul_mat(
  178. ctx0, lw->b,
  179. ggml_mul_mat(ctx0, lw->a, cur)
  180. );
  181. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  182. res = ggml_add(ctx0, res, ab_cur);
  183. }
  184. return res;
  185. }
  186. // do mat_mul_id, while optionally apply lora
  187. static struct ggml_tensor * llm_build_lora_mm_id(
  188. struct llama_context & lctx,
  189. struct ggml_context * ctx0,
  190. struct ggml_tensor * w, // struct ggml_tensor * as
  191. struct ggml_tensor * cur, // struct ggml_tensor * b
  192. struct ggml_tensor * ids) {
  193. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  194. for (auto & it : lctx.lora) {
  195. struct llama_adapter_lora_weight * lw = it.first->get_weight(w);
  196. if (lw == nullptr) {
  197. continue;
  198. }
  199. const float alpha = it.first->alpha;
  200. const float rank = (float) lw->b->ne[0];
  201. const float scale = alpha ? it.second * alpha / rank : it.second;
  202. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  203. ctx0, lw->b,
  204. ggml_mul_mat_id(ctx0, lw->a, cur, ids),
  205. ids
  206. );
  207. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  208. res = ggml_add(ctx0, res, ab_cur);
  209. }
  210. return res;
  211. }
  212. static struct ggml_tensor * llm_build_norm(
  213. struct ggml_context * ctx,
  214. struct ggml_tensor * cur,
  215. const llama_hparams & hparams,
  216. struct ggml_tensor * mw,
  217. struct ggml_tensor * mb,
  218. llm_norm_type type,
  219. const llm_build_cb & cb,
  220. int il) {
  221. switch (type) {
  222. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  223. case LLM_NORM_RMS: cur = ggml_rms_norm (ctx, cur, hparams.f_norm_rms_eps); break;
  224. case LLM_NORM_GROUP:
  225. {
  226. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], 1, cur->ne[1]);
  227. cur = ggml_group_norm(ctx, cur, hparams.n_norm_groups, hparams.f_norm_group_eps);
  228. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], cur->ne[2]);
  229. } break;
  230. }
  231. if (mw || mb) {
  232. cb(cur, "norm", il);
  233. }
  234. if (mw) {
  235. cur = ggml_mul(ctx, cur, mw);
  236. if (mb) {
  237. cb(cur, "norm_w", il);
  238. }
  239. }
  240. if (mb) {
  241. cur = ggml_add(ctx, cur, mb);
  242. }
  243. return cur;
  244. }
  245. static struct ggml_tensor * llm_build_ffn(
  246. struct ggml_context * ctx,
  247. struct llama_context & lctx,
  248. struct ggml_tensor * cur,
  249. struct ggml_tensor * up,
  250. struct ggml_tensor * up_b,
  251. struct ggml_tensor * up_s,
  252. struct ggml_tensor * gate,
  253. struct ggml_tensor * gate_b,
  254. struct ggml_tensor * gate_s,
  255. struct ggml_tensor * down,
  256. struct ggml_tensor * down_b,
  257. struct ggml_tensor * down_s,
  258. struct ggml_tensor * act_scales,
  259. llm_ffn_op_type type_op,
  260. llm_ffn_gate_type type_gate,
  261. const llm_build_cb & cb,
  262. int il) {
  263. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  264. cb(tmp, "ffn_up", il);
  265. if (up_b) {
  266. tmp = ggml_add(ctx, tmp, up_b);
  267. cb(tmp, "ffn_up_b", il);
  268. }
  269. if (up_s) {
  270. tmp = ggml_mul(ctx, tmp, up_s);
  271. cb(tmp, "ffn_up_s", il);
  272. }
  273. if (gate) {
  274. switch (type_gate) {
  275. case LLM_FFN_SEQ:
  276. {
  277. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  278. cb(cur, "ffn_gate", il);
  279. } break;
  280. case LLM_FFN_PAR:
  281. {
  282. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  283. cb(cur, "ffn_gate", il);
  284. } break;
  285. }
  286. if (gate_b) {
  287. cur = ggml_add(ctx, cur, gate_b);
  288. cb(cur, "ffn_gate_b", il);
  289. }
  290. if (gate_s) {
  291. cur = ggml_mul(ctx, cur, gate_s);
  292. cb(cur, "ffn_gate_s", il);
  293. }
  294. } else {
  295. cur = tmp;
  296. }
  297. switch (type_op) {
  298. case LLM_FFN_SILU:
  299. {
  300. cur = ggml_silu(ctx, cur);
  301. cb(cur, "ffn_silu", il);
  302. } break;
  303. case LLM_FFN_GELU:
  304. {
  305. cur = ggml_gelu(ctx, cur);
  306. cb(cur, "ffn_gelu", il);
  307. if (act_scales != NULL) {
  308. cur = ggml_div(ctx, cur, act_scales);
  309. cb(cur, "ffn_act", il);
  310. }
  311. } break;
  312. case LLM_FFN_RELU:
  313. {
  314. cur = ggml_relu(ctx, cur);
  315. cb(cur, "ffn_relu", il);
  316. } break;
  317. case LLM_FFN_RELU_SQR:
  318. {
  319. cur = ggml_relu(ctx, cur);
  320. cb(cur, "ffn_relu", il);
  321. cur = ggml_sqr(ctx, cur);
  322. cb(cur, "ffn_sqr(relu)", il);
  323. } break;
  324. case LLM_FFN_SWIGLU:
  325. {
  326. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  327. int64_t split_point = cur->ne[0] / 2;
  328. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  329. struct ggml_tensor * x1 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], split_point * ggml_element_size(cur)));
  330. x0 = ggml_silu(ctx, x0);
  331. cb(cur, "ffn_silu", il);
  332. cur = ggml_mul(ctx, x0, x1);
  333. cb(cur, "ffn_mul", il);
  334. } break;
  335. }
  336. if (type_gate == LLM_FFN_PAR) {
  337. cur = ggml_mul(ctx, cur, tmp);
  338. cb(cur, "ffn_gate_par", il);
  339. }
  340. if (down) {
  341. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  342. }
  343. if (down_b) {
  344. cb(cur, "ffn_down", il);
  345. }
  346. if (down_b) {
  347. cur = ggml_add(ctx, cur, down_b);
  348. }
  349. if (down_s) {
  350. cur = ggml_mul(ctx, cur, down_s);
  351. cb(cur, "ffn_down_s", il);
  352. }
  353. return cur;
  354. }
  355. static struct ggml_tensor * llm_build_moe_ffn(
  356. struct ggml_context * ctx,
  357. struct llama_context & lctx,
  358. struct ggml_tensor * cur,
  359. struct ggml_tensor * gate_inp,
  360. struct ggml_tensor * up_exps,
  361. struct ggml_tensor * gate_exps,
  362. struct ggml_tensor * down_exps,
  363. struct ggml_tensor * exp_probs_b,
  364. int64_t n_expert,
  365. int64_t n_expert_used,
  366. llm_ffn_op_type type_op,
  367. bool norm_w,
  368. bool scale_w,
  369. float w_scale,
  370. llama_expert_gating_func_type gating_op,
  371. const llm_build_cb & cb,
  372. int il) {
  373. int64_t n_embd = cur->ne[0];
  374. int64_t n_tokens = cur->ne[1];
  375. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  376. cb(logits, "ffn_moe_logits", il);
  377. ggml_tensor * probs = nullptr;
  378. switch (gating_op) {
  379. case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX:
  380. {
  381. probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  382. } break;
  383. case LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID:
  384. {
  385. probs = ggml_sigmoid(ctx, logits); // [n_expert, n_tokens]
  386. } break;
  387. default:
  388. GGML_ABORT("fatal error");
  389. }
  390. cb(probs, "ffn_moe_probs", il);
  391. // add experts selection bias - introduced in DeepSeek V3
  392. // leave probs unbiased as it's later used to get expert weights
  393. ggml_tensor * selection_probs = probs;
  394. if (exp_probs_b != nullptr) {
  395. selection_probs = ggml_add(ctx, probs, exp_probs_b);
  396. cb(selection_probs, "ffn_moe_probs_biased", il);
  397. }
  398. // select experts
  399. ggml_tensor * selected_experts = ggml_top_k(ctx, selection_probs, n_expert_used); // [n_expert_used, n_tokens]
  400. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  401. cb(selected_experts, "ffn_moe_topk", il);
  402. ggml_tensor * weights = ggml_get_rows(ctx,
  403. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  404. cb(weights, "ffn_moe_weights", il);
  405. if (norm_w) {
  406. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  407. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  408. cb(weights_sum, "ffn_moe_weights_sum", il);
  409. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  410. cb(weights, "ffn_moe_weights_norm", il);
  411. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  412. }
  413. if (scale_w) {
  414. weights = ggml_scale(ctx, weights, w_scale);
  415. cb(weights, "ffn_moe_weights_scaled", il);
  416. }
  417. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  418. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  419. cb(up, "ffn_moe_up", il);
  420. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  421. cb(gate, "ffn_moe_gate", il);
  422. switch (type_op) {
  423. case LLM_FFN_SILU:
  424. {
  425. gate = ggml_silu(ctx, gate);
  426. cb(gate, "ffn_moe_silu", il);
  427. } break;
  428. case LLM_FFN_GELU:
  429. {
  430. gate = ggml_gelu(ctx, gate);
  431. cb(gate, "ffn_moe_gelu", il);
  432. } break;
  433. default:
  434. GGML_ABORT("fatal error");
  435. }
  436. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  437. cb(par, "ffn_moe_gate_par", il);
  438. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  439. cb(experts, "ffn_moe_down", il);
  440. experts = ggml_mul(ctx, experts, weights);
  441. // aggregate experts
  442. ggml_tensor * moe_out = nullptr;
  443. for (int i = 0; i < n_expert_used; ++i) {
  444. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  445. experts->nb[2], i*experts->nb[1]);
  446. if (i == 0) {
  447. moe_out = cur_expert;
  448. } else {
  449. moe_out = ggml_add(ctx, moe_out, cur_expert);
  450. }
  451. }
  452. if (n_expert_used == 1) {
  453. // avoid returning a non-contiguous tensor
  454. moe_out = ggml_cont(ctx, moe_out);
  455. }
  456. return moe_out;
  457. }
  458. static struct ggml_tensor * llm_build_kqv(
  459. struct ggml_context * ctx,
  460. struct llama_context & lctx,
  461. const llama_kv_cache & kv,
  462. struct ggml_cgraph * graph,
  463. struct ggml_tensor * wo,
  464. struct ggml_tensor * wo_b,
  465. struct ggml_tensor * q_cur,
  466. struct ggml_tensor * kq_mask,
  467. int32_t n_tokens,
  468. int32_t n_kv,
  469. float kq_scale,
  470. const llm_build_cb & cb,
  471. int il) {
  472. const llama_model & model = lctx.model;
  473. const llama_hparams & hparams = lctx.model.hparams;
  474. const llama_cparams & cparams = lctx.cparams;
  475. const int64_t n_ctx = cparams.n_ctx;
  476. const int64_t n_head = hparams.n_head(il);
  477. const int64_t n_head_kv = hparams.n_head_kv(il);
  478. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  479. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  480. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  481. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  482. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  483. cb(q, "q", il);
  484. struct ggml_tensor * k =
  485. ggml_view_3d(ctx, kv.k_l[il],
  486. n_embd_head_k, n_kv, n_head_kv,
  487. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  488. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  489. 0);
  490. cb(k, "k", il);
  491. struct ggml_tensor * cur;
  492. if (cparams.flash_attn) {
  493. GGML_UNUSED(model);
  494. GGML_UNUSED(n_ctx);
  495. // split cached v into n_head heads (not transposed)
  496. struct ggml_tensor * v =
  497. ggml_view_3d(ctx, kv.v_l[il],
  498. n_embd_head_v, n_kv, n_head_kv,
  499. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  500. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  501. 0);
  502. cb(v, "v", il);
  503. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  504. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  505. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  506. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  507. } else {
  508. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  509. cb(kq, "kq", il);
  510. // note: this op tends to require high floating point range
  511. // while for some models F16 is enough, for others it is not, so we default to F32 here
  512. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  513. if (model.arch == LLM_ARCH_GROK) {
  514. // need to do the following:
  515. // multiply by attn_output_multiplyer of 0.08838834764831845
  516. // and then :
  517. // kq = 30 * tanh(kq / 30)
  518. // before the softmax below
  519. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  520. kq = ggml_scale(ctx, kq, 30);
  521. }
  522. if (hparams.attn_soft_cap) {
  523. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  524. kq = ggml_tanh(ctx, kq);
  525. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  526. }
  527. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  528. cb(kq, "kq_soft_max_ext", il);
  529. GGML_ASSERT(kv.size == n_ctx);
  530. // split cached v into n_head heads
  531. struct ggml_tensor * v =
  532. ggml_view_3d(ctx, kv.v_l[il],
  533. n_kv, n_embd_head_v, n_head_kv,
  534. ggml_element_size(kv.v_l[il])*n_ctx,
  535. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  536. 0);
  537. cb(v, "v", il);
  538. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  539. cb(kqv, "kqv", il);
  540. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  541. cb(kqv_merged, "kqv_merged", il);
  542. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  543. cb(cur, "kqv_merged_cont", il);
  544. }
  545. ggml_build_forward_expand(graph, cur);
  546. if (wo) {
  547. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  548. }
  549. if (wo_b) {
  550. cb(cur, "kqv_wo", il);
  551. }
  552. if (wo_b) {
  553. cur = ggml_add(ctx, cur, wo_b);
  554. }
  555. return cur;
  556. }
  557. static struct ggml_tensor * llm_build_kv(
  558. struct ggml_context * ctx,
  559. struct llama_context & lctx,
  560. const llama_kv_cache & kv,
  561. struct ggml_cgraph * graph,
  562. struct ggml_tensor * wo,
  563. struct ggml_tensor * wo_b,
  564. struct ggml_tensor * k_cur,
  565. struct ggml_tensor * v_cur,
  566. struct ggml_tensor * q_cur,
  567. struct ggml_tensor * kq_mask,
  568. int32_t n_tokens,
  569. int32_t kv_head,
  570. int32_t n_kv,
  571. float kq_scale,
  572. const llm_build_cb & cb,
  573. int il) {
  574. const llama_hparams & hparams = lctx.model.hparams;
  575. const llama_cparams & cparams = lctx.cparams;
  576. // these nodes are added to the graph together so that they are not reordered
  577. // by doing so, the number of splits in the graph is reduced
  578. ggml_build_forward_expand(graph, q_cur);
  579. ggml_build_forward_expand(graph, k_cur);
  580. ggml_build_forward_expand(graph, v_cur);
  581. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  582. struct ggml_tensor * cur;
  583. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b, q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  584. cb(cur, "kqv_out", il);
  585. return cur;
  586. }
  587. static struct ggml_tensor * llm_build_copy_mask_state(
  588. struct ggml_context * ctx,
  589. struct ggml_cgraph * graph,
  590. struct ggml_tensor * s,
  591. struct ggml_tensor * state_copy,
  592. struct ggml_tensor * state_mask,
  593. int32_t n_state,
  594. int32_t kv_size,
  595. int32_t kv_head,
  596. int32_t n_kv,
  597. int32_t n_seqs) {
  598. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  599. // copy states
  600. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  601. // this shrinks the tensors's ne[1] to n_kv
  602. states = ggml_get_rows(ctx, states, state_copy);
  603. // clear states of sequences which are starting at the beginning of this batch
  604. // FIXME: zero-out NANs?
  605. states = ggml_mul(ctx, states, state_mask);
  606. // copy states which won't be changed further (between n_seqs and n_kv)
  607. ggml_build_forward_expand(graph,
  608. ggml_cpy(ctx,
  609. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  610. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  611. // the part of the states that will be used and modified
  612. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  613. }
  614. // TODO: split
  615. static struct ggml_tensor * llm_build_mamba(
  616. struct ggml_context * ctx,
  617. struct llama_context & lctx,
  618. const llama_ubatch & ubatch,
  619. struct ggml_cgraph * graph,
  620. struct ggml_tensor * cur,
  621. struct ggml_tensor * state_copy,
  622. struct ggml_tensor * state_mask,
  623. int32_t kv_head,
  624. int32_t n_kv,
  625. const llm_build_cb & cb,
  626. int il) {
  627. const llama_model & model = lctx.model;
  628. const llama_hparams & hparams = model.hparams;
  629. const llama_kv_cache & kv = lctx.kv_self;
  630. const int64_t d_conv = hparams.ssm_d_conv;
  631. const int64_t d_inner = hparams.ssm_d_inner;
  632. const int64_t d_state = hparams.ssm_d_state;
  633. const int64_t dt_rank = hparams.ssm_dt_rank;
  634. const int64_t n_seqs = ubatch.n_seqs;
  635. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  636. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  637. // Use the same RMS norm as the final layer norm
  638. const float norm_rms_eps = hparams.f_norm_rms_eps;
  639. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  640. GGML_ASSERT(n_seqs != 0);
  641. GGML_ASSERT(ubatch.equal_seqs);
  642. GGML_ASSERT(ubatch.n_tokens == n_seq_tokens * n_seqs);
  643. struct ggml_tensor * conv_states_all = kv.k_l[il];
  644. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  645. // (ab)using the KV cache to store the states
  646. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  647. graph, conv_states_all, state_copy, state_mask,
  648. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  649. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  650. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  651. graph, ssm_states_all, state_copy, state_mask,
  652. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  653. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  654. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  655. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  656. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  657. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  658. // split the above in two
  659. // => {d_inner, n_seq_tokens, n_seqs}
  660. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  661. struct ggml_tensor * z = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], d_inner*ggml_element_size(xz));
  662. // conv
  663. {
  664. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  665. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  666. // copy last (d_conv - 1) columns back into the state cache
  667. struct ggml_tensor * last_conv = ggml_view_3d(ctx, conv_x, d_conv - 1, d_inner, n_seqs, conv_x->nb[1], conv_x->nb[2], n_seq_tokens*(conv_x->nb[0]));
  668. ggml_build_forward_expand(graph,
  669. ggml_cpy(ctx, last_conv,
  670. ggml_view_1d(ctx, conv_states_all,
  671. (d_conv - 1)*(d_inner)*(n_seqs),
  672. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  673. // 1D convolution
  674. // The equivalent is to make a self-overlapping view of conv_x
  675. // over d_conv columns at each stride in the 3rd dimension,
  676. // then element-wise multiply that with the conv1d weight,
  677. // then sum the elements of each row,
  678. // (the last two steps are a dot product over rows (also doable with mul_mat))
  679. // then permute away the ne[0] dimension,
  680. // and then you're left with the resulting x tensor.
  681. // For simultaneous sequences, all sequences need to have the same length.
  682. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  683. // bias
  684. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  685. x = ggml_silu(ctx, x);
  686. }
  687. // ssm
  688. {
  689. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  690. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  691. // split
  692. struct ggml_tensor * dt = ggml_view_3d(ctx, x_db, dt_rank, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], 0);
  693. struct ggml_tensor * B = ggml_view_3d(ctx, x_db, d_state, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], ggml_element_size(x_db)*dt_rank);
  694. struct ggml_tensor * C = ggml_view_3d(ctx, x_db, d_state, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], ggml_element_size(x_db)*(dt_rank+d_state));
  695. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  696. if (ssm_dt_b_c_rms) {
  697. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  698. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  699. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  700. }
  701. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  702. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  703. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  704. // Custom operator to optimize the parallel associative scan
  705. // as described in the Annex D of the Mamba paper.
  706. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  707. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  708. // store last states
  709. ggml_build_forward_expand(graph,
  710. ggml_cpy(ctx,
  711. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  712. ggml_view_1d(ctx, ssm_states_all, d_state*d_inner*n_seqs, kv_head*d_state*d_inner*ggml_element_size(ssm_states_all))));
  713. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  714. // TODO: skip computing output earlier for unused tokens
  715. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  716. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  717. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  718. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  719. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  720. }
  721. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  722. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  723. cb(cur, "mamba_out", il);
  724. return cur;
  725. }
  726. static struct ggml_tensor * llm_build_rwkv6_time_mix(
  727. struct llama_context & lctx,
  728. struct ggml_context * ctx,
  729. const struct llama_layer * layer,
  730. struct ggml_tensor * cur,
  731. struct ggml_tensor * x_prev,
  732. struct ggml_tensor ** wkv_state,
  733. size_t wkv_head_size,
  734. size_t head_count_kv) {
  735. size_t n_embd = cur->ne[0];
  736. size_t n_seq_tokens = cur->ne[1];
  737. size_t n_seqs = cur->ne[2];
  738. size_t head_size = wkv_head_size;
  739. size_t head_count = n_embd / head_size;
  740. size_t n_tokens = n_seqs * n_seq_tokens;
  741. bool is_qrwkv = layer->time_mix_first == nullptr;
  742. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  743. sx = ggml_reshape_2d(ctx, sx, n_embd, n_tokens);
  744. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  745. struct ggml_tensor * xxx = ggml_add(ctx, ggml_mul(ctx, sx, layer->time_mix_lerp_x), cur);
  746. xxx = ggml_reshape_4d(
  747. ctx,
  748. ggml_tanh(
  749. ctx,
  750. ggml_mul_mat(ctx, layer->time_mix_w1, xxx)
  751. ),
  752. layer->time_mix_w1->ne[1] / 5, 1, 5, n_tokens
  753. );
  754. xxx = ggml_cont(ctx, ggml_permute(ctx, xxx, 0, 1, 3, 2));
  755. xxx = ggml_mul_mat(
  756. ctx,
  757. ggml_reshape_4d(
  758. ctx,
  759. layer->time_mix_w2,
  760. layer->time_mix_w2->ne[0], layer->time_mix_w2->ne[1], 1, 5
  761. ),
  762. xxx
  763. );
  764. struct ggml_tensor *xw, *xk, *xv, *xr, *xg;
  765. if (layer->time_mix_lerp_fused) {
  766. // fusing these weights makes some performance improvement
  767. sx = ggml_reshape_3d(ctx, sx, n_embd, 1, n_tokens);
  768. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  769. xxx = ggml_add(ctx, ggml_mul(ctx, ggml_add(ctx, xxx, layer->time_mix_lerp_fused), sx), cur);
  770. xw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  771. xk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  772. xv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  773. xr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  774. xg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  775. } else {
  776. // for backward compatibility
  777. xw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  778. xk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  779. xv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  780. xr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  781. xg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  782. xw = ggml_add(ctx, ggml_mul(ctx, ggml_add(ctx, xw, layer->time_mix_lerp_w), sx), cur);
  783. xk = ggml_add(ctx, ggml_mul(ctx, ggml_add(ctx, xk, layer->time_mix_lerp_k), sx), cur);
  784. xv = ggml_add(ctx, ggml_mul(ctx, ggml_add(ctx, xv, layer->time_mix_lerp_v), sx), cur);
  785. xr = ggml_add(ctx, ggml_mul(ctx, ggml_add(ctx, xr, layer->time_mix_lerp_r), sx), cur);
  786. xg = ggml_add(ctx, ggml_mul(ctx, ggml_add(ctx, xg, layer->time_mix_lerp_g), sx), cur);
  787. }
  788. struct ggml_tensor * r = llm_build_lora_mm(lctx, ctx, layer->time_mix_receptance, xr);
  789. struct ggml_tensor * k = llm_build_lora_mm(lctx, ctx, layer->time_mix_key, xk);
  790. struct ggml_tensor * v = llm_build_lora_mm(lctx, ctx, layer->time_mix_value, xv);
  791. if (layer->time_mix_receptance_b) {
  792. r = ggml_add(ctx, r, layer->time_mix_receptance_b);
  793. }
  794. if (layer->time_mix_key_b) {
  795. k = ggml_add(ctx, k, layer->time_mix_key_b);
  796. }
  797. if (layer->time_mix_value_b) {
  798. v = ggml_add(ctx, v, layer->time_mix_value_b);
  799. }
  800. struct ggml_tensor * g = llm_build_lora_mm(lctx, ctx, layer->time_mix_gate, xg);
  801. if (is_qrwkv) {
  802. g = ggml_sigmoid(ctx, g);
  803. } else {
  804. g = ggml_silu(ctx, g);
  805. }
  806. if (head_count_kv != head_count) {
  807. GGML_ASSERT(head_count % head_count_kv == 0);
  808. k = ggml_reshape_4d(ctx, k, head_size, 1, head_count_kv, n_tokens);
  809. v = ggml_reshape_4d(ctx, v, head_size, 1, head_count_kv, n_tokens);
  810. struct ggml_tensor * tmp = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, head_size, head_count / head_count_kv, head_count_kv, n_tokens);
  811. k = ggml_repeat(ctx, k, tmp);
  812. v = ggml_repeat(ctx, v, tmp);
  813. }
  814. k = ggml_reshape_3d(ctx, k, head_size, head_count, n_tokens);
  815. v = ggml_reshape_3d(ctx, v, head_size, head_count, n_tokens);
  816. r = ggml_reshape_3d(ctx, r, head_size, head_count, n_tokens);
  817. struct ggml_tensor * w = ggml_mul_mat(
  818. ctx,
  819. layer->time_mix_decay_w2,
  820. ggml_tanh(
  821. ctx,
  822. ggml_mul_mat(ctx, layer->time_mix_decay_w1, xw)
  823. )
  824. );
  825. w = ggml_add(ctx, w, layer->time_mix_decay);
  826. w = ggml_exp(ctx, ggml_neg(ctx, ggml_exp(ctx, w)));
  827. w = ggml_reshape_3d(ctx, w, head_size, head_count, n_tokens);
  828. if (is_qrwkv) {
  829. // k = k * (1 - w)
  830. k = ggml_sub(ctx, k, ggml_mul(ctx, k, w));
  831. }
  832. struct ggml_tensor * wkv_output;
  833. if (!layer->time_mix_first) {
  834. wkv_output = ggml_gated_linear_attn(ctx, k, v, r, w, *wkv_state, pow(head_size, -0.5f));
  835. } else {
  836. wkv_output = ggml_rwkv_wkv6(ctx, k, v, r, layer->time_mix_first, w, *wkv_state);
  837. }
  838. cur = ggml_view_1d(ctx, wkv_output, n_embd * n_tokens, 0);
  839. *wkv_state = ggml_view_1d(ctx, wkv_output, n_embd * head_size * n_seqs, n_embd * n_tokens * sizeof(float));
  840. if (!is_qrwkv) {
  841. // group norm with head_count groups
  842. cur = ggml_reshape_3d(ctx, cur, n_embd / head_count, head_count, n_tokens);
  843. cur = ggml_norm(ctx, cur, 64e-5f);
  844. // Convert back to regular vectors.
  845. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  846. cur = ggml_add(ctx, ggml_mul(ctx, cur, layer->time_mix_ln), layer->time_mix_ln_b);
  847. } else {
  848. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  849. }
  850. cur = ggml_mul(ctx, cur, g);
  851. cur = llm_build_lora_mm(lctx, ctx, layer->time_mix_output, cur);
  852. return ggml_reshape_3d(ctx, cur, n_embd, n_seq_tokens, n_seqs);
  853. }
  854. static struct ggml_tensor * llm_build_rwkv6_channel_mix(
  855. struct llama_context & lctx,
  856. struct ggml_context * ctx,
  857. const struct llama_layer * layer,
  858. struct ggml_tensor * cur,
  859. struct ggml_tensor * x_prev) {
  860. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  861. struct ggml_tensor * xk = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_k), cur);
  862. struct ggml_tensor * xr = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_r), cur);
  863. struct ggml_tensor * r = ggml_sigmoid(ctx, llm_build_lora_mm(lctx, ctx, layer->channel_mix_receptance, xr));
  864. struct ggml_tensor * k = ggml_sqr(
  865. ctx,
  866. ggml_relu(
  867. ctx,
  868. llm_build_lora_mm(lctx, ctx, layer->channel_mix_key, xk)
  869. )
  870. );
  871. return ggml_mul(ctx, r, llm_build_lora_mm(lctx, ctx, layer->channel_mix_value, k));
  872. }
  873. struct llm_build_context {
  874. const llama_model & model;
  875. llama_context & lctx;
  876. const llama_hparams & hparams;
  877. const llama_cparams & cparams;
  878. const llama_ubatch & ubatch;
  879. const llama_kv_cache & kv_self;
  880. const int64_t n_embd;
  881. const int64_t n_layer;
  882. const int64_t n_rot;
  883. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  884. const int64_t n_head;
  885. const int64_t n_head_kv;
  886. const int64_t n_embd_head_k;
  887. const int64_t n_embd_k_gqa;
  888. const int64_t n_embd_head_v;
  889. const int64_t n_embd_v_gqa;
  890. const int64_t n_expert;
  891. const int64_t n_expert_used;
  892. const float freq_base;
  893. const float freq_scale;
  894. const float ext_factor;
  895. const float attn_factor;
  896. const float beta_fast;
  897. const float beta_slow;
  898. const float norm_eps;
  899. const float norm_rms_eps;
  900. const int32_t n_tokens;
  901. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  902. const int32_t n_outputs;
  903. const int32_t n_outputs_enc;
  904. const int32_t kv_head; // index of where we store new KV data in the cache
  905. const int32_t n_ctx_orig;
  906. const bool flash_attn;
  907. const enum llama_pooling_type pooling_type;
  908. const enum llama_rope_type rope_type;
  909. const llm_build_cb & cb;
  910. std::vector<uint8_t> & buf_compute_meta;
  911. struct ggml_context * ctx0 = nullptr;
  912. // TODO: consider making the entire interface noexcept
  913. llm_build_context(
  914. llama_context & lctx,
  915. const llama_ubatch & ubatch,
  916. const llm_build_cb & cb,
  917. bool worst_case) :
  918. model (lctx.model),
  919. lctx (lctx),
  920. hparams (model.hparams),
  921. cparams (lctx.cparams),
  922. ubatch (ubatch),
  923. kv_self (lctx.kv_self),
  924. n_embd (hparams.n_embd),
  925. n_layer (hparams.n_layer),
  926. n_rot (hparams.n_rot),
  927. n_ctx (cparams.n_ctx),
  928. n_head (hparams.n_head()),
  929. n_head_kv (hparams.n_head_kv()),
  930. n_embd_head_k (hparams.n_embd_head_k),
  931. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  932. n_embd_head_v (hparams.n_embd_head_v),
  933. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  934. n_expert (hparams.n_expert),
  935. n_expert_used (hparams.n_expert_used),
  936. freq_base (cparams.rope_freq_base),
  937. freq_scale (cparams.rope_freq_scale),
  938. ext_factor (cparams.yarn_ext_factor),
  939. attn_factor (cparams.yarn_attn_factor),
  940. beta_fast (cparams.yarn_beta_fast),
  941. beta_slow (cparams.yarn_beta_slow),
  942. norm_eps (hparams.f_norm_eps),
  943. norm_rms_eps (hparams.f_norm_rms_eps),
  944. n_tokens (ubatch.n_tokens),
  945. n_kv (worst_case ? kv_self.size : kv_self.n),
  946. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  947. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  948. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  949. n_ctx_orig (cparams.n_ctx_orig_yarn),
  950. flash_attn (cparams.flash_attn),
  951. pooling_type (cparams.pooling_type),
  952. rope_type (hparams.rope_type),
  953. cb (cb),
  954. buf_compute_meta (lctx.buf_compute_meta) {
  955. // all initializations should be done in init()
  956. }
  957. void init() {
  958. struct ggml_init_params params = {
  959. /*.mem_size =*/ buf_compute_meta.size(),
  960. /*.mem_buffer =*/ buf_compute_meta.data(),
  961. /*.no_alloc =*/ true,
  962. };
  963. ctx0 = ggml_init(params);
  964. lctx.inp_tokens = nullptr;
  965. lctx.inp_embd = nullptr;
  966. lctx.inp_pos = nullptr;
  967. lctx.inp_out_ids = nullptr;
  968. lctx.inp_KQ_mask = nullptr;
  969. lctx.inp_KQ_mask_swa = nullptr;
  970. lctx.inp_K_shift = nullptr;
  971. lctx.inp_mean = nullptr;
  972. lctx.inp_cls = nullptr;
  973. lctx.inp_s_copy = nullptr;
  974. lctx.inp_s_mask = nullptr;
  975. lctx.inp_s_seq = nullptr;
  976. lctx.inp_pos_bucket = nullptr;
  977. lctx.inp_embd_enc = nullptr;
  978. lctx.inp_KQ_mask_cross = nullptr;
  979. }
  980. void free() {
  981. ggml_free(ctx0);
  982. ctx0 = nullptr;
  983. }
  984. struct ggml_cgraph * build_k_shift() {
  985. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  986. GGML_ASSERT(kv_self.size == n_ctx);
  987. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  988. cb(lctx.inp_K_shift, "K_shift", -1);
  989. ggml_set_input(lctx.inp_K_shift);
  990. for (int il = 0; il < n_layer; ++il) {
  991. const int64_t n_head_kv = hparams.n_head_kv(il);
  992. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  993. struct ggml_tensor * rope_factors = build_rope_factors(il);
  994. struct ggml_tensor * k =
  995. ggml_view_3d(ctx0, kv_self.k_l[il],
  996. n_embd_head_k, n_head_kv, n_ctx,
  997. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  998. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  999. 0);
  1000. struct ggml_tensor * tmp;
  1001. if (ggml_is_quantized(k->type)) {
  1002. // dequantize to f32 -> RoPE -> quantize back
  1003. tmp = ggml_cast(ctx0, k, GGML_TYPE_F32);
  1004. cb(tmp, "K_f32", il);
  1005. for (auto & backend : lctx.backends) {
  1006. // Figure out which backend KV cache belongs to
  1007. if (ggml_backend_supports_buft(backend.get(), ggml_backend_buffer_get_type(kv_self.k_l[il]->buffer))) {
  1008. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), tmp, backend.get());
  1009. break;
  1010. }
  1011. }
  1012. tmp = ggml_rope_ext_inplace(ctx0, tmp,
  1013. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1014. ext_factor, attn_factor, beta_fast, beta_slow);
  1015. cb(tmp, "K_shifted_f32", il);
  1016. tmp = ggml_cpy(ctx0, tmp, k);
  1017. } else {
  1018. // we rotate only the first n_rot dimensions
  1019. tmp = ggml_rope_ext_inplace(ctx0, k,
  1020. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1021. ext_factor, attn_factor, beta_fast, beta_slow);
  1022. }
  1023. cb(tmp, "K_shifted", il);
  1024. ggml_build_forward_expand(gf, tmp);
  1025. }
  1026. return gf;
  1027. }
  1028. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  1029. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1030. for (uint32_t i = 0; i < ids.size(); ++i) {
  1031. const uint32_t id = ids[i];
  1032. if (i == id || id == ids.size()) {
  1033. continue;
  1034. }
  1035. uint32_t nm = 1;
  1036. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  1037. nm++;
  1038. }
  1039. for (int il = 0; il < n_layer; ++il) {
  1040. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  1041. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  1042. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  1043. n_embd_k_gqa, nm,
  1044. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  1045. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  1046. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  1047. n_embd_k_gqa, nm,
  1048. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  1049. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  1050. ggml_tensor * view_v_src;
  1051. ggml_tensor * view_v_dst;
  1052. if (flash_attn) {
  1053. // NOTE: the V cache is not transposed when using flash attention
  1054. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  1055. n_embd_v_gqa, nm,
  1056. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  1057. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  1058. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  1059. n_embd_v_gqa, nm,
  1060. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  1061. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  1062. } else {
  1063. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  1064. nm, n_embd_v_gqa,
  1065. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  1066. ggml_row_size(kv_self.v_l[il]->type, i));
  1067. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  1068. nm, n_embd_v_gqa,
  1069. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  1070. ggml_row_size(kv_self.v_l[il]->type, id));
  1071. }
  1072. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  1073. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  1074. }
  1075. i += nm - 1;
  1076. }
  1077. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  1078. return gf;
  1079. }
  1080. struct ggml_tensor * build_inp_pos() {
  1081. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  1082. cb(lctx.inp_pos, "inp_pos", -1);
  1083. ggml_set_input(lctx.inp_pos);
  1084. return lctx.inp_pos;
  1085. }
  1086. struct ggml_tensor * build_rope_factors(int il) {
  1087. // choose long/short freq factors based on the context size
  1088. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  1089. if (model.layers[il].rope_freqs != nullptr) {
  1090. return model.layers[il].rope_freqs;
  1091. }
  1092. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  1093. return model.layers[il].rope_long;
  1094. }
  1095. return model.layers[il].rope_short;
  1096. }
  1097. struct ggml_tensor * build_inp_out_ids() {
  1098. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  1099. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  1100. ggml_set_input(lctx.inp_out_ids);
  1101. return lctx.inp_out_ids;
  1102. }
  1103. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  1104. lctx.inp_KQ_mask = causal
  1105. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  1106. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  1107. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  1108. ggml_set_input(lctx.inp_KQ_mask);
  1109. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  1110. }
  1111. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  1112. GGML_ASSERT(hparams.n_swa > 0);
  1113. lctx.inp_KQ_mask_swa = causal
  1114. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  1115. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  1116. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  1117. ggml_set_input(lctx.inp_KQ_mask_swa);
  1118. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  1119. }
  1120. struct ggml_tensor * build_inp_mean() {
  1121. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  1122. cb(lctx.inp_mean, "inp_mean", -1);
  1123. ggml_set_input(lctx.inp_mean);
  1124. return lctx.inp_mean;
  1125. }
  1126. struct ggml_tensor * build_inp_cls() {
  1127. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  1128. cb(lctx.inp_cls, "inp_cls", -1);
  1129. ggml_set_input(lctx.inp_cls);
  1130. return lctx.inp_cls;
  1131. }
  1132. struct ggml_tensor * build_inp_s_copy() {
  1133. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  1134. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  1135. ggml_set_input(lctx.inp_s_copy);
  1136. return lctx.inp_s_copy;
  1137. }
  1138. struct ggml_tensor * build_inp_s_mask() {
  1139. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  1140. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  1141. ggml_set_input(lctx.inp_s_mask);
  1142. return lctx.inp_s_mask;
  1143. }
  1144. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  1145. // find result_norm tensor for input
  1146. struct ggml_tensor * inp = nullptr;
  1147. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  1148. inp = ggml_graph_node(gf, i);
  1149. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  1150. break;
  1151. } else {
  1152. inp = nullptr;
  1153. }
  1154. }
  1155. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  1156. struct ggml_tensor * cur;
  1157. switch (pooling_type) {
  1158. case LLAMA_POOLING_TYPE_NONE:
  1159. {
  1160. cur = inp;
  1161. } break;
  1162. case LLAMA_POOLING_TYPE_MEAN:
  1163. {
  1164. struct ggml_tensor * inp_mean = build_inp_mean();
  1165. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  1166. } break;
  1167. case LLAMA_POOLING_TYPE_CLS:
  1168. case LLAMA_POOLING_TYPE_LAST:
  1169. {
  1170. struct ggml_tensor * inp_cls = build_inp_cls();
  1171. cur = ggml_get_rows(ctx0, inp, inp_cls);
  1172. } break;
  1173. case LLAMA_POOLING_TYPE_RANK:
  1174. {
  1175. struct ggml_tensor * inp_cls = build_inp_cls();
  1176. inp = ggml_get_rows(ctx0, inp, inp_cls);
  1177. // classification head
  1178. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  1179. GGML_ASSERT(model.cls != nullptr);
  1180. GGML_ASSERT(model.cls_b != nullptr);
  1181. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls, inp), model.cls_b);
  1182. cur = ggml_tanh(ctx0, cur);
  1183. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  1184. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  1185. if (model.cls_out) {
  1186. GGML_ASSERT(model.cls_out_b != nullptr);
  1187. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls_out, cur), model.cls_out_b);
  1188. }
  1189. } break;
  1190. default:
  1191. {
  1192. GGML_ABORT("unknown pooling type");
  1193. }
  1194. }
  1195. cb(cur, "result_embd_pooled", -1);
  1196. ggml_build_forward_expand(gf, cur);
  1197. return gf;
  1198. }
  1199. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  1200. if (causal) {
  1201. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  1202. } else {
  1203. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  1204. }
  1205. ggml_set_input(lctx.inp_pos_bucket);
  1206. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  1207. return lctx.inp_pos_bucket;
  1208. }
  1209. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  1210. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  1211. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  1212. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  1213. cb(pos_bias, "pos_bias", -1);
  1214. pos_bias = ggml_view_3d(ctx0, pos_bias, pos_bias->ne[0], lctx.inp_pos_bucket->ne[0], lctx.inp_pos_bucket->ne[1], ggml_element_size(pos_bias) * pos_bias->ne[0], ggml_element_size(pos_bias) * pos_bias->ne[0] * lctx.inp_pos_bucket->ne[0], 0);
  1215. cb(pos_bias, "pos_bias", -1);
  1216. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  1217. cb(pos_bias, "pos_bias", -1);
  1218. pos_bias = ggml_cont(ctx0, pos_bias);
  1219. cb(pos_bias, "pos_bias", -1);
  1220. return pos_bias;
  1221. }
  1222. struct ggml_tensor * llm_build_inp_embd_enc() {
  1223. const int64_t n_embd = hparams.n_embd;
  1224. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  1225. ggml_set_input(lctx.inp_embd_enc);
  1226. cb(lctx.inp_embd_enc, "embd_enc", -1);
  1227. return lctx.inp_embd_enc;
  1228. }
  1229. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  1230. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  1231. ggml_set_input(lctx.inp_KQ_mask_cross);
  1232. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  1233. return lctx.inp_KQ_mask_cross;
  1234. }
  1235. struct ggml_cgraph * build_llama() {
  1236. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1237. // mutable variable, needed during the last layer of the computation to skip unused tokens
  1238. int32_t n_tokens = this->n_tokens;
  1239. const int64_t n_embd_head = hparams.n_embd_head_v;
  1240. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1241. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1242. struct ggml_tensor * cur;
  1243. struct ggml_tensor * inpL;
  1244. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1245. // inp_pos - contains the positions
  1246. struct ggml_tensor * inp_pos = build_inp_pos();
  1247. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1248. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1249. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  1250. for (int il = 0; il < n_layer; ++il) {
  1251. struct ggml_tensor * inpSA = inpL;
  1252. // norm
  1253. cur = llm_build_norm(ctx0, inpL, hparams,
  1254. model.layers[il].attn_norm, NULL,
  1255. LLM_NORM_RMS, cb, il);
  1256. cb(cur, "attn_norm", il);
  1257. // self-attention
  1258. {
  1259. // rope freq factors for llama3; may return nullptr for llama2 and other models
  1260. struct ggml_tensor * rope_factors = build_rope_factors(il);
  1261. // compute Q and K and RoPE them
  1262. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  1263. cb(Qcur, "Qcur", il);
  1264. if (model.layers[il].bq) {
  1265. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  1266. cb(Qcur, "Qcur", il);
  1267. }
  1268. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  1269. cb(Kcur, "Kcur", il);
  1270. if (model.layers[il].bk) {
  1271. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  1272. cb(Kcur, "Kcur", il);
  1273. }
  1274. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  1275. cb(Vcur, "Vcur", il);
  1276. if (model.layers[il].bv) {
  1277. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  1278. cb(Vcur, "Vcur", il);
  1279. }
  1280. Qcur = ggml_rope_ext(
  1281. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  1282. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1283. ext_factor, attn_factor, beta_fast, beta_slow
  1284. );
  1285. cb(Qcur, "Qcur", il);
  1286. Kcur = ggml_rope_ext(
  1287. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  1288. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1289. ext_factor, attn_factor, beta_fast, beta_slow
  1290. );
  1291. cb(Kcur, "Kcur", il);
  1292. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  1293. model.layers[il].wo, model.layers[il].bo,
  1294. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  1295. }
  1296. if (il == n_layer - 1) {
  1297. // skip computing output for unused tokens
  1298. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  1299. n_tokens = n_outputs;
  1300. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  1301. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  1302. }
  1303. // For Granite architecture
  1304. if (hparams.f_residual_scale) {
  1305. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  1306. }
  1307. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  1308. cb(ffn_inp, "ffn_inp", il);
  1309. // feed-forward network
  1310. if (model.layers[il].ffn_gate_inp == nullptr) {
  1311. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  1312. model.layers[il].ffn_norm, NULL,
  1313. LLM_NORM_RMS, cb, il);
  1314. cb(cur, "ffn_norm", il);
  1315. cur = llm_build_ffn(ctx0, lctx, cur,
  1316. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  1317. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  1318. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  1319. NULL,
  1320. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  1321. cb(cur, "ffn_out", il);
  1322. } else {
  1323. // MoE branch
  1324. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  1325. model.layers[il].ffn_norm, NULL,
  1326. LLM_NORM_RMS, cb, il);
  1327. cb(cur, "ffn_norm", il);
  1328. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  1329. model.layers[il].ffn_gate_inp,
  1330. model.layers[il].ffn_up_exps,
  1331. model.layers[il].ffn_gate_exps,
  1332. model.layers[il].ffn_down_exps,
  1333. nullptr,
  1334. n_expert, n_expert_used,
  1335. LLM_FFN_SILU, true,
  1336. false, 0.0,
  1337. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  1338. cb, il);
  1339. cb(cur, "ffn_moe_out", il);
  1340. }
  1341. // For Granite architecture
  1342. if (hparams.f_residual_scale) {
  1343. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  1344. }
  1345. cur = ggml_add(ctx0, cur, ffn_inp);
  1346. cb(cur, "ffn_out", il);
  1347. cur = lctx.cvec.apply_to(ctx0, cur, il);
  1348. cb(cur, "l_out", il);
  1349. // input for next layer
  1350. inpL = cur;
  1351. }
  1352. cur = inpL;
  1353. cur = llm_build_norm(ctx0, cur, hparams,
  1354. model.output_norm, NULL,
  1355. LLM_NORM_RMS, cb, -1);
  1356. cb(cur, "result_norm", -1);
  1357. // lm_head
  1358. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  1359. // For Granite architecture
  1360. if (hparams.f_logit_scale) {
  1361. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  1362. }
  1363. cb(cur, "result_output", -1);
  1364. ggml_build_forward_expand(gf, cur);
  1365. return gf;
  1366. }
  1367. struct ggml_cgraph * build_deci() {
  1368. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1369. // mutable variable, needed during the last layer of the computation to skip unused tokens
  1370. int32_t n_tokens = this->n_tokens;
  1371. const int64_t n_embd_head = hparams.n_embd_head_v;
  1372. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1373. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1374. struct ggml_tensor * cur;
  1375. struct ggml_tensor * inpL;
  1376. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1377. // inp_pos - contains the positions
  1378. struct ggml_tensor * inp_pos = build_inp_pos();
  1379. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1380. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1381. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  1382. for (int il = 0; il < n_layer; ++il) {
  1383. struct ggml_tensor * inpSA = inpL;
  1384. const int64_t n_head_kv = hparams.n_head_kv(il);
  1385. const int64_t n_head = hparams.n_head(il);
  1386. if (n_head == 0) {
  1387. // attention-free layer of Llama-3_1-Nemotron-51B
  1388. cur = inpL;
  1389. } else {
  1390. // norm
  1391. cur = llm_build_norm(ctx0, inpL, hparams,
  1392. model.layers[il].attn_norm, NULL,
  1393. LLM_NORM_RMS, cb, il);
  1394. cb(cur, "attn_norm", il);
  1395. }
  1396. if (n_head > 0 && n_head_kv == 0) {
  1397. // "linear attention" of Llama-3_1-Nemotron-51B
  1398. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  1399. cb(cur, "wo", il);
  1400. } else if (n_head > 0) {
  1401. // self-attention
  1402. // rope freq factors for llama3; may return nullptr for llama2 and other models
  1403. struct ggml_tensor * rope_factors = build_rope_factors(il);
  1404. // compute Q and K and RoPE them
  1405. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  1406. cb(Qcur, "Qcur", il);
  1407. if (model.layers[il].bq) {
  1408. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  1409. cb(Qcur, "Qcur", il);
  1410. }
  1411. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  1412. cb(Kcur, "Kcur", il);
  1413. if (model.layers[il].bk) {
  1414. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  1415. cb(Kcur, "Kcur", il);
  1416. }
  1417. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  1418. cb(Vcur, "Vcur", il);
  1419. if (model.layers[il].bv) {
  1420. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  1421. cb(Vcur, "Vcur", il);
  1422. }
  1423. Qcur = ggml_rope_ext(
  1424. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  1425. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1426. ext_factor, attn_factor, beta_fast, beta_slow
  1427. );
  1428. cb(Qcur, "Qcur", il);
  1429. Kcur = ggml_rope_ext(
  1430. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  1431. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1432. ext_factor, attn_factor, beta_fast, beta_slow
  1433. );
  1434. cb(Kcur, "Kcur", il);
  1435. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  1436. model.layers[il].wo, model.layers[il].bo,
  1437. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  1438. }
  1439. if (il == n_layer - 1) {
  1440. // skip computing output for unused tokens
  1441. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  1442. n_tokens = n_outputs;
  1443. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  1444. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  1445. }
  1446. // For Granite architecture
  1447. if (hparams.f_residual_scale) {
  1448. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  1449. }
  1450. // modified to support attention-free layer of Llama-3_1-Nemotron-51B
  1451. struct ggml_tensor * ffn_inp = cur;
  1452. if (n_head > 0) {
  1453. ffn_inp = ggml_add(ctx0, cur, inpSA);
  1454. cb(ffn_inp, "ffn_inp", il);
  1455. }
  1456. // feed-forward network
  1457. if (model.layers[il].ffn_gate_inp == nullptr) {
  1458. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  1459. model.layers[il].ffn_norm, NULL,
  1460. LLM_NORM_RMS, cb, il);
  1461. cb(cur, "ffn_norm", il);
  1462. cur = llm_build_ffn(ctx0, lctx, cur,
  1463. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  1464. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  1465. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  1466. NULL,
  1467. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  1468. cb(cur, "ffn_out", il);
  1469. }
  1470. // For Granite architecture
  1471. if (hparams.f_residual_scale) {
  1472. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  1473. }
  1474. cur = ggml_add(ctx0, cur, ffn_inp);
  1475. cb(cur, "ffn_out", il);
  1476. cur = lctx.cvec.apply_to(ctx0, cur, il);
  1477. cb(cur, "l_out", il);
  1478. // input for next layer
  1479. inpL = cur;
  1480. }
  1481. cur = inpL;
  1482. cur = llm_build_norm(ctx0, cur, hparams,
  1483. model.output_norm, NULL,
  1484. LLM_NORM_RMS, cb, -1);
  1485. cb(cur, "result_norm", -1);
  1486. // lm_head
  1487. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  1488. // For Granite architecture
  1489. if (hparams.f_logit_scale) {
  1490. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  1491. }
  1492. cb(cur, "result_output", -1);
  1493. ggml_build_forward_expand(gf, cur);
  1494. return gf;
  1495. }
  1496. struct ggml_cgraph * build_baichuan() {
  1497. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1498. const int64_t n_embd_head = hparams.n_embd_head_v;
  1499. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1500. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1501. struct ggml_tensor * cur;
  1502. struct ggml_tensor * inpL;
  1503. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1504. // inp_pos - contains the positions
  1505. struct ggml_tensor * inp_pos = model.type == LLM_TYPE_7B ? build_inp_pos() : nullptr;
  1506. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1507. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1508. for (int il = 0; il < n_layer; ++il) {
  1509. struct ggml_tensor * inpSA = inpL;
  1510. cur = llm_build_norm(ctx0, inpL, hparams,
  1511. model.layers[il].attn_norm, NULL,
  1512. LLM_NORM_RMS, cb, il);
  1513. cb(cur, "attn_norm", il);
  1514. // self-attention
  1515. {
  1516. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  1517. cb(Qcur, "Qcur", il);
  1518. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  1519. cb(Kcur, "Kcur", il);
  1520. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  1521. cb(Vcur, "Vcur", il);
  1522. switch (model.type) {
  1523. case LLM_TYPE_7B:
  1524. Qcur = ggml_rope_ext(
  1525. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  1526. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1527. ext_factor, attn_factor, beta_fast, beta_slow
  1528. );
  1529. Kcur = ggml_rope_ext(
  1530. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  1531. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1532. ext_factor, attn_factor, beta_fast, beta_slow
  1533. );
  1534. break;
  1535. case LLM_TYPE_13B:
  1536. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  1537. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  1538. break;
  1539. default:
  1540. GGML_ABORT("fatal error");
  1541. }
  1542. cb(Qcur, "Qcur", il);
  1543. cb(Kcur, "Kcur", il);
  1544. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  1545. model.layers[il].wo, NULL,
  1546. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  1547. }
  1548. if (il == n_layer - 1) {
  1549. // skip computing output for unused tokens
  1550. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  1551. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  1552. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  1553. }
  1554. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  1555. cb(ffn_inp, "ffn_inp", il);
  1556. // feed-forward network
  1557. {
  1558. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  1559. model.layers[il].ffn_norm, NULL,
  1560. LLM_NORM_RMS, cb, il);
  1561. cb(cur, "ffn_norm", il);
  1562. cur = llm_build_ffn(ctx0, lctx, cur,
  1563. model.layers[il].ffn_up, NULL, NULL,
  1564. model.layers[il].ffn_gate, NULL, NULL,
  1565. model.layers[il].ffn_down, NULL, NULL,
  1566. NULL,
  1567. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  1568. cb(cur, "ffn_out", il);
  1569. }
  1570. cur = ggml_add(ctx0, cur, ffn_inp);
  1571. cur = lctx.cvec.apply_to(ctx0, cur, il);
  1572. cb(cur, "l_out", il);
  1573. // input for next layer
  1574. inpL = cur;
  1575. }
  1576. cur = inpL;
  1577. cur = llm_build_norm(ctx0, cur, hparams,
  1578. model.output_norm, NULL,
  1579. LLM_NORM_RMS, cb, -1);
  1580. cb(cur, "result_norm", -1);
  1581. // lm_head
  1582. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  1583. cb(cur, "result_output", -1);
  1584. ggml_build_forward_expand(gf, cur);
  1585. return gf;
  1586. }
  1587. struct ggml_cgraph * build_xverse() {
  1588. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1589. const int64_t n_embd_head = hparams.n_embd_head_v;
  1590. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1591. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1592. struct ggml_tensor * cur;
  1593. struct ggml_tensor * inpL;
  1594. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1595. // inp_pos - contains the positions
  1596. struct ggml_tensor * inp_pos = build_inp_pos();
  1597. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1598. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1599. for (int il = 0; il < n_layer; ++il) {
  1600. struct ggml_tensor * inpSA = inpL;
  1601. cur = llm_build_norm(ctx0, inpL, hparams,
  1602. model.layers[il].attn_norm, NULL,
  1603. LLM_NORM_RMS, cb, il);
  1604. cb(cur, "attn_norm", il);
  1605. // self-attention
  1606. {
  1607. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  1608. cb(Qcur, "Qcur", il);
  1609. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  1610. cb(Kcur, "Kcur", il);
  1611. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  1612. cb(Vcur, "Vcur", il);
  1613. Qcur = ggml_rope_ext(
  1614. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  1615. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1616. ext_factor, attn_factor, beta_fast, beta_slow
  1617. );
  1618. cb(Qcur, "Qcur", il);
  1619. Kcur = ggml_rope_ext(
  1620. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  1621. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1622. ext_factor, attn_factor, beta_fast, beta_slow
  1623. );
  1624. cb(Kcur, "Kcur", il);
  1625. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  1626. model.layers[il].wo, NULL,
  1627. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  1628. }
  1629. if (il == n_layer - 1) {
  1630. // skip computing output for unused tokens
  1631. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  1632. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  1633. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  1634. }
  1635. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  1636. cb(ffn_inp, "ffn_inp", il);
  1637. // feed-forward network
  1638. {
  1639. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  1640. model.layers[il].ffn_norm, NULL,
  1641. LLM_NORM_RMS, cb, il);
  1642. cb(cur, "ffn_norm", il);
  1643. cur = llm_build_ffn(ctx0, lctx, cur,
  1644. model.layers[il].ffn_up, NULL, NULL,
  1645. model.layers[il].ffn_gate, NULL, NULL,
  1646. model.layers[il].ffn_down, NULL, NULL,
  1647. NULL,
  1648. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  1649. cb(cur, "ffn_out", il);
  1650. }
  1651. cur = ggml_add(ctx0, cur, ffn_inp);
  1652. cur = lctx.cvec.apply_to(ctx0, cur, il);
  1653. cb(cur, "l_out", il);
  1654. // input for next layer
  1655. inpL = cur;
  1656. }
  1657. cur = inpL;
  1658. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  1659. cb(cur, "result_norm", -1);
  1660. // lm_head
  1661. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  1662. cb(cur, "result_output", -1);
  1663. ggml_build_forward_expand(gf, cur);
  1664. return gf;
  1665. }
  1666. struct ggml_cgraph * build_falcon() {
  1667. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1668. const int64_t n_embd_head = hparams.n_embd_head_v;
  1669. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  1670. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1671. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1672. struct ggml_tensor * cur;
  1673. struct ggml_tensor * inpL;
  1674. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1675. // inp_pos - contains the positions
  1676. struct ggml_tensor * inp_pos = build_inp_pos();
  1677. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1678. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1679. for (int il = 0; il < n_layer; ++il) {
  1680. struct ggml_tensor * attn_norm;
  1681. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  1682. model.layers[il].attn_norm,
  1683. model.layers[il].attn_norm_b,
  1684. LLM_NORM, cb, il);
  1685. cb(attn_norm, "attn_norm", il);
  1686. // self-attention
  1687. {
  1688. if (model.layers[il].attn_norm_2) {
  1689. // Falcon-40B
  1690. cur = llm_build_norm(ctx0, inpL, hparams,
  1691. model.layers[il].attn_norm_2,
  1692. model.layers[il].attn_norm_2_b,
  1693. LLM_NORM, cb, il);
  1694. cb(cur, "attn_norm_2", il);
  1695. } else {
  1696. cur = attn_norm;
  1697. }
  1698. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  1699. cb(cur, "wqkv", il);
  1700. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  1701. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  1702. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  1703. cb(Qcur, "Qcur", il);
  1704. cb(Kcur, "Kcur", il);
  1705. cb(Vcur, "Vcur", il);
  1706. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  1707. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  1708. // using mode = 2 for neox mode
  1709. Qcur = ggml_rope_ext(
  1710. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  1711. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  1712. );
  1713. cb(Qcur, "Qcur", il);
  1714. Kcur = ggml_rope_ext(
  1715. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  1716. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  1717. );
  1718. cb(Kcur, "Kcur", il);
  1719. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  1720. model.layers[il].wo, NULL,
  1721. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  1722. }
  1723. if (il == n_layer - 1) {
  1724. // skip computing output for unused tokens
  1725. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  1726. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  1727. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  1728. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  1729. }
  1730. struct ggml_tensor * ffn_inp = cur;
  1731. // feed forward
  1732. {
  1733. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  1734. model.layers[il].ffn_up, NULL, NULL,
  1735. NULL, NULL, NULL,
  1736. model.layers[il].ffn_down, NULL, NULL,
  1737. NULL,
  1738. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  1739. cb(cur, "ffn_out", il);
  1740. }
  1741. cur = ggml_add(ctx0, cur, ffn_inp);
  1742. cur = ggml_add(ctx0, cur, inpL);
  1743. cur = lctx.cvec.apply_to(ctx0, cur, il);
  1744. cb(cur, "l_out", il);
  1745. // input for next layer
  1746. inpL = cur;
  1747. }
  1748. cur = inpL;
  1749. // norm
  1750. cur = llm_build_norm(ctx0, cur, hparams,
  1751. model.output_norm,
  1752. model.output_norm_b,
  1753. LLM_NORM, cb, -1);
  1754. cb(cur, "result_norm", -1);
  1755. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  1756. cb(cur, "result_output", -1);
  1757. ggml_build_forward_expand(gf, cur);
  1758. return gf;
  1759. }
  1760. struct ggml_cgraph * build_grok() {
  1761. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1762. // mutable variable, needed during the last layer of the computation to skip unused tokens
  1763. int32_t n_tokens = this->n_tokens;
  1764. const int64_t n_embd_head = hparams.n_embd_head_v;
  1765. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1766. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1767. struct ggml_tensor * cur;
  1768. struct ggml_tensor * inpL;
  1769. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1770. // multiply by embedding_multiplier_scale of 78.38367176906169
  1771. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  1772. // inp_pos - contains the positions
  1773. struct ggml_tensor * inp_pos = build_inp_pos();
  1774. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1775. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1776. for (int il = 0; il < n_layer; ++il) {
  1777. struct ggml_tensor * inpSA = inpL;
  1778. // norm
  1779. cur = llm_build_norm(ctx0, inpL, hparams,
  1780. model.layers[il].attn_norm, NULL,
  1781. LLM_NORM_RMS, cb, il);
  1782. cb(cur, "attn_norm", il);
  1783. // self-attention
  1784. {
  1785. // compute Q and K and RoPE them
  1786. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  1787. cb(Qcur, "Qcur", il);
  1788. if (model.layers[il].bq) {
  1789. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  1790. cb(Qcur, "Qcur", il);
  1791. }
  1792. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  1793. cb(Kcur, "Kcur", il);
  1794. if (model.layers[il].bk) {
  1795. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  1796. cb(Kcur, "Kcur", il);
  1797. }
  1798. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  1799. cb(Vcur, "Vcur", il);
  1800. if (model.layers[il].bv) {
  1801. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  1802. cb(Vcur, "Vcur", il);
  1803. }
  1804. Qcur = ggml_rope_ext(
  1805. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  1806. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1807. ext_factor, attn_factor, beta_fast, beta_slow
  1808. );
  1809. cb(Qcur, "Qcur", il);
  1810. Kcur = ggml_rope_ext(
  1811. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  1812. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1813. ext_factor, attn_factor, beta_fast, beta_slow
  1814. );
  1815. cb(Kcur, "Kcur", il);
  1816. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  1817. model.layers[il].wo, model.layers[il].bo,
  1818. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  1819. }
  1820. if (il == n_layer - 1) {
  1821. // skip computing output for unused tokens
  1822. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  1823. n_tokens = n_outputs;
  1824. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  1825. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  1826. }
  1827. // Grok
  1828. // if attn_out_norm is present then apply it before adding the input
  1829. if (model.layers[il].attn_out_norm) {
  1830. cur = llm_build_norm(ctx0, cur, hparams,
  1831. model.layers[il].attn_out_norm, NULL,
  1832. LLM_NORM_RMS, cb, il);
  1833. cb(cur, "attn_out_norm", il);
  1834. }
  1835. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  1836. cb(ffn_inp, "ffn_inp", il);
  1837. // feed-forward network
  1838. // MoE branch
  1839. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  1840. model.layers[il].ffn_norm, NULL,
  1841. LLM_NORM_RMS, cb, il);
  1842. cb(cur, "ffn_norm", il);
  1843. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  1844. model.layers[il].ffn_gate_inp,
  1845. model.layers[il].ffn_up_exps,
  1846. model.layers[il].ffn_gate_exps,
  1847. model.layers[il].ffn_down_exps,
  1848. nullptr,
  1849. n_expert, n_expert_used,
  1850. LLM_FFN_GELU, true,
  1851. false, 0.0,
  1852. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  1853. cb, il);
  1854. cb(cur, "ffn_moe_out", il);
  1855. // Grok
  1856. // if layer_out_norm is present then apply it before adding the input
  1857. // Idea: maybe ffn_out_norm is a better name
  1858. if (model.layers[il].layer_out_norm) {
  1859. cur = llm_build_norm(ctx0, cur, hparams,
  1860. model.layers[il].layer_out_norm, NULL,
  1861. LLM_NORM_RMS, cb, il);
  1862. cb(cur, "layer_out_norm", il);
  1863. }
  1864. cur = ggml_add(ctx0, cur, ffn_inp);
  1865. cb(cur, "ffn_out", il);
  1866. cur = lctx.cvec.apply_to(ctx0, cur, il);
  1867. cb(cur, "l_out", il);
  1868. // input for next layer
  1869. inpL = cur;
  1870. }
  1871. cur = inpL;
  1872. cur = llm_build_norm(ctx0, cur, hparams,
  1873. model.output_norm, NULL,
  1874. LLM_NORM_RMS, cb, -1);
  1875. cb(cur, "result_norm", -1);
  1876. // lm_head
  1877. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  1878. // Grok
  1879. // multiply logits by output_multiplier_scale of 0.5773502691896257
  1880. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  1881. cb(cur, "result_output", -1);
  1882. ggml_build_forward_expand(gf, cur);
  1883. return gf;
  1884. }
  1885. struct ggml_cgraph * build_dbrx() {
  1886. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1887. // mutable variable, needed during the last layer of the computation to skip unused tokens
  1888. int32_t n_tokens = this->n_tokens;
  1889. const int64_t n_embd_head = hparams.n_embd_head_v;
  1890. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  1891. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1892. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1893. struct ggml_tensor * cur;
  1894. struct ggml_tensor * inpL;
  1895. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1896. // inp_pos - contains the positions
  1897. struct ggml_tensor * inp_pos = build_inp_pos();
  1898. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1899. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1900. for (int il = 0; il < n_layer; ++il) {
  1901. struct ggml_tensor * inpSA = inpL;
  1902. // norm
  1903. cur = llm_build_norm(ctx0, inpL, hparams,
  1904. model.layers[il].attn_norm, NULL,
  1905. LLM_NORM, cb, il);
  1906. cb(cur, "attn_norm", il);
  1907. // self-attention
  1908. {
  1909. struct ggml_tensor * Qcur = nullptr;
  1910. struct ggml_tensor * Kcur = nullptr;
  1911. struct ggml_tensor * Vcur = nullptr;
  1912. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  1913. cb(cur, "wqkv", il);
  1914. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  1915. cb(cur, "wqkv_clamped", il);
  1916. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  1917. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  1918. Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  1919. cb(Qcur, "Qcur", il);
  1920. cb(Kcur, "Kcur", il);
  1921. cb(Vcur, "Vcur", il);
  1922. Qcur = ggml_rope_ext(
  1923. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  1924. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1925. ext_factor, attn_factor, beta_fast, beta_slow
  1926. );
  1927. cb(Qcur, "Qcur", il);
  1928. Kcur = ggml_rope_ext(
  1929. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  1930. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  1931. ext_factor, attn_factor, beta_fast, beta_slow
  1932. );
  1933. cb(Kcur, "Kcur", il);
  1934. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  1935. model.layers[il].wo, NULL,
  1936. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  1937. }
  1938. if (il == n_layer - 1) {
  1939. // skip computing output for unused tokens
  1940. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  1941. n_tokens = n_outputs;
  1942. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  1943. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  1944. }
  1945. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  1946. cb(ffn_inp, "ffn_inp", il);
  1947. // feed-forward network
  1948. // MoE branch
  1949. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  1950. model.layers[il].attn_out_norm, NULL,
  1951. LLM_NORM, cb, il);
  1952. cb(cur, "attn_out_norm", il);
  1953. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  1954. model.layers[il].ffn_gate_inp,
  1955. model.layers[il].ffn_up_exps,
  1956. model.layers[il].ffn_gate_exps,
  1957. model.layers[il].ffn_down_exps,
  1958. nullptr,
  1959. n_expert, n_expert_used,
  1960. LLM_FFN_SILU, true,
  1961. false, 0.0,
  1962. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  1963. cb, il);
  1964. cb(cur, "ffn_moe_out", il);
  1965. cur = ggml_add(ctx0, cur, ffn_inp);
  1966. cb(cur, "ffn_out", il);
  1967. cur = lctx.cvec.apply_to(ctx0, cur, il);
  1968. cb(cur, "l_out", il);
  1969. // input for next layer
  1970. inpL = cur;
  1971. }
  1972. cur = inpL;
  1973. cur = llm_build_norm(ctx0, cur, hparams,
  1974. model.output_norm, NULL,
  1975. LLM_NORM, cb, -1);
  1976. cb(cur, "result_norm", -1);
  1977. // lm_head
  1978. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  1979. cb(cur, "result_output", -1);
  1980. ggml_build_forward_expand(gf, cur);
  1981. return gf;
  1982. }
  1983. struct ggml_cgraph * build_starcoder() {
  1984. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  1985. const int64_t n_embd_head = hparams.n_embd_head_v;
  1986. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  1987. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  1988. struct ggml_tensor * cur;
  1989. struct ggml_tensor * inpL;
  1990. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  1991. // inp_pos - contains the positions
  1992. struct ggml_tensor * inp_pos = build_inp_pos();
  1993. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  1994. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  1995. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  1996. cb(pos, "pos_embd", -1);
  1997. inpL = ggml_add(ctx0, inpL, pos);
  1998. cb(inpL, "inpL", -1);
  1999. for (int il = 0; il < n_layer; ++il) {
  2000. cur = llm_build_norm(ctx0, inpL, hparams,
  2001. model.layers[il].attn_norm,
  2002. model.layers[il].attn_norm_b,
  2003. LLM_NORM, cb, il);
  2004. cb(cur, "attn_norm", il);
  2005. // self-attention
  2006. {
  2007. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  2008. cb(cur, "wqkv", il);
  2009. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  2010. cb(cur, "bqkv", il);
  2011. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  2012. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  2013. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  2014. cb(Qcur, "Qcur", il);
  2015. cb(Kcur, "Kcur", il);
  2016. cb(Vcur, "Vcur", il);
  2017. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2018. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2019. model.layers[il].wo, model.layers[il].bo,
  2020. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2021. }
  2022. if (il == n_layer - 1) {
  2023. // skip computing output for unused tokens
  2024. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2025. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2026. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  2027. }
  2028. // add the input
  2029. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  2030. cb(ffn_inp, "ffn_inp", il);
  2031. // FF
  2032. {
  2033. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2034. model.layers[il].ffn_norm,
  2035. model.layers[il].ffn_norm_b,
  2036. LLM_NORM, cb, il);
  2037. cb(cur, "ffn_norm", il);
  2038. cur = llm_build_ffn(ctx0, lctx, cur,
  2039. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  2040. NULL, NULL, NULL,
  2041. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  2042. NULL,
  2043. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  2044. cb(cur, "ffn_out", il);
  2045. }
  2046. cur = ggml_add(ctx0, cur, ffn_inp);
  2047. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2048. cb(cur, "l_out", il);
  2049. // input for next layer
  2050. inpL = cur;
  2051. }
  2052. cur = llm_build_norm(ctx0, inpL, hparams,
  2053. model.output_norm,
  2054. model.output_norm_b,
  2055. LLM_NORM, cb, -1);
  2056. cb(cur, "result_norm", -1);
  2057. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2058. cb(cur, "result_output", -1);
  2059. ggml_build_forward_expand(gf, cur);
  2060. return gf;
  2061. }
  2062. struct ggml_cgraph * build_refact() {
  2063. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2064. const int64_t n_embd_head = hparams.n_embd_head_v;
  2065. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2066. struct ggml_tensor * cur;
  2067. struct ggml_tensor * inpL;
  2068. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2069. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2070. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2071. for (int il = 0; il < n_layer; ++il) {
  2072. struct ggml_tensor * inpSA = inpL;
  2073. cur = llm_build_norm(ctx0, inpL, hparams,
  2074. model.layers[il].attn_norm, NULL,
  2075. LLM_NORM_RMS, cb, il);
  2076. cb(cur, "attn_norm", il);
  2077. // self-attention
  2078. {
  2079. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  2080. cb(Qcur, "Qcur", il);
  2081. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  2082. cb(Kcur, "Kcur", il);
  2083. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  2084. cb(Vcur, "Vcur", il);
  2085. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  2086. cb(Kcur, "Kcur", il);
  2087. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2088. cb(Qcur, "Qcur", il);
  2089. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2090. model.layers[il].wo, NULL,
  2091. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2092. }
  2093. if (il == n_layer - 1) {
  2094. // skip computing output for unused tokens
  2095. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2096. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2097. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  2098. }
  2099. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  2100. cb(ffn_inp, "ffn_inp", il);
  2101. // feed-forward network
  2102. {
  2103. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2104. model.layers[il].ffn_norm, NULL,
  2105. LLM_NORM_RMS, cb, il);
  2106. cb(cur, "ffn_norm", il);
  2107. cur = llm_build_ffn(ctx0, lctx, cur,
  2108. model.layers[il].ffn_up, NULL, NULL,
  2109. model.layers[il].ffn_gate, NULL, NULL,
  2110. model.layers[il].ffn_down, NULL, NULL,
  2111. NULL,
  2112. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2113. cb(cur, "ffn_out", il);
  2114. }
  2115. cur = ggml_add(ctx0, cur, ffn_inp);
  2116. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2117. cb(cur, "l_out", il);
  2118. // input for next layer
  2119. inpL = cur;
  2120. }
  2121. cur = inpL;
  2122. cur = llm_build_norm(ctx0, cur, hparams,
  2123. model.output_norm, NULL,
  2124. LLM_NORM_RMS, cb, -1);
  2125. cb(cur, "result_norm", -1);
  2126. // lm_head
  2127. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2128. cb(cur, "result_output", -1);
  2129. ggml_build_forward_expand(gf, cur);
  2130. return gf;
  2131. }
  2132. struct ggml_cgraph * build_bert() {
  2133. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2134. const int64_t n_embd_head = hparams.n_embd_head_v;
  2135. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  2136. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2137. struct ggml_tensor * cur;
  2138. struct ggml_tensor * inpL;
  2139. struct ggml_tensor * inp_pos = nullptr;
  2140. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  2141. inp_pos = build_inp_pos();
  2142. }
  2143. // construct input embeddings (token, type, position)
  2144. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2145. // token types are hardcoded to zero ("Sentence A")
  2146. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  2147. inpL = ggml_add(ctx0, inpL, type_row0);
  2148. if (model.arch == LLM_ARCH_BERT) {
  2149. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  2150. }
  2151. cb(inpL, "inp_embd", -1);
  2152. // embed layer norm
  2153. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  2154. cb(inpL, "inp_norm", -1);
  2155. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2156. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  2157. // iterate layers
  2158. for (int il = 0; il < n_layer; ++il) {
  2159. struct ggml_tensor * cur = inpL;
  2160. struct ggml_tensor * Qcur;
  2161. struct ggml_tensor * Kcur;
  2162. struct ggml_tensor * Vcur;
  2163. // self-attention
  2164. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  2165. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  2166. cb(Qcur, "Qcur", il);
  2167. if (model.layers[il].attn_q_norm) {
  2168. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  2169. model.layers[il].attn_q_norm,
  2170. model.layers[il].attn_q_norm_b,
  2171. LLM_NORM, cb, il);
  2172. }
  2173. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  2174. cb(Kcur, "Kcur", il);
  2175. if (model.layers[il].attn_k_norm) {
  2176. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  2177. model.layers[il].attn_k_norm,
  2178. model.layers[il].attn_k_norm_b,
  2179. LLM_NORM, cb, il);
  2180. }
  2181. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  2182. cb(Vcur, "Vcur", il);
  2183. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2184. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  2185. } else {
  2186. // compute Q and K and RoPE them
  2187. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  2188. cb(cur, "wqkv", il);
  2189. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  2190. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  2191. Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  2192. cb(Qcur, "Qcur", il);
  2193. cb(Kcur, "Kcur", il);
  2194. cb(Vcur, "Vcur", il);
  2195. Qcur = ggml_rope_ext(
  2196. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  2197. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2198. ext_factor, attn_factor, beta_fast, beta_slow
  2199. );
  2200. cb(Qcur, "Qcur", il);
  2201. Kcur = ggml_rope_ext(
  2202. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  2203. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2204. ext_factor, attn_factor, beta_fast, beta_slow
  2205. );
  2206. cb(Kcur, "Kcur", il);
  2207. }
  2208. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  2209. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  2210. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  2211. cb(kq, "kq", il);
  2212. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  2213. cb(kq, "kq_soft_max_ext", il);
  2214. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  2215. cb(v, "v", il);
  2216. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  2217. cb(kqv, "kqv", il);
  2218. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  2219. cb(kqv_merged, "kqv_merged", il);
  2220. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  2221. cb(cur, "kqv_merged_cont", il);
  2222. ggml_build_forward_expand(gf, cur);
  2223. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  2224. if (model.layers[il].bo) {
  2225. cb(cur, "kqv_wo", il);
  2226. }
  2227. if (model.layers[il].bo) {
  2228. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  2229. }
  2230. cb(cur, "kqv_out", il);
  2231. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  2232. // skip computing output for unused tokens
  2233. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2234. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2235. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  2236. }
  2237. // re-add the layer input
  2238. cur = ggml_add(ctx0, cur, inpL);
  2239. // attention layer norm
  2240. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  2241. if (model.layers[il].attn_norm_2 != nullptr) {
  2242. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  2243. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  2244. }
  2245. struct ggml_tensor * ffn_inp = cur;
  2246. cb(ffn_inp, "ffn_inp", il);
  2247. // feed-forward network
  2248. if (model.arch == LLM_ARCH_BERT) {
  2249. cur = llm_build_ffn(ctx0, lctx, cur,
  2250. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  2251. NULL, NULL, NULL,
  2252. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  2253. NULL,
  2254. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  2255. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  2256. cur = llm_build_ffn(ctx0, lctx, cur,
  2257. model.layers[il].ffn_up, NULL, NULL,
  2258. model.layers[il].ffn_gate, NULL, NULL,
  2259. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  2260. NULL,
  2261. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  2262. } else {
  2263. cur = llm_build_ffn(ctx0, lctx, cur,
  2264. model.layers[il].ffn_up, NULL, NULL,
  2265. model.layers[il].ffn_gate, NULL, NULL,
  2266. model.layers[il].ffn_down, NULL, NULL,
  2267. NULL,
  2268. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2269. }
  2270. cb(cur, "ffn_out", il);
  2271. // attentions bypass the intermediate layer
  2272. cur = ggml_add(ctx0, cur, ffn_inp);
  2273. // output layer norm
  2274. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  2275. // input for next layer
  2276. inpL = cur;
  2277. }
  2278. cur = inpL;
  2279. cb(cur, "result_embd", -1);
  2280. ggml_build_forward_expand(gf, cur);
  2281. return gf;
  2282. }
  2283. struct ggml_cgraph * build_bloom() {
  2284. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2285. const int64_t n_embd_head = hparams.n_embd_head_v;
  2286. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  2287. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2288. struct ggml_tensor * cur;
  2289. struct ggml_tensor * inpL;
  2290. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2291. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2292. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2293. inpL = llm_build_norm(ctx0, inpL, hparams,
  2294. model.tok_norm,
  2295. model.tok_norm_b,
  2296. LLM_NORM, cb, -1);
  2297. cb(inpL, "inp_norm", -1);
  2298. for (int il = 0; il < n_layer; ++il) {
  2299. cur = llm_build_norm(ctx0, inpL, hparams,
  2300. model.layers[il].attn_norm,
  2301. model.layers[il].attn_norm_b,
  2302. LLM_NORM, cb, il);
  2303. cb(cur, "attn_norm", il);
  2304. // self-attention
  2305. {
  2306. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  2307. cb(cur, "wqkv", il);
  2308. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  2309. cb(cur, "bqkv", il);
  2310. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  2311. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  2312. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  2313. cb(Qcur, "Qcur", il);
  2314. cb(Kcur, "Kcur", il);
  2315. cb(Vcur, "Vcur", il);
  2316. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2317. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2318. model.layers[il].wo, model.layers[il].bo,
  2319. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2320. }
  2321. if (il == n_layer - 1) {
  2322. // skip computing output for unused tokens
  2323. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2324. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2325. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  2326. }
  2327. // Add the input
  2328. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  2329. cb(ffn_inp, "ffn_inp", il);
  2330. // FF
  2331. {
  2332. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2333. model.layers[il].ffn_norm,
  2334. model.layers[il].ffn_norm_b,
  2335. LLM_NORM, cb, il);
  2336. cb(cur, "ffn_norm", il);
  2337. cur = llm_build_ffn(ctx0, lctx, cur,
  2338. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  2339. NULL, NULL, NULL,
  2340. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  2341. NULL,
  2342. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  2343. cb(cur, "ffn_out", il);
  2344. }
  2345. cur = ggml_add(ctx0, cur, ffn_inp);
  2346. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2347. cb(cur, "l_out", il);
  2348. // input for next layer
  2349. inpL = cur;
  2350. }
  2351. cur = llm_build_norm(ctx0, inpL, hparams,
  2352. model.output_norm,
  2353. model.output_norm_b,
  2354. LLM_NORM, cb, -1);
  2355. cb(cur, "result_norm", -1);
  2356. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2357. cb(cur, "result_output", -1);
  2358. ggml_build_forward_expand(gf, cur);
  2359. return gf;
  2360. }
  2361. struct ggml_cgraph * build_mpt() {
  2362. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2363. const int64_t n_embd_head = hparams.n_embd_head_v;
  2364. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  2365. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2366. struct ggml_tensor * cur;
  2367. struct ggml_tensor * pos;
  2368. struct ggml_tensor * inpL;
  2369. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2370. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2371. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2372. if (model.pos_embd) {
  2373. // inp_pos - contains the positions
  2374. struct ggml_tensor * inp_pos = build_inp_pos();
  2375. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  2376. cb(pos, "pos_embd", -1);
  2377. inpL = ggml_add(ctx0, inpL, pos);
  2378. cb(inpL, "inpL", -1);
  2379. }
  2380. for (int il = 0; il < n_layer; ++il) {
  2381. struct ggml_tensor * attn_norm;
  2382. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  2383. model.layers[il].attn_norm,
  2384. model.layers[il].attn_norm_b,
  2385. LLM_NORM, cb, il);
  2386. cb(attn_norm, "attn_norm", il);
  2387. // self-attention
  2388. {
  2389. cur = attn_norm;
  2390. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  2391. cb(cur, "wqkv", il);
  2392. if (model.layers[il].bqkv){
  2393. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  2394. cb(cur, "bqkv", il);
  2395. }
  2396. if (hparams.f_clamp_kqv > 0.0f) {
  2397. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  2398. cb(cur, "wqkv_clamped", il);
  2399. }
  2400. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  2401. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  2402. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  2403. cb(Qcur, "Qcur", il);
  2404. cb(Kcur, "Kcur", il);
  2405. cb(Vcur, "Vcur", il);
  2406. // Q/K Layernorm
  2407. if (model.layers[il].attn_q_norm) {
  2408. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  2409. model.layers[il].attn_q_norm,
  2410. model.layers[il].attn_q_norm_b,
  2411. LLM_NORM, cb, il);
  2412. cb(Qcur, "Qcur", il);
  2413. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  2414. model.layers[il].attn_k_norm,
  2415. model.layers[il].attn_k_norm_b,
  2416. LLM_NORM, cb, il);
  2417. cb(Kcur, "Kcur", il);
  2418. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2419. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  2420. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2421. model.layers[il].wo, model.layers[il].bo,
  2422. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2423. } else {
  2424. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2425. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2426. model.layers[il].wo, model.layers[il].bo,
  2427. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2428. }
  2429. }
  2430. if (il == n_layer - 1) {
  2431. // skip computing output for unused tokens
  2432. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2433. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2434. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  2435. }
  2436. // Add the input
  2437. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  2438. cb(ffn_inp, "ffn_inp", il);
  2439. // feed forward
  2440. {
  2441. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2442. model.layers[il].ffn_norm,
  2443. model.layers[il].ffn_norm_b,
  2444. LLM_NORM, cb, il);
  2445. cb(cur, "ffn_norm", il);
  2446. cur = llm_build_ffn(ctx0, lctx, cur,
  2447. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  2448. NULL, NULL, NULL,
  2449. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  2450. model.layers[il].ffn_act,
  2451. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  2452. cb(cur, "ffn_out", il);
  2453. }
  2454. cur = ggml_add(ctx0, cur, ffn_inp);
  2455. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2456. cb(cur, "l_out", il);
  2457. // input for next layer
  2458. inpL = cur;
  2459. }
  2460. cur = inpL;
  2461. cur = llm_build_norm(ctx0, cur, hparams,
  2462. model.output_norm,
  2463. model.output_norm_b,
  2464. LLM_NORM, cb, -1);
  2465. cb(cur, "result_norm", -1);
  2466. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2467. cb(cur, "result_output", -1);
  2468. ggml_build_forward_expand(gf, cur);
  2469. return gf;
  2470. }
  2471. struct ggml_cgraph * build_stablelm() {
  2472. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  2473. const int64_t n_embd_head = hparams.n_embd_head_v;
  2474. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2475. struct ggml_tensor * cur;
  2476. struct ggml_tensor * inpL;
  2477. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2478. // inp_pos - contains the positions
  2479. struct ggml_tensor * inp_pos = build_inp_pos();
  2480. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2481. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2482. for (int il = 0; il < n_layer; ++il) {
  2483. // norm
  2484. cur = llm_build_norm(ctx0, inpL, hparams,
  2485. model.layers[il].attn_norm,
  2486. model.layers[il].attn_norm_b,
  2487. LLM_NORM, cb, il);
  2488. cb(cur, "attn_norm", il);
  2489. struct ggml_tensor * inpSA = cur;
  2490. // self-attention
  2491. {
  2492. // compute Q and K and RoPE them
  2493. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  2494. cb(Qcur, "Qcur", il);
  2495. if (model.layers[il].bq) {
  2496. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  2497. cb(Qcur, "Qcur", il);
  2498. }
  2499. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  2500. cb(Kcur, "Kcur", il);
  2501. if (model.layers[il].bk) {
  2502. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  2503. cb(Kcur, "Kcur", il);
  2504. }
  2505. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  2506. cb(Vcur, "Vcur", il);
  2507. if (model.layers[il].bv) {
  2508. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  2509. cb(Vcur, "Vcur", il);
  2510. }
  2511. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2512. cb(Qcur, "Qcur", il);
  2513. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  2514. cb(Kcur, "Kcur", il);
  2515. if (model.layers[il].attn_q_norm) {
  2516. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  2517. model.layers[il].attn_q_norm,
  2518. NULL,
  2519. LLM_NORM, cb, il);
  2520. cb(Qcur, "Qcur", il);
  2521. }
  2522. if (model.layers[il].attn_k_norm) {
  2523. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  2524. model.layers[il].attn_k_norm,
  2525. NULL,
  2526. LLM_NORM, cb, il);
  2527. cb(Kcur, "Kcur", il);
  2528. }
  2529. Qcur = ggml_rope_ext(
  2530. ctx0, Qcur, inp_pos, nullptr,
  2531. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2532. ext_factor, attn_factor, beta_fast, beta_slow
  2533. );
  2534. cb(Qcur, "Qcur", il);
  2535. Kcur = ggml_rope_ext(
  2536. ctx0, Kcur, inp_pos, nullptr,
  2537. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2538. ext_factor, attn_factor, beta_fast, beta_slow
  2539. );
  2540. cb(Kcur, "Kcur", il);
  2541. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2542. model.layers[il].wo, NULL,
  2543. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2544. }
  2545. if (il == n_layer - 1) {
  2546. // skip computing output for unused tokens
  2547. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2548. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2549. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  2550. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  2551. }
  2552. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  2553. cb(ffn_inp, "ffn_inp", il);
  2554. // feed-forward network
  2555. {
  2556. if (model.layers[il].ffn_norm) {
  2557. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2558. model.layers[il].ffn_norm,
  2559. model.layers[il].ffn_norm_b,
  2560. LLM_NORM, cb, il);
  2561. cb(cur, "ffn_norm", il);
  2562. } else {
  2563. // parallel residual
  2564. cur = inpSA;
  2565. }
  2566. cur = llm_build_ffn(ctx0, lctx, cur,
  2567. model.layers[il].ffn_up, NULL, NULL,
  2568. model.layers[il].ffn_gate, NULL, NULL,
  2569. model.layers[il].ffn_down, NULL, NULL,
  2570. NULL,
  2571. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2572. cb(cur, "ffn_out", il);
  2573. }
  2574. cur = ggml_add(ctx0, cur, ffn_inp);
  2575. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2576. cb(cur, "l_out", il);
  2577. // input for next layer
  2578. inpL = cur;
  2579. }
  2580. cur = inpL;
  2581. cur = llm_build_norm(ctx0, cur, hparams,
  2582. model.output_norm,
  2583. model.output_norm_b,
  2584. LLM_NORM, cb, -1);
  2585. cb(cur, "result_norm", -1);
  2586. // lm_head
  2587. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2588. cb(cur, "result_output", -1);
  2589. ggml_build_forward_expand(gf, cur);
  2590. return gf;
  2591. }
  2592. struct ggml_cgraph * build_qwen() {
  2593. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2594. const int64_t n_embd_head = hparams.n_embd_head_v;
  2595. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2596. struct ggml_tensor * cur;
  2597. struct ggml_tensor * inpL;
  2598. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2599. // inp_pos - contains the positions
  2600. struct ggml_tensor * inp_pos = build_inp_pos();
  2601. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2602. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2603. for (int il = 0; il < n_layer; ++il) {
  2604. struct ggml_tensor * inpSA = inpL;
  2605. cur = llm_build_norm(ctx0, inpL, hparams,
  2606. model.layers[il].attn_norm, NULL,
  2607. LLM_NORM_RMS, cb, il);
  2608. cb(cur, "attn_norm", il);
  2609. // self-attention
  2610. {
  2611. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  2612. cb(cur, "wqkv", il);
  2613. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  2614. cb(cur, "bqkv", il);
  2615. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  2616. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  2617. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  2618. cb(Qcur, "Qcur", il);
  2619. cb(Kcur, "Kcur", il);
  2620. cb(Vcur, "Vcur", il);
  2621. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  2622. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  2623. // using mode = 2 for neox mode
  2624. Qcur = ggml_rope_ext(
  2625. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  2626. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  2627. );
  2628. cb(Qcur, "Qcur", il);
  2629. Kcur = ggml_rope_ext(
  2630. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  2631. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  2632. );
  2633. cb(Kcur, "Kcur", il);
  2634. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2635. model.layers[il].wo, NULL,
  2636. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2637. }
  2638. if (il == n_layer - 1) {
  2639. // skip computing output for unused tokens
  2640. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2641. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2642. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  2643. }
  2644. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  2645. cb(ffn_inp, "ffn_inp", il);
  2646. // feed-forward forward
  2647. {
  2648. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2649. model.layers[il].ffn_norm, NULL,
  2650. LLM_NORM_RMS, cb, il);
  2651. cb(cur, "ffn_norm", il);
  2652. cur = llm_build_ffn(ctx0, lctx, cur,
  2653. model.layers[il].ffn_up, NULL, NULL,
  2654. model.layers[il].ffn_gate, NULL, NULL,
  2655. model.layers[il].ffn_down, NULL, NULL,
  2656. NULL,
  2657. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2658. cb(cur, "ffn_out", il);
  2659. }
  2660. cur = ggml_add(ctx0, cur, ffn_inp);
  2661. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2662. cb(cur, "l_out", il);
  2663. // input for next layer
  2664. inpL = cur;
  2665. }
  2666. cur = inpL;
  2667. cur = llm_build_norm(ctx0, cur, hparams,
  2668. model.output_norm, NULL,
  2669. LLM_NORM_RMS, cb, -1);
  2670. cb(cur, "result_norm", -1);
  2671. // lm_head
  2672. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2673. cb(cur, "result_output", -1);
  2674. ggml_build_forward_expand(gf, cur);
  2675. return gf;
  2676. }
  2677. struct ggml_cgraph * build_qwen2() {
  2678. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2679. const int64_t n_embd_head = hparams.n_embd_head_v;
  2680. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2681. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2682. struct ggml_tensor * cur;
  2683. struct ggml_tensor * inpL;
  2684. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2685. // inp_pos - contains the positions
  2686. struct ggml_tensor * inp_pos = build_inp_pos();
  2687. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2688. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2689. for (int il = 0; il < n_layer; ++il) {
  2690. struct ggml_tensor * inpSA = inpL;
  2691. // norm
  2692. cur = llm_build_norm(ctx0, inpL, hparams,
  2693. model.layers[il].attn_norm, NULL,
  2694. LLM_NORM_RMS, cb, il);
  2695. cb(cur, "attn_norm", il);
  2696. // self-attention
  2697. {
  2698. // compute Q and K and RoPE them
  2699. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  2700. cb(Qcur, "Qcur", il);
  2701. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  2702. cb(Qcur, "Qcur", il);
  2703. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  2704. cb(Kcur, "Kcur", il);
  2705. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  2706. cb(Kcur, "Kcur", il);
  2707. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  2708. cb(Vcur, "Vcur", il);
  2709. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  2710. cb(Vcur, "Vcur", il);
  2711. Qcur = ggml_rope_ext(
  2712. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  2713. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2714. ext_factor, attn_factor, beta_fast, beta_slow
  2715. );
  2716. cb(Qcur, "Qcur", il);
  2717. Kcur = ggml_rope_ext(
  2718. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  2719. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2720. ext_factor, attn_factor, beta_fast, beta_slow
  2721. );
  2722. cb(Kcur, "Kcur", il);
  2723. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2724. model.layers[il].wo, model.layers[il].bo,
  2725. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2726. }
  2727. if (il == n_layer - 1) {
  2728. // skip computing output for unused tokens
  2729. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2730. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2731. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  2732. }
  2733. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  2734. cb(ffn_inp, "ffn_inp", il);
  2735. // feed-forward network
  2736. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2737. model.layers[il].ffn_norm, NULL,
  2738. LLM_NORM_RMS, cb, il);
  2739. cb(cur, "ffn_norm", il);
  2740. cur = llm_build_ffn(ctx0, lctx, cur,
  2741. model.layers[il].ffn_up, NULL, NULL,
  2742. model.layers[il].ffn_gate, NULL, NULL,
  2743. model.layers[il].ffn_down, NULL, NULL,
  2744. NULL,
  2745. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2746. cb(cur, "ffn_out", il);
  2747. cur = ggml_add(ctx0, cur, ffn_inp);
  2748. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2749. cb(cur, "l_out", il);
  2750. // input for next layer
  2751. inpL = cur;
  2752. }
  2753. cur = inpL;
  2754. cur = llm_build_norm(ctx0, cur, hparams,
  2755. model.output_norm, NULL,
  2756. LLM_NORM_RMS, cb, -1);
  2757. cb(cur, "result_norm", -1);
  2758. // lm_head
  2759. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2760. cb(cur, "result_output", -1);
  2761. ggml_build_forward_expand(gf, cur);
  2762. return gf;
  2763. }
  2764. struct ggml_cgraph * build_qwen2vl() {
  2765. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2766. const int64_t n_embd_head = hparams.n_embd_head_v;
  2767. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2768. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2769. struct ggml_tensor * cur;
  2770. struct ggml_tensor * inpL;
  2771. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2772. // inp_pos - contains the positions
  2773. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens * 4);
  2774. cb(lctx.inp_pos, "inp_pos", -1);
  2775. ggml_set_input(lctx.inp_pos);
  2776. struct ggml_tensor * inp_pos = lctx.inp_pos;
  2777. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2778. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2779. int sections[4];
  2780. std::copy(std::begin(hparams.rope_sections), std::begin(hparams.rope_sections) + 4, sections);
  2781. for (int il = 0; il < n_layer; ++il) {
  2782. struct ggml_tensor * inpSA = inpL;
  2783. // norm
  2784. cur = llm_build_norm(ctx0, inpL, hparams,
  2785. model.layers[il].attn_norm, NULL,
  2786. LLM_NORM_RMS, cb, il);
  2787. cb(cur, "attn_norm", il);
  2788. // self-attention
  2789. {
  2790. // compute Q and K and RoPE them
  2791. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  2792. cb(Qcur, "Qcur", il);
  2793. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  2794. cb(Qcur, "Qcur", il);
  2795. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  2796. cb(Kcur, "Kcur", il);
  2797. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  2798. cb(Kcur, "Kcur", il);
  2799. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  2800. cb(Vcur, "Vcur", il);
  2801. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  2802. cb(Vcur, "Vcur", il);
  2803. Qcur = ggml_rope_multi(
  2804. ctx0,
  2805. ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  2806. n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
  2807. ext_factor, attn_factor, beta_fast, beta_slow
  2808. );
  2809. cb(Qcur, "Qcur", il);
  2810. Kcur = ggml_rope_multi(
  2811. ctx0,
  2812. ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  2813. n_rot, sections, rope_type, n_ctx_orig, freq_base, freq_scale,
  2814. ext_factor, attn_factor, beta_fast, beta_slow
  2815. );
  2816. cb(Kcur, "Kcur", il);
  2817. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2818. model.layers[il].wo, model.layers[il].bo,
  2819. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2820. }
  2821. if (il == n_layer - 1) {
  2822. // skip computing output for unused tokens
  2823. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2824. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2825. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  2826. }
  2827. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  2828. cb(ffn_inp, "ffn_inp", il);
  2829. // feed-forward network
  2830. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2831. model.layers[il].ffn_norm, NULL,
  2832. LLM_NORM_RMS, cb, il);
  2833. cb(cur, "ffn_norm", il);
  2834. cur = llm_build_ffn(ctx0, lctx, cur,
  2835. model.layers[il].ffn_up, NULL, NULL,
  2836. model.layers[il].ffn_gate, NULL, NULL,
  2837. model.layers[il].ffn_down, NULL, NULL,
  2838. NULL,
  2839. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2840. cb(cur, "ffn_out", il);
  2841. cur = ggml_add(ctx0, cur, ffn_inp);
  2842. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2843. cb(cur, "l_out", il);
  2844. // input for next layer
  2845. inpL = cur;
  2846. }
  2847. cur = inpL;
  2848. cur = llm_build_norm(ctx0, cur, hparams,
  2849. model.output_norm, NULL,
  2850. LLM_NORM_RMS, cb, -1);
  2851. cb(cur, "result_norm", -1);
  2852. // lm_head
  2853. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2854. cb(cur, "result_output", -1);
  2855. ggml_build_forward_expand(gf, cur);
  2856. return gf;
  2857. }
  2858. struct ggml_cgraph * build_qwen2moe() {
  2859. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2860. // mutable variable, needed during the last layer of the computation to skip unused tokens
  2861. int32_t n_tokens = this->n_tokens;
  2862. const int64_t n_embd_head = hparams.n_embd_head_v;
  2863. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2864. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2865. struct ggml_tensor * cur;
  2866. struct ggml_tensor * inpL;
  2867. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2868. // inp_pos - contains the positions
  2869. struct ggml_tensor * inp_pos = build_inp_pos();
  2870. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2871. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2872. for (int il = 0; il < n_layer; ++il) {
  2873. struct ggml_tensor * inpSA = inpL;
  2874. // norm
  2875. cur = llm_build_norm(ctx0, inpL, hparams,
  2876. model.layers[il].attn_norm, NULL,
  2877. LLM_NORM_RMS, cb, il);
  2878. cb(cur, "attn_norm", il);
  2879. // self_attention
  2880. {
  2881. // compute Q and K and RoPE them
  2882. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  2883. cb(Qcur, "Qcur", il);
  2884. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  2885. cb(Qcur, "Qcur", il);
  2886. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  2887. cb(Kcur, "Kcur", il);
  2888. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  2889. cb(Kcur, "Kcur", il);
  2890. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  2891. cb(Vcur, "Vcur", il);
  2892. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  2893. cb(Vcur, "Vcur", il);
  2894. Qcur = ggml_rope_ext(
  2895. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  2896. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2897. ext_factor, attn_factor, beta_fast, beta_slow
  2898. );
  2899. cb(Qcur, "Qcur", il);
  2900. Kcur = ggml_rope_ext(
  2901. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  2902. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  2903. ext_factor, attn_factor, beta_fast, beta_slow
  2904. );
  2905. cb(Kcur, "Kcur", il);
  2906. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  2907. model.layers[il].wo, model.layers[il].bo,
  2908. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  2909. }
  2910. if (il == n_layer - 1) {
  2911. // skip computing output for unused tokens
  2912. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  2913. n_tokens = n_outputs;
  2914. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  2915. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  2916. }
  2917. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  2918. cb(ffn_inp, "ffn_inp", il);
  2919. // MoE branch
  2920. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  2921. model.layers[il].ffn_norm, NULL,
  2922. LLM_NORM_RMS, cb, il);
  2923. cb(cur, "ffn_norm", il);
  2924. ggml_tensor * moe_out =
  2925. llm_build_moe_ffn(ctx0, lctx, cur,
  2926. model.layers[il].ffn_gate_inp,
  2927. model.layers[il].ffn_up_exps,
  2928. model.layers[il].ffn_gate_exps,
  2929. model.layers[il].ffn_down_exps,
  2930. nullptr,
  2931. n_expert, n_expert_used,
  2932. LLM_FFN_SILU, false,
  2933. false, 0.0,
  2934. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  2935. cb, il);
  2936. cb(cur, "ffn_moe_out", il);
  2937. // FFN shared expert
  2938. {
  2939. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  2940. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  2941. // sigmoid
  2942. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  2943. cb(cur_gate, "ffn_shexp_gate", il);
  2944. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  2945. model.layers[il].ffn_up_shexp, NULL, NULL,
  2946. model.layers[il].ffn_gate_shexp, NULL, NULL,
  2947. model.layers[il].ffn_down_shexp, NULL, NULL,
  2948. NULL,
  2949. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  2950. cb(cur_ffn, "ffn_shexp", il);
  2951. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  2952. cb(ffn_shexp_out, "ffn_shexp_out", il);
  2953. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  2954. cb(moe_out, "ffn_out", il);
  2955. cur = moe_out;
  2956. }
  2957. cur = ggml_add(ctx0, cur, ffn_inp);
  2958. cur = lctx.cvec.apply_to(ctx0, cur, il);
  2959. cb(cur, "l_out", il);
  2960. // input for next layer
  2961. inpL = cur;
  2962. }
  2963. cur = inpL;
  2964. cur = llm_build_norm(ctx0, cur, hparams,
  2965. model.output_norm, NULL,
  2966. LLM_NORM_RMS, cb, -1);
  2967. cb(cur, "result_norm", -1);
  2968. // lm_head
  2969. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  2970. cb(cur, "result_output", -1);
  2971. ggml_build_forward_expand(gf, cur);
  2972. return gf;
  2973. }
  2974. struct ggml_cgraph * build_phi2() {
  2975. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  2976. const int64_t n_embd_head = hparams.n_embd_head_v;
  2977. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  2978. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  2979. struct ggml_tensor * cur;
  2980. struct ggml_tensor * attn_norm_output;
  2981. struct ggml_tensor * ffn_output;
  2982. struct ggml_tensor * inpL;
  2983. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  2984. // inp_pos - contains the positions
  2985. struct ggml_tensor * inp_pos = build_inp_pos();
  2986. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2987. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  2988. for (int il = 0; il < n_layer; ++il) {
  2989. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  2990. model.layers[il].attn_norm,
  2991. model.layers[il].attn_norm_b,
  2992. LLM_NORM, cb, il);
  2993. cb(attn_norm_output, "attn_norm", il);
  2994. // self-attention
  2995. {
  2996. struct ggml_tensor * Qcur = nullptr;
  2997. struct ggml_tensor * Kcur = nullptr;
  2998. struct ggml_tensor * Vcur = nullptr;
  2999. if (model.layers[il].wqkv) {
  3000. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  3001. cb(cur, "wqkv", il);
  3002. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3003. cb(cur, "bqkv", il);
  3004. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3005. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  3006. Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  3007. } else {
  3008. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  3009. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  3010. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  3011. }
  3012. cb(Qcur, "Qcur", il);
  3013. cb(Kcur, "Kcur", il);
  3014. cb(Vcur, "Vcur", il);
  3015. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3016. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  3017. Qcur = ggml_rope_ext(
  3018. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  3019. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3020. );
  3021. cb(Qcur, "Qcur", il);
  3022. // with phi2, we scale the Q to avoid precision issues
  3023. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  3024. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  3025. cb(Qcur, "Qcur", il);
  3026. Kcur = ggml_rope_ext(
  3027. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  3028. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3029. );
  3030. cb(Kcur, "Kcur", il);
  3031. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3032. model.layers[il].wo, model.layers[il].bo,
  3033. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  3034. }
  3035. if (il == n_layer - 1) {
  3036. // skip computing output for unused tokens
  3037. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3038. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3039. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  3040. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  3041. }
  3042. // FF
  3043. {
  3044. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  3045. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  3046. NULL, NULL, NULL,
  3047. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  3048. NULL,
  3049. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3050. cb(ffn_output, "ffn_out", il);
  3051. }
  3052. cur = ggml_add(ctx0, cur, ffn_output);
  3053. cur = ggml_add(ctx0, cur, inpL);
  3054. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3055. cb(cur, "l_out", il);
  3056. // input for next layer
  3057. inpL = cur;
  3058. }
  3059. cur = llm_build_norm(ctx0, inpL, hparams,
  3060. model.output_norm,
  3061. model.output_norm_b,
  3062. LLM_NORM, cb, -1);
  3063. cb(cur, "result_norm", -1);
  3064. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3065. cb(cur, "result_output_no_bias", -1);
  3066. cur = ggml_add(ctx0, cur, model.output_b);
  3067. cb(cur, "result_output", -1);
  3068. ggml_build_forward_expand(gf, cur);
  3069. return gf;
  3070. }
  3071. struct ggml_cgraph * build_phi3() {
  3072. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3073. const int64_t n_embd_head = hparams.n_embd_head_v;
  3074. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  3075. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3076. struct ggml_tensor * cur;
  3077. struct ggml_tensor * inpL;
  3078. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3079. // inp_pos - contains the positions
  3080. struct ggml_tensor * inp_pos = build_inp_pos();
  3081. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3082. struct ggml_tensor * KQ_mask = nullptr;
  3083. if (hparams.n_swa == 0) {
  3084. // Phi-4 doesn't use sliding window attention
  3085. KQ_mask = build_inp_KQ_mask();
  3086. } else {
  3087. KQ_mask = build_inp_KQ_mask_swa();
  3088. }
  3089. for (int il = 0; il < n_layer; ++il) {
  3090. auto residual = inpL;
  3091. // self-attention
  3092. {
  3093. // rope freq factors for 128k context
  3094. struct ggml_tensor * rope_factors = build_rope_factors(il);
  3095. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  3096. model.layers[il].attn_norm,
  3097. model.layers[il].attn_norm_b,
  3098. LLM_NORM_RMS, cb, il);
  3099. cb(attn_norm_output, "attn_norm", il);
  3100. struct ggml_tensor * Qcur = nullptr;
  3101. struct ggml_tensor * Kcur = nullptr;
  3102. struct ggml_tensor * Vcur = nullptr;
  3103. if (model.layers[il].wqkv) {
  3104. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  3105. cb(cur, "wqkv", il);
  3106. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  3107. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  3108. Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd + n_embd_gqa)));
  3109. } else {
  3110. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  3111. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  3112. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  3113. }
  3114. cb(Qcur, "Qcur", il);
  3115. cb(Kcur, "Kcur", il);
  3116. cb(Vcur, "Vcur", il);
  3117. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3118. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  3119. Qcur = ggml_rope_ext(
  3120. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  3121. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3122. );
  3123. cb(Qcur, "Qcur", il);
  3124. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  3125. cb(Qcur, "Qcur", il);
  3126. Kcur = ggml_rope_ext(
  3127. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  3128. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3129. );
  3130. cb(Kcur, "Kcur", il);
  3131. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3132. model.layers[il].wo, model.layers[il].bo,
  3133. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  3134. }
  3135. if (il == n_layer - 1) {
  3136. // skip computing output for unused tokens
  3137. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  3138. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3139. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  3140. }
  3141. cur = ggml_add(ctx0, cur, residual);
  3142. residual = cur;
  3143. cur = llm_build_norm(ctx0, cur, hparams,
  3144. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  3145. LLM_NORM_RMS, cb, il);
  3146. cb(cur, "ffn_norm", il);
  3147. // feed-forward network
  3148. if (model.layers[il].ffn_gate_inp == nullptr) {
  3149. cur = llm_build_ffn(ctx0, lctx, cur,
  3150. model.layers[il].ffn_up, NULL, NULL,
  3151. NULL, NULL, NULL,
  3152. model.layers[il].ffn_down, NULL, NULL,
  3153. NULL,
  3154. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  3155. cb(cur, "ffn_out", il);
  3156. } else {
  3157. // MoE branch
  3158. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  3159. model.layers[il].ffn_gate_inp,
  3160. model.layers[il].ffn_up_exps,
  3161. model.layers[il].ffn_gate_exps,
  3162. model.layers[il].ffn_down_exps,
  3163. nullptr,
  3164. n_expert, n_expert_used,
  3165. LLM_FFN_SILU, true,
  3166. false, 0.0,
  3167. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  3168. cb, il);
  3169. cb(cur, "ffn_moe_out", il);
  3170. }
  3171. cur = ggml_add(ctx0, residual, cur);
  3172. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3173. cb(cur, "l_out", il);
  3174. // input for next layer
  3175. inpL = cur;
  3176. }
  3177. cur = llm_build_norm(ctx0, inpL, hparams,
  3178. model.output_norm,
  3179. model.output_norm_b,
  3180. LLM_NORM_RMS, cb, -1);
  3181. cb(cur, "result_norm", -1);
  3182. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3183. if (model.output_b != nullptr) {
  3184. cb(cur, "result_output_no_bias", -1);
  3185. cur = ggml_add(ctx0, cur, model.output_b);
  3186. }
  3187. cb(cur, "result_output", -1);
  3188. ggml_build_forward_expand(gf, cur);
  3189. return gf;
  3190. }
  3191. struct ggml_cgraph * build_plamo() {
  3192. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  3193. const int64_t n_embd_head = hparams.n_embd_head_v;
  3194. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3195. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3196. struct ggml_tensor * cur;
  3197. struct ggml_tensor * inpL;
  3198. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3199. // inp_pos - contains the positions
  3200. struct ggml_tensor * inp_pos = build_inp_pos();
  3201. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3202. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3203. for (int il = 0; il < n_layer; ++il) {
  3204. // norm
  3205. cur = llm_build_norm(ctx0, inpL, hparams,
  3206. model.layers[il].attn_norm, NULL,
  3207. LLM_NORM_RMS, cb, il);
  3208. cb(cur, "attn_norm", il);
  3209. struct ggml_tensor * attention_norm = cur;
  3210. // self-attention
  3211. {
  3212. // compute Q and K and RoPE them
  3213. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  3214. cb(Qcur, "Qcur", il);
  3215. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  3216. cb(Kcur, "Kcur", il);
  3217. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  3218. cb(Vcur, "Vcur", il);
  3219. Qcur = ggml_rope_ext(
  3220. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  3221. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  3222. ext_factor, attn_factor, beta_fast, beta_slow);
  3223. cb(Qcur, "Qcur", il);
  3224. Kcur = ggml_rope_ext(
  3225. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  3226. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  3227. ext_factor, attn_factor, beta_fast, beta_slow);
  3228. cb(Kcur, "Kcur", il);
  3229. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3230. model.layers[il].wo, NULL,
  3231. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3232. }
  3233. struct ggml_tensor * sa_out = cur;
  3234. cur = attention_norm;
  3235. if (il == n_layer - 1) {
  3236. // skip computing output for unused tokens
  3237. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3238. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3239. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  3240. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  3241. }
  3242. // feed-forward network
  3243. {
  3244. cur = llm_build_ffn(ctx0, lctx, cur,
  3245. model.layers[il].ffn_up, NULL, NULL,
  3246. model.layers[il].ffn_gate, NULL, NULL,
  3247. model.layers[il].ffn_down, NULL, NULL,
  3248. NULL,
  3249. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3250. cb(cur, "ffn_out", il);
  3251. }
  3252. cur = ggml_add(ctx0, cur, sa_out);
  3253. cur = ggml_add(ctx0, cur, inpL);
  3254. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3255. cb(cur, "l_out", il);
  3256. // input for next layer
  3257. inpL = cur;
  3258. }
  3259. cur = inpL;
  3260. cur = llm_build_norm(ctx0, cur, hparams,
  3261. model.output_norm, NULL,
  3262. LLM_NORM_RMS, cb, -1);
  3263. cb(cur, "result_norm", -1);
  3264. // lm_head
  3265. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3266. cb(cur, "result_output", -1);
  3267. ggml_build_forward_expand(gf, cur);
  3268. return gf;
  3269. }
  3270. struct ggml_cgraph * build_gpt2() {
  3271. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3272. const int64_t n_embd_head = hparams.n_embd_head_v;
  3273. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  3274. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3275. struct ggml_tensor * cur;
  3276. struct ggml_tensor * pos;
  3277. struct ggml_tensor * inpL;
  3278. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3279. // inp_pos - contains the positions
  3280. struct ggml_tensor * inp_pos = build_inp_pos();
  3281. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3282. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3283. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  3284. cb(pos, "pos_embd", -1);
  3285. inpL = ggml_add(ctx0, inpL, pos);
  3286. cb(inpL, "inpL", -1);
  3287. for (int il = 0; il < n_layer; ++il) {
  3288. cur = llm_build_norm(ctx0, inpL, hparams,
  3289. model.layers[il].attn_norm,
  3290. model.layers[il].attn_norm_b,
  3291. LLM_NORM, cb, il);
  3292. cb(cur, "attn_norm", il);
  3293. // self-attention
  3294. {
  3295. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  3296. cb(cur, "wqkv", il);
  3297. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3298. cb(cur, "bqkv", il);
  3299. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3300. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  3301. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  3302. cb(Qcur, "Qcur", il);
  3303. cb(Kcur, "Kcur", il);
  3304. cb(Vcur, "Vcur", il);
  3305. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3306. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3307. model.layers[il].wo, model.layers[il].bo,
  3308. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3309. }
  3310. if (il == n_layer - 1) {
  3311. // skip computing output for unused tokens
  3312. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3313. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3314. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  3315. }
  3316. // add the input
  3317. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  3318. cb(ffn_inp, "ffn_inp", il);
  3319. // FF
  3320. {
  3321. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3322. model.layers[il].ffn_norm,
  3323. model.layers[il].ffn_norm_b,
  3324. LLM_NORM, cb, il);
  3325. cb(cur, "ffn_norm", il);
  3326. cur = llm_build_ffn(ctx0, lctx, cur,
  3327. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  3328. NULL, NULL, NULL,
  3329. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  3330. NULL,
  3331. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3332. cb(cur, "ffn_out", il);
  3333. }
  3334. cur = ggml_add(ctx0, cur, ffn_inp);
  3335. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3336. cb(cur, "l_out", il);
  3337. // input for next layer
  3338. inpL = cur;
  3339. }
  3340. cur = llm_build_norm(ctx0, inpL, hparams,
  3341. model.output_norm,
  3342. model.output_norm_b,
  3343. LLM_NORM, cb, -1);
  3344. cb(cur, "result_norm", -1);
  3345. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3346. cb(cur, "result_output", -1);
  3347. ggml_build_forward_expand(gf, cur);
  3348. return gf;
  3349. }
  3350. struct ggml_cgraph * build_codeshell() {
  3351. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3352. const int64_t n_embd_head = hparams.n_embd_head_v;
  3353. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  3354. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3355. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3356. struct ggml_tensor * cur;
  3357. struct ggml_tensor * inpL;
  3358. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3359. // inp_pos - contains the positions
  3360. struct ggml_tensor * inp_pos = build_inp_pos();
  3361. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3362. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3363. for (int il = 0; il < n_layer; ++il) {
  3364. cur = llm_build_norm(ctx0, inpL, hparams,
  3365. model.layers[il].attn_norm,
  3366. model.layers[il].attn_norm_b,
  3367. LLM_NORM, cb, il);
  3368. cb(cur, "attn_norm", il);
  3369. // self-attention
  3370. {
  3371. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  3372. cb(cur, "wqkv", il);
  3373. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  3374. cb(cur, "bqkv", il);
  3375. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3376. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  3377. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  3378. cb(tmpq, "tmpq", il);
  3379. cb(tmpk, "tmpk", il);
  3380. cb(Vcur, "Vcur", il);
  3381. struct ggml_tensor * Qcur = ggml_rope_ext(
  3382. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  3383. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3384. ext_factor, attn_factor, beta_fast, beta_slow
  3385. );
  3386. cb(Qcur, "Qcur", il);
  3387. struct ggml_tensor * Kcur = ggml_rope_ext(
  3388. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  3389. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3390. ext_factor, attn_factor, beta_fast, beta_slow
  3391. );
  3392. cb(Kcur, "Kcur", il);
  3393. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3394. model.layers[il].wo, model.layers[il].bo,
  3395. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3396. }
  3397. if (il == n_layer - 1) {
  3398. // skip computing output for unused tokens
  3399. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3400. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3401. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  3402. }
  3403. // add the input
  3404. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  3405. cb(ffn_inp, "ffn_inp", il);
  3406. // FF
  3407. {
  3408. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3409. model.layers[il].ffn_norm,
  3410. model.layers[il].ffn_norm_b,
  3411. LLM_NORM, cb, il);
  3412. cb(cur, "ffn_norm", il);
  3413. cur = llm_build_ffn(ctx0, lctx, cur,
  3414. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  3415. NULL, NULL, NULL,
  3416. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  3417. NULL,
  3418. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  3419. cb(cur, "ffn_out", il);
  3420. }
  3421. cur = ggml_add(ctx0, cur, ffn_inp);
  3422. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3423. cb(cur, "l_out", il);
  3424. // input for next layer
  3425. inpL = cur;
  3426. }
  3427. cur = llm_build_norm(ctx0, inpL, hparams,
  3428. model.output_norm,
  3429. model.output_norm_b,
  3430. LLM_NORM, cb, -1);
  3431. cb(cur, "result_norm", -1);
  3432. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3433. cb(cur, "result_output", -1);
  3434. ggml_build_forward_expand(gf, cur);
  3435. return gf;
  3436. }
  3437. struct ggml_cgraph * build_orion() {
  3438. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3439. const int64_t n_embd_head = hparams.n_embd_head_v;
  3440. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3441. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3442. struct ggml_tensor * cur;
  3443. struct ggml_tensor * inpL;
  3444. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3445. // inp_pos - contains the positions
  3446. struct ggml_tensor * inp_pos = build_inp_pos();
  3447. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3448. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3449. for (int il = 0; il < n_layer; ++il) {
  3450. struct ggml_tensor * inpSA = inpL;
  3451. // norm
  3452. cur = llm_build_norm(ctx0, inpL, hparams,
  3453. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  3454. LLM_NORM, cb, il);
  3455. cb(cur, "attn_norm", il);
  3456. // self-attention
  3457. {
  3458. // compute Q and K and RoPE them
  3459. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  3460. cb(Qcur, "Qcur", il);
  3461. // if (model.layers[il].bq) {
  3462. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3463. // cb(Qcur, "Qcur", il);
  3464. // }
  3465. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  3466. cb(Kcur, "Kcur", il);
  3467. // if (model.layers[il].bk) {
  3468. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3469. // cb(Kcur, "Kcur", il);
  3470. // }
  3471. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  3472. cb(Vcur, "Vcur", il);
  3473. // if (model.layers[il].bv) {
  3474. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3475. // cb(Vcur, "Vcur", il);
  3476. // }
  3477. Qcur = ggml_rope_ext(
  3478. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  3479. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3480. ext_factor, attn_factor, beta_fast, beta_slow
  3481. );
  3482. cb(Qcur, "Qcur", il);
  3483. Kcur = ggml_rope_ext(
  3484. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  3485. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3486. ext_factor, attn_factor, beta_fast, beta_slow
  3487. );
  3488. cb(Kcur, "Kcur", il);
  3489. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3490. model.layers[il].wo, NULL,
  3491. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3492. }
  3493. if (il == n_layer - 1) {
  3494. // skip computing output for unused tokens
  3495. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3496. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3497. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  3498. }
  3499. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3500. cb(ffn_inp, "ffn_inp", il);
  3501. // feed-forward network
  3502. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3503. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  3504. LLM_NORM, cb, il);
  3505. cb(cur, "ffn_norm", il);
  3506. cur = llm_build_ffn(ctx0, lctx, cur,
  3507. model.layers[il].ffn_up, NULL, NULL,
  3508. model.layers[il].ffn_gate, NULL, NULL,
  3509. model.layers[il].ffn_down, NULL, NULL,
  3510. NULL,
  3511. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3512. cb(cur, "ffn_out", il);
  3513. cur = ggml_add(ctx0, cur, ffn_inp);
  3514. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3515. cb(cur, "l_out", il);
  3516. // input for next layer
  3517. inpL = cur;
  3518. }
  3519. cur = inpL;
  3520. cur = llm_build_norm(ctx0, cur, hparams,
  3521. model.output_norm, model.output_norm_b,
  3522. LLM_NORM, cb, -1);
  3523. cb(cur, "result_norm", -1);
  3524. // lm_head
  3525. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3526. cb(cur, "result_output", -1);
  3527. ggml_build_forward_expand(gf, cur);
  3528. return gf;
  3529. }
  3530. struct ggml_cgraph * build_internlm2() {
  3531. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3532. const int64_t n_embd_head = hparams.n_embd_head_v;
  3533. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3534. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3535. struct ggml_tensor * cur;
  3536. struct ggml_tensor * inpL;
  3537. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3538. // inp_pos - contains the positions
  3539. struct ggml_tensor * inp_pos = build_inp_pos();
  3540. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3541. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3542. for (int il = 0; il < n_layer; ++il) {
  3543. struct ggml_tensor * inpSA = inpL;
  3544. // norm
  3545. cur = llm_build_norm(ctx0, inpL, hparams,
  3546. model.layers[il].attn_norm, NULL,
  3547. LLM_NORM_RMS, cb, il);
  3548. cb(cur, "attn_norm", il);
  3549. // self-attention
  3550. {
  3551. // compute Q and K and RoPE them
  3552. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  3553. cb(Qcur, "Qcur", il);
  3554. if (model.layers[il].bq) {
  3555. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3556. cb(Qcur, "Qcur", il);
  3557. }
  3558. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  3559. cb(Kcur, "Kcur", il);
  3560. if (model.layers[il].bk) {
  3561. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3562. cb(Kcur, "Kcur", il);
  3563. }
  3564. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  3565. cb(Vcur, "Vcur", il);
  3566. if (model.layers[il].bv) {
  3567. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3568. cb(Vcur, "Vcur", il);
  3569. }
  3570. Qcur = ggml_rope_ext(
  3571. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  3572. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3573. ext_factor, attn_factor, beta_fast, beta_slow
  3574. );
  3575. cb(Qcur, "Qcur", il);
  3576. Kcur = ggml_rope_ext(
  3577. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  3578. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3579. ext_factor, attn_factor, beta_fast, beta_slow
  3580. );
  3581. cb(Kcur, "Kcur", il);
  3582. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3583. model.layers[il].wo, model.layers[il].bo,
  3584. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3585. }
  3586. if (il == n_layer - 1) {
  3587. // skip computing output for unused tokens
  3588. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3589. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3590. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  3591. }
  3592. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3593. cb(ffn_inp, "ffn_inp", il);
  3594. // feed-forward network
  3595. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3596. model.layers[il].ffn_norm, NULL,
  3597. LLM_NORM_RMS, cb, il);
  3598. cb(cur, "ffn_norm", il);
  3599. cur = llm_build_ffn(ctx0, lctx, cur,
  3600. model.layers[il].ffn_up, NULL, NULL,
  3601. model.layers[il].ffn_gate, NULL, NULL,
  3602. model.layers[il].ffn_down, NULL, NULL,
  3603. NULL,
  3604. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3605. cb(cur, "ffn_out", il);
  3606. cur = ggml_add(ctx0, cur, ffn_inp);
  3607. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3608. cb(cur, "l_out", il);
  3609. // input for next layer
  3610. inpL = cur;
  3611. }
  3612. cur = inpL;
  3613. cur = llm_build_norm(ctx0, cur, hparams,
  3614. model.output_norm, NULL,
  3615. LLM_NORM_RMS, cb, -1);
  3616. cb(cur, "result_norm", -1);
  3617. // lm_head
  3618. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3619. cb(cur, "result_output", -1);
  3620. ggml_build_forward_expand(gf, cur);
  3621. return gf;
  3622. }
  3623. struct ggml_cgraph * build_minicpm3() {
  3624. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3625. //TODO: if the model varies, these parameters need to be read from the model
  3626. const int64_t n_embd_base = 256;
  3627. const float scale_embd = 12.0f;
  3628. const float scale_depth = 1.4f;
  3629. const float kq_scale = 1.0f / sqrtf(float(hparams.n_embd_head_k));
  3630. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  3631. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  3632. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  3633. struct ggml_tensor * cur;
  3634. struct ggml_tensor * inpL;
  3635. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3636. // scale the input embeddings
  3637. inpL = ggml_scale(ctx0, inpL, scale_embd);
  3638. cb(inpL, "inp_scaled", -1);
  3639. // inp_pos - contains the positions
  3640. struct ggml_tensor * inp_pos = build_inp_pos();
  3641. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3642. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3643. for (int il = 0; il < n_layer; ++il) {
  3644. struct ggml_tensor * inpSA = inpL;
  3645. struct ggml_tensor * rope_factors = build_rope_factors(il);
  3646. // norm
  3647. cur = llm_build_norm(ctx0, inpL, hparams,
  3648. model.layers[il].attn_norm, NULL,
  3649. LLM_NORM_RMS, cb, il);
  3650. cb(cur, "attn_norm", il);
  3651. // self_attention
  3652. {
  3653. struct ggml_tensor * q = NULL;
  3654. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  3655. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  3656. cb(q, "q", il);
  3657. q = llm_build_norm(ctx0, q, hparams,
  3658. model.layers[il].attn_q_a_norm, NULL,
  3659. LLM_NORM_RMS, cb, il);
  3660. cb(q, "q", il);
  3661. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  3662. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  3663. cb(q, "q", il);
  3664. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  3665. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  3666. ggml_row_size(q->type, hparams.n_embd_head_k),
  3667. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  3668. 0);
  3669. cb(q_nope, "q_nope", il);
  3670. // and {n_head * n_embd_head_qk_rope, n_tokens}
  3671. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  3672. ggml_row_size(q->type, hparams.n_embd_head_k),
  3673. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  3674. ggml_row_size(q->type, n_embd_head_qk_nope));
  3675. cb(q_pe, "q_pe", il);
  3676. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  3677. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  3678. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  3679. // split into {kv_lora_rank, n_tokens}
  3680. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  3681. kv_pe_compresseed->nb[1],
  3682. 0);
  3683. cb(kv_compressed, "kv_compressed", il);
  3684. // and {n_embd_head_qk_rope, n_tokens}
  3685. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  3686. kv_pe_compresseed->nb[1],
  3687. kv_pe_compresseed->nb[1],
  3688. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  3689. cb(k_pe, "k_pe", il);
  3690. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  3691. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  3692. model.layers[il].attn_kv_a_norm, NULL,
  3693. LLM_NORM_RMS, cb, il);
  3694. cb(kv_compressed, "kv_compressed", il);
  3695. // {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)} * {kv_lora_rank, n_tokens} -> {n_head * (n_embd_head_qk_nope + n_embd_head_v), n_tokens}
  3696. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  3697. cb(kv, "kv", il);
  3698. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  3699. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  3700. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  3701. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  3702. 0);
  3703. cb(k_nope, "k_nope", il);
  3704. // and {n_head * n_embd_head_v, n_tokens}
  3705. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  3706. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  3707. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  3708. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  3709. cb(v_states, "v_states", il);
  3710. v_states = ggml_cont(ctx0, v_states);
  3711. cb(v_states, "v_states", il);
  3712. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  3713. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  3714. 0);
  3715. cb(v_states, "v_states", il);
  3716. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend used to not support non-cont. RoPE, investigate removing this
  3717. q_pe = ggml_rope_ext(
  3718. ctx0, q_pe, inp_pos, rope_factors,
  3719. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3720. ext_factor, attn_factor, beta_fast, beta_slow
  3721. );
  3722. cb(q_pe, "q_pe", il);
  3723. // shared RoPE key
  3724. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend used to not support non-cont. RoPE, investigate removing this
  3725. k_pe = ggml_rope_ext(
  3726. ctx0, k_pe, inp_pos, rope_factors,
  3727. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3728. ext_factor, attn_factor, beta_fast, beta_slow
  3729. );
  3730. cb(k_pe, "k_pe", il);
  3731. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  3732. cb(q_states, "q_states", il);
  3733. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  3734. cb(k_states, "k_states", il);
  3735. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3736. model.layers[il].wo, NULL,
  3737. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  3738. }
  3739. if (il == n_layer - 1) {
  3740. // skip computing output for unused tokens
  3741. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3742. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3743. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  3744. }
  3745. // scale_res - scale the hidden states for residual connection
  3746. const float scale_res = scale_depth/sqrtf(float(n_layer));
  3747. cur = ggml_scale(ctx0, cur, scale_res);
  3748. cb(cur, "hidden_scaled", il);
  3749. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3750. cb(ffn_inp, "ffn_inp", il);
  3751. // feed-forward network
  3752. {
  3753. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3754. model.layers[il].ffn_norm, NULL,
  3755. LLM_NORM_RMS, cb, il);
  3756. cb(cur, "ffn_norm", il);
  3757. cur = llm_build_ffn(ctx0, lctx, cur,
  3758. model.layers[il].ffn_up, NULL, NULL,
  3759. model.layers[il].ffn_gate, NULL, NULL,
  3760. model.layers[il].ffn_down, NULL, NULL,
  3761. NULL,
  3762. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3763. cb(cur, "ffn_out", il);
  3764. }
  3765. // scale the hidden states for residual connection
  3766. cur = ggml_scale(ctx0, cur, scale_res);
  3767. cb(cur, "hidden_scaled_ffn", il);
  3768. cur = ggml_add(ctx0, cur, ffn_inp);
  3769. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3770. cb(cur, "l_out", il);
  3771. // input for next layer
  3772. inpL = cur;
  3773. }
  3774. cur = inpL;
  3775. cur = llm_build_norm(ctx0, cur, hparams,
  3776. model.output_norm, NULL,
  3777. LLM_NORM_RMS, cb, -1);
  3778. cb(cur, "result_norm", -1);
  3779. // lm_head scaling
  3780. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  3781. cur = ggml_scale(ctx0, cur, scale_lmhead);
  3782. cb(cur, "lmhead_scaling", -1);
  3783. // lm_head
  3784. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3785. cb(cur, "result_output", -1);
  3786. ggml_build_forward_expand(gf, cur);
  3787. return gf;
  3788. }
  3789. struct ggml_cgraph * build_gemma() {
  3790. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3791. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3792. struct ggml_tensor * cur;
  3793. struct ggml_tensor * inpL;
  3794. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3795. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  3796. cb(inpL, "inp_scaled", -1);
  3797. // inp_pos - contains the positions
  3798. struct ggml_tensor * inp_pos = build_inp_pos();
  3799. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3800. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3801. for (int il = 0; il < n_layer; ++il) {
  3802. // norm
  3803. cur = llm_build_norm(ctx0, inpL, hparams,
  3804. model.layers[il].attn_norm, NULL,
  3805. LLM_NORM_RMS, cb, il);
  3806. cb(cur, "attn_norm", il);
  3807. // self-attention
  3808. {
  3809. // compute Q and K and RoPE them
  3810. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  3811. cb(Qcur, "Qcur", il);
  3812. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  3813. cb(Kcur, "Kcur", il);
  3814. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  3815. cb(Vcur, "Vcur", il);
  3816. Qcur = ggml_rope_ext(
  3817. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  3818. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3819. ext_factor, attn_factor, beta_fast, beta_slow);
  3820. cb(Qcur, "Qcur", il);
  3821. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  3822. cb(Qcur, "Qcur_scaled", il);
  3823. Kcur = ggml_rope_ext(
  3824. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  3825. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3826. ext_factor, attn_factor, beta_fast, beta_slow);
  3827. cb(Kcur, "Kcur", il);
  3828. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3829. model.layers[il].wo, NULL,
  3830. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  3831. }
  3832. if (il == n_layer - 1) {
  3833. // skip computing output for unused tokens
  3834. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3835. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3836. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  3837. }
  3838. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  3839. cb(sa_out, "sa_out", il);
  3840. cur = llm_build_norm(ctx0, sa_out, hparams,
  3841. model.layers[il].ffn_norm, NULL,
  3842. LLM_NORM_RMS, cb, il);
  3843. cb(cur, "ffn_norm", il);
  3844. // feed-forward network
  3845. {
  3846. cur = llm_build_ffn(ctx0, lctx, cur,
  3847. model.layers[il].ffn_up, NULL, NULL,
  3848. model.layers[il].ffn_gate, NULL, NULL,
  3849. model.layers[il].ffn_down, NULL, NULL,
  3850. NULL,
  3851. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  3852. cb(cur, "ffn_out", il);
  3853. }
  3854. cur = ggml_add(ctx0, cur, sa_out);
  3855. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3856. cb(cur, "l_out", il);
  3857. // input for next layer
  3858. inpL = cur;
  3859. }
  3860. cur = inpL;
  3861. cur = llm_build_norm(ctx0, cur, hparams,
  3862. model.output_norm, NULL,
  3863. LLM_NORM_RMS, cb, -1);
  3864. cb(cur, "result_norm", -1);
  3865. // lm_head
  3866. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3867. cb(cur, "result_output", -1);
  3868. ggml_build_forward_expand(gf, cur);
  3869. return gf;
  3870. }
  3871. struct ggml_cgraph * build_gemma2() {
  3872. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3873. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3874. struct ggml_tensor * cur;
  3875. struct ggml_tensor * inpL;
  3876. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3877. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  3878. cb(inpL, "inp_scaled", -1);
  3879. // inp_pos - contains the positions
  3880. struct ggml_tensor * inp_pos = build_inp_pos();
  3881. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3882. // gemma 2 requires different mask for layers using sliding window (SWA)
  3883. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  3884. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  3885. for (int il = 0; il < n_layer; ++il) {
  3886. // (il % 2) layers use SWA
  3887. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  3888. // norm
  3889. cur = llm_build_norm(ctx0, inpL, hparams,
  3890. model.layers[il].attn_norm, NULL,
  3891. LLM_NORM_RMS, cb, il);
  3892. cb(cur, "attn_norm", il);
  3893. // self-attention
  3894. {
  3895. // compute Q and K and RoPE them
  3896. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  3897. cb(Qcur, "Qcur", il);
  3898. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  3899. cb(Kcur, "Kcur", il);
  3900. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  3901. cb(Vcur, "Vcur", il);
  3902. Qcur = ggml_rope_ext(
  3903. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  3904. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3905. ext_factor, attn_factor, beta_fast, beta_slow);
  3906. cb(Qcur, "Qcur", il);
  3907. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  3908. switch (model.type) {
  3909. case LLM_TYPE_2B:
  3910. case LLM_TYPE_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  3911. case LLM_TYPE_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  3912. default: GGML_ABORT("fatal error");
  3913. };
  3914. cb(Qcur, "Qcur_scaled", il);
  3915. Kcur = ggml_rope_ext(
  3916. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  3917. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  3918. ext_factor, attn_factor, beta_fast, beta_slow);
  3919. cb(Kcur, "Kcur", il);
  3920. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  3921. model.layers[il].wo, NULL,
  3922. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  3923. }
  3924. cur = llm_build_norm(ctx0, cur, hparams,
  3925. model.layers[il].attn_post_norm, NULL,
  3926. LLM_NORM_RMS, cb, il);
  3927. cb(cur, "attn_post_norm", il);
  3928. if (il == n_layer - 1) {
  3929. // skip computing output for unused tokens
  3930. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  3931. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  3932. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  3933. }
  3934. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  3935. cb(sa_out, "sa_out", il);
  3936. cur = llm_build_norm(ctx0, sa_out, hparams,
  3937. model.layers[il].ffn_norm, NULL,
  3938. LLM_NORM_RMS, cb, il);
  3939. cb(cur, "ffn_norm", il);
  3940. // feed-forward network
  3941. {
  3942. cur = llm_build_ffn(ctx0, lctx, cur,
  3943. model.layers[il].ffn_up, NULL, NULL,
  3944. model.layers[il].ffn_gate, NULL, NULL,
  3945. model.layers[il].ffn_down, NULL, NULL,
  3946. NULL,
  3947. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  3948. cb(cur, "ffn_out", il);
  3949. }
  3950. cur = llm_build_norm(ctx0, cur, hparams,
  3951. model.layers[il].ffn_post_norm, NULL,
  3952. LLM_NORM_RMS, cb, -1);
  3953. cb(cur, "ffn_post_norm", -1);
  3954. cur = ggml_add(ctx0, cur, sa_out);
  3955. cur = lctx.cvec.apply_to(ctx0, cur, il);
  3956. cb(cur, "l_out", il);
  3957. // input for next layer
  3958. inpL = cur;
  3959. }
  3960. cur = inpL;
  3961. cur = llm_build_norm(ctx0, cur, hparams,
  3962. model.output_norm, NULL,
  3963. LLM_NORM_RMS, cb, -1);
  3964. cb(cur, "result_norm", -1);
  3965. // lm_head
  3966. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  3967. // final logit soft-capping
  3968. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  3969. cur = ggml_tanh(ctx0, cur);
  3970. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  3971. cb(cur, "result_output", -1);
  3972. ggml_build_forward_expand(gf, cur);
  3973. return gf;
  3974. }
  3975. struct ggml_cgraph * build_starcoder2() {
  3976. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  3977. const int64_t n_embd_head = hparams.n_embd_head_v;
  3978. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3979. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3980. struct ggml_tensor * cur;
  3981. struct ggml_tensor * inpL;
  3982. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  3983. // inp_pos - contains the positions
  3984. struct ggml_tensor * inp_pos = build_inp_pos();
  3985. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3986. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  3987. for (int il = 0; il < n_layer; ++il) {
  3988. struct ggml_tensor * inpSA = inpL;
  3989. // norm
  3990. cur = llm_build_norm(ctx0, inpL, hparams,
  3991. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  3992. LLM_NORM, cb, il);
  3993. cb(cur, "attn_norm", il);
  3994. // self-attention
  3995. {
  3996. // compute Q and K and RoPE them
  3997. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  3998. cb(Qcur, "Qcur", il);
  3999. if (model.layers[il].bq) {
  4000. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4001. cb(Qcur, "Qcur", il);
  4002. }
  4003. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4004. cb(Kcur, "Kcur", il);
  4005. if (model.layers[il].bk) {
  4006. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4007. cb(Kcur, "Kcur", il);
  4008. }
  4009. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4010. cb(Vcur, "Vcur", il);
  4011. if (model.layers[il].bv) {
  4012. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4013. cb(Vcur, "Vcur", il);
  4014. }
  4015. Qcur = ggml_rope_ext(
  4016. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  4017. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4018. ext_factor, attn_factor, beta_fast, beta_slow
  4019. );
  4020. cb(Qcur, "Qcur", il);
  4021. Kcur = ggml_rope_ext(
  4022. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  4023. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4024. ext_factor, attn_factor, beta_fast, beta_slow
  4025. );
  4026. cb(Kcur, "Kcur", il);
  4027. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4028. model.layers[il].wo, model.layers[il].bo,
  4029. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4030. }
  4031. if (il == n_layer - 1) {
  4032. // skip computing output for unused tokens
  4033. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4034. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4035. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  4036. }
  4037. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4038. cb(ffn_inp, "ffn_inp", il);
  4039. // feed-forward network
  4040. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4041. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  4042. LLM_NORM, cb, il);
  4043. cb(cur, "ffn_norm", il);
  4044. cur = llm_build_ffn(ctx0, lctx, cur,
  4045. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  4046. NULL, NULL, NULL,
  4047. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  4048. NULL,
  4049. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4050. cb(cur, "ffn_out", il);
  4051. cur = ggml_add(ctx0, cur, ffn_inp);
  4052. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4053. cb(cur, "l_out", il);
  4054. // input for next layer
  4055. inpL = cur;
  4056. }
  4057. cur = inpL;
  4058. cur = llm_build_norm(ctx0, cur, hparams,
  4059. model.output_norm, model.output_norm_b,
  4060. LLM_NORM, cb, -1);
  4061. cb(cur, "result_norm", -1);
  4062. // lm_head
  4063. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4064. cb(cur, "result_output", -1);
  4065. ggml_build_forward_expand(gf, cur);
  4066. return gf;
  4067. }
  4068. struct ggml_cgraph * build_mamba() {
  4069. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4070. struct ggml_tensor * cur;
  4071. struct ggml_tensor * inpL;
  4072. // {n_embd, n_tokens}
  4073. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4074. struct ggml_tensor * state_copy = build_inp_s_copy();
  4075. struct ggml_tensor * state_mask = build_inp_s_mask();
  4076. for (int il = 0; il < n_layer; ++il) {
  4077. // norm
  4078. cur = llm_build_norm(ctx0, inpL, hparams,
  4079. model.layers[il].attn_norm, NULL,
  4080. LLM_NORM_RMS, cb, il);
  4081. cb(cur, "attn_norm", il);
  4082. cur = llm_build_mamba(ctx0, lctx, ubatch, gf, cur,
  4083. state_copy, state_mask,
  4084. kv_head, n_kv, cb, il);
  4085. if (il == n_layer - 1) {
  4086. // skip computing output for unused tokens
  4087. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4088. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4089. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  4090. }
  4091. // residual
  4092. cur = ggml_add(ctx0, cur, inpL);
  4093. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4094. cb(cur, "l_out", il);
  4095. // input for next layer
  4096. inpL = cur;
  4097. }
  4098. // final rmsnorm
  4099. cur = llm_build_norm(ctx0, inpL, hparams,
  4100. model.output_norm, NULL,
  4101. LLM_NORM_RMS, cb, -1);
  4102. cb(cur, "result_norm", -1);
  4103. // lm_head
  4104. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4105. cb(cur, "result_output", -1);
  4106. ggml_build_forward_expand(gf, cur);
  4107. return gf;
  4108. }
  4109. struct ggml_cgraph * build_command_r() {
  4110. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4111. const int64_t n_embd_head = hparams.n_embd_head_v;
  4112. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4113. const float f_logit_scale = hparams.f_logit_scale;
  4114. struct ggml_tensor * cur;
  4115. struct ggml_tensor * inpL;
  4116. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4117. // inp_pos - contains the positions
  4118. struct ggml_tensor * inp_pos = build_inp_pos();
  4119. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4120. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4121. for (int il = 0; il < n_layer; ++il) {
  4122. // norm
  4123. cur = llm_build_norm(ctx0, inpL, hparams,
  4124. model.layers[il].attn_norm, NULL,
  4125. LLM_NORM, cb, il);
  4126. cb(cur, "attn_norm", il);
  4127. struct ggml_tensor * ffn_inp = cur;
  4128. // self-attention
  4129. {
  4130. // compute Q and K and RoPE them
  4131. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  4132. cb(Qcur, "Qcur", il);
  4133. if (model.layers[il].bq) {
  4134. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4135. cb(Qcur, "Qcur", il);
  4136. }
  4137. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4138. cb(Kcur, "Kcur", il);
  4139. if (model.layers[il].bk) {
  4140. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4141. cb(Kcur, "Kcur", il);
  4142. }
  4143. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4144. cb(Vcur, "Vcur", il);
  4145. if (model.layers[il].bv) {
  4146. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4147. cb(Vcur, "Vcur", il);
  4148. }
  4149. if (model.layers[il].attn_q_norm) {
  4150. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  4151. ggml_element_size(Qcur) * n_embd_head,
  4152. ggml_element_size(Qcur) * n_embd_head * n_head,
  4153. 0);
  4154. cb(Qcur, "Qcur", il);
  4155. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  4156. ggml_element_size(Kcur) * n_embd_head,
  4157. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  4158. 0);
  4159. cb(Kcur, "Kcur", il);
  4160. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  4161. model.layers[il].attn_q_norm,
  4162. NULL,
  4163. LLM_NORM, cb, il);
  4164. cb(Qcur, "Qcur", il);
  4165. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  4166. model.layers[il].attn_k_norm,
  4167. NULL,
  4168. LLM_NORM, cb, il);
  4169. cb(Kcur, "Kcur", il);
  4170. }
  4171. Qcur = ggml_rope_ext(
  4172. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  4173. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4174. ext_factor, attn_factor, beta_fast, beta_slow
  4175. );
  4176. cb(Qcur, "Qcur", il);
  4177. Kcur = ggml_rope_ext(
  4178. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  4179. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4180. ext_factor, attn_factor, beta_fast, beta_slow
  4181. );
  4182. cb(Kcur, "Kcur", il);
  4183. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4184. model.layers[il].wo, model.layers[il].bo,
  4185. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4186. }
  4187. if (il == n_layer - 1) {
  4188. // skip computing output for unused tokens
  4189. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4190. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4191. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  4192. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  4193. }
  4194. struct ggml_tensor * attn_out = cur;
  4195. // feed-forward network
  4196. {
  4197. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  4198. model.layers[il].ffn_up, NULL, NULL,
  4199. model.layers[il].ffn_gate, NULL, NULL,
  4200. model.layers[il].ffn_down, NULL, NULL,
  4201. NULL,
  4202. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4203. cb(cur, "ffn_out", il);
  4204. }
  4205. // add together residual + FFN + self-attention
  4206. cur = ggml_add(ctx0, cur, inpL);
  4207. cur = ggml_add(ctx0, cur, attn_out);
  4208. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4209. cb(cur, "l_out", il);
  4210. // input for next layer
  4211. inpL = cur;
  4212. }
  4213. cur = inpL;
  4214. cur = llm_build_norm(ctx0, cur, hparams,
  4215. model.output_norm, NULL,
  4216. LLM_NORM, cb, -1);
  4217. cb(cur, "result_norm", -1);
  4218. // lm_head
  4219. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4220. if (f_logit_scale) {
  4221. cur = ggml_scale(ctx0, cur, f_logit_scale);
  4222. }
  4223. cb(cur, "result_output", -1);
  4224. ggml_build_forward_expand(gf, cur);
  4225. return gf;
  4226. }
  4227. struct ggml_cgraph * build_cohere2() {
  4228. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4229. const int64_t n_embd_head = hparams.n_embd_head_v;
  4230. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4231. const float f_logit_scale = hparams.f_logit_scale;
  4232. struct ggml_tensor * cur;
  4233. struct ggml_tensor * inpL;
  4234. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4235. // inp_pos - contains the positions
  4236. struct ggml_tensor * inp_pos = build_inp_pos();
  4237. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4238. // cohere2 requires different mask for layers using sliding window (SWA)
  4239. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4240. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  4241. // sliding window switch pattern
  4242. const int32_t sliding_window_pattern = 4;
  4243. for (int il = 0; il < n_layer; ++il) {
  4244. // three layers sliding window attention (window size 4096) and ROPE
  4245. // fourth layer uses global attention without positional embeddings
  4246. const bool is_sliding = il % sliding_window_pattern < (sliding_window_pattern - 1);
  4247. struct ggml_tensor * KQ_mask_l = is_sliding ? KQ_mask_swa : KQ_mask;
  4248. // norm
  4249. cur = llm_build_norm(ctx0, inpL, hparams, model.layers[il].attn_norm, NULL, LLM_NORM, cb, il);
  4250. cb(cur, "attn_norm", il);
  4251. struct ggml_tensor * ffn_inp = cur;
  4252. // self-attention
  4253. {
  4254. // rope freq factors for 128k context
  4255. struct ggml_tensor * rope_factors = build_rope_factors(il);
  4256. // compute Q and K and RoPE them
  4257. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  4258. cb(Qcur, "Qcur", il);
  4259. if (model.layers[il].bq) {
  4260. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4261. cb(Qcur, "Qcur", il);
  4262. }
  4263. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4264. cb(Kcur, "Kcur", il);
  4265. if (model.layers[il].bk) {
  4266. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4267. cb(Kcur, "Kcur", il);
  4268. }
  4269. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4270. cb(Vcur, "Vcur", il);
  4271. if (model.layers[il].bv) {
  4272. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4273. cb(Vcur, "Vcur", il);
  4274. }
  4275. if (is_sliding) {
  4276. Qcur = ggml_rope_ext(ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  4277. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor,
  4278. beta_fast, beta_slow);
  4279. cb(Qcur, "Qcur", il);
  4280. Kcur = ggml_rope_ext(ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4281. rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale, ext_factor,
  4282. attn_factor, beta_fast, beta_slow);
  4283. cb(Kcur, "Kcur", il);
  4284. } else {
  4285. // For non-sliding layers, just reshape without applying RoPE
  4286. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4287. cb(Qcur, "Qcur", il);
  4288. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4289. cb(Kcur, "Kcur", il);
  4290. }
  4291. cur = llm_build_kv(ctx0, lctx, kv_self, gf, model.layers[il].wo, model.layers[il].bo, Kcur, Vcur, Qcur,
  4292. KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f / sqrtf(float(n_embd_head)), cb, il);
  4293. }
  4294. if (il == n_layer - 1) {
  4295. // skip computing output for unused tokens
  4296. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4297. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4298. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  4299. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  4300. }
  4301. struct ggml_tensor * attn_out = cur;
  4302. // feed-forward network
  4303. {
  4304. cur = llm_build_ffn(ctx0, lctx, ffn_inp, model.layers[il].ffn_up, NULL, NULL, model.layers[il].ffn_gate,
  4305. NULL, NULL, model.layers[il].ffn_down, NULL, NULL, NULL, LLM_FFN_SILU, LLM_FFN_PAR,
  4306. cb, il);
  4307. cb(cur, "ffn_out", il);
  4308. }
  4309. // add together residual + FFN + self-attention
  4310. cur = ggml_add(ctx0, cur, inpL);
  4311. cur = ggml_add(ctx0, cur, attn_out);
  4312. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4313. cb(cur, "l_out", il);
  4314. // input for next layer
  4315. inpL = cur;
  4316. }
  4317. cur = inpL;
  4318. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM, cb, -1);
  4319. cb(cur, "result_norm", -1);
  4320. // lm_head
  4321. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4322. if (f_logit_scale) {
  4323. cur = ggml_scale(ctx0, cur, f_logit_scale);
  4324. }
  4325. cb(cur, "result_output", -1);
  4326. ggml_build_forward_expand(gf, cur);
  4327. return gf;
  4328. }
  4329. // ref: https://allenai.org/olmo
  4330. // based on the original build_llama() function, changes:
  4331. // * non-parametric layer norm
  4332. // * clamp qkv
  4333. // * removed bias
  4334. // * removed MoE
  4335. struct ggml_cgraph * build_olmo() {
  4336. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4337. // mutable variable, needed during the last layer of the computation to skip unused tokens
  4338. int32_t n_tokens = this->n_tokens;
  4339. const int64_t n_embd_head = hparams.n_embd_head_v;
  4340. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4341. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4342. struct ggml_tensor * cur;
  4343. struct ggml_tensor * inpL;
  4344. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4345. // inp_pos - contains the positions
  4346. struct ggml_tensor * inp_pos = build_inp_pos();
  4347. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4348. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4349. for (int il = 0; il < n_layer; ++il) {
  4350. struct ggml_tensor * inpSA = inpL;
  4351. // norm
  4352. cur = llm_build_norm(ctx0, inpL, hparams,
  4353. NULL, NULL,
  4354. LLM_NORM, cb, il);
  4355. cb(cur, "attn_norm", il);
  4356. // self-attention
  4357. {
  4358. // compute Q and K and RoPE them
  4359. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  4360. cb(Qcur, "Qcur", il);
  4361. if (hparams.f_clamp_kqv > 0.0f) {
  4362. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4363. cb(Qcur, "Qcur", il);
  4364. }
  4365. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4366. cb(Kcur, "Kcur", il);
  4367. if (hparams.f_clamp_kqv > 0.0f) {
  4368. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4369. cb(Kcur, "Kcur", il);
  4370. }
  4371. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4372. cb(Vcur, "Vcur", il);
  4373. if (hparams.f_clamp_kqv > 0.0f) {
  4374. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4375. cb(Vcur, "Vcur", il);
  4376. }
  4377. Qcur = ggml_rope_ext(
  4378. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  4379. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4380. ext_factor, attn_factor, beta_fast, beta_slow
  4381. );
  4382. cb(Qcur, "Qcur", il);
  4383. Kcur = ggml_rope_ext(
  4384. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  4385. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4386. ext_factor, attn_factor, beta_fast, beta_slow
  4387. );
  4388. cb(Kcur, "Kcur", il);
  4389. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4390. model.layers[il].wo, nullptr,
  4391. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4392. }
  4393. if (il == n_layer - 1) {
  4394. // skip computing output for unused tokens
  4395. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4396. n_tokens = n_outputs;
  4397. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4398. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  4399. }
  4400. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4401. cb(ffn_inp, "ffn_inp", il);
  4402. // feed-forward network
  4403. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4404. NULL, NULL,
  4405. LLM_NORM, cb, il);
  4406. cb(cur, "ffn_norm", il);
  4407. cur = llm_build_ffn(ctx0, lctx, cur,
  4408. model.layers[il].ffn_up, NULL, NULL,
  4409. model.layers[il].ffn_gate, NULL, NULL,
  4410. model.layers[il].ffn_down, NULL, NULL,
  4411. NULL,
  4412. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4413. cb(cur, "ffn_out", il);
  4414. cur = ggml_add(ctx0, cur, ffn_inp);
  4415. cb(cur, "ffn_out", il);
  4416. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4417. cb(cur, "l_out", il);
  4418. // input for next layer
  4419. inpL = cur;
  4420. }
  4421. cur = inpL;
  4422. cur = llm_build_norm(ctx0, cur, hparams,
  4423. NULL, NULL,
  4424. LLM_NORM, cb, -1);
  4425. cb(cur, "result_norm", -1);
  4426. // lm_head
  4427. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4428. cb(cur, "result_output", -1);
  4429. ggml_build_forward_expand(gf, cur);
  4430. return gf;
  4431. }
  4432. struct ggml_cgraph * build_olmo2() {
  4433. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4434. // mutable variable, needed during the last layer of the computation to skip unused tokens
  4435. int32_t n_tokens = this->n_tokens;
  4436. const int64_t n_embd_head = hparams.n_embd_head_v;
  4437. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4438. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4439. struct ggml_tensor * cur;
  4440. struct ggml_tensor * inpL;
  4441. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4442. // inp_pos - contains the positions
  4443. struct ggml_tensor * inp_pos = build_inp_pos();
  4444. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4445. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4446. for (int il = 0; il < n_layer; ++il) {
  4447. struct ggml_tensor * inpSA = inpL;
  4448. cur = inpL;
  4449. // self_attention
  4450. {
  4451. // compute Q and K and RoPE them
  4452. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  4453. cb(Qcur, "Qcur", il);
  4454. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4455. cb(Kcur, "Kcur", il);
  4456. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4457. cb(Vcur, "Vcur", il);
  4458. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  4459. LLM_NORM_RMS, cb, il);
  4460. cb(Qcur, "Qcur_normed", il);
  4461. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  4462. LLM_NORM_RMS, cb, il);
  4463. cb(Kcur, "Kcur_normed", il);
  4464. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4465. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4466. Qcur = ggml_rope_ext(
  4467. ctx0, Qcur, inp_pos, nullptr,
  4468. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4469. ext_factor, attn_factor, beta_fast, beta_slow
  4470. );
  4471. cb(Qcur, "Qcur_rope", il);
  4472. Kcur = ggml_rope_ext(
  4473. ctx0, Kcur, inp_pos, nullptr,
  4474. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4475. ext_factor, attn_factor, beta_fast, beta_slow
  4476. );
  4477. cb(Kcur, "Kcur_rope", il);
  4478. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4479. model.layers[il].wo, NULL,
  4480. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4481. }
  4482. cur = llm_build_norm(ctx0, cur, hparams,
  4483. model.layers[il].attn_post_norm, NULL,
  4484. LLM_NORM_RMS, cb, il);
  4485. cb(cur, "attn_post_norm", il);
  4486. if (il == n_layer - 1) {
  4487. // skip computing output for unused tokens
  4488. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4489. n_tokens = n_outputs;
  4490. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4491. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  4492. }
  4493. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4494. cb(ffn_inp, "ffn_inp", il);
  4495. // feed-forward network
  4496. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  4497. model.layers[il].ffn_up, NULL, NULL,
  4498. model.layers[il].ffn_gate, NULL, NULL,
  4499. model.layers[il].ffn_down, NULL, NULL,
  4500. NULL,
  4501. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4502. cb(cur, "ffn_out", il);
  4503. cur = llm_build_norm(ctx0, cur, hparams,
  4504. model.layers[il].ffn_post_norm, NULL,
  4505. LLM_NORM_RMS, cb, -1);
  4506. cb(cur, "ffn_post_norm", -1);
  4507. cur = ggml_add(ctx0, cur, ffn_inp);
  4508. cb(cur, "ffn_out", il);
  4509. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4510. cb(cur, "l_out", il);
  4511. // input for next layer
  4512. inpL = cur;
  4513. }
  4514. cur = inpL;
  4515. cur = llm_build_norm(ctx0, cur, hparams,
  4516. model.output_norm, NULL,
  4517. LLM_NORM_RMS, cb, -1);
  4518. cb(cur, "result_norm", -1);
  4519. // lm_head
  4520. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4521. cb(cur, "result_output", -1);
  4522. ggml_build_forward_expand(gf, cur);
  4523. return gf;
  4524. }
  4525. // based on the build_qwen2moe() function, changes:
  4526. // * removed shared experts
  4527. // * removed bias
  4528. // * added q, k norm
  4529. struct ggml_cgraph * build_olmoe() {
  4530. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4531. // mutable variable, needed during the last layer of the computation to skip unused tokens
  4532. int32_t n_tokens = this->n_tokens;
  4533. const int64_t n_embd_head = hparams.n_embd_head_v;
  4534. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4535. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4536. struct ggml_tensor * cur;
  4537. struct ggml_tensor * inpL;
  4538. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4539. // inp_pos - contains the positions
  4540. struct ggml_tensor * inp_pos = build_inp_pos();
  4541. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4542. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4543. for (int il = 0; il < n_layer; ++il) {
  4544. struct ggml_tensor * inpSA = inpL;
  4545. // norm
  4546. cur = llm_build_norm(ctx0, inpL, hparams,
  4547. model.layers[il].attn_norm, NULL,
  4548. LLM_NORM_RMS, cb, il);
  4549. cb(cur, "attn_norm", il);
  4550. // self_attention
  4551. {
  4552. // compute Q and K and RoPE them
  4553. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  4554. cb(Qcur, "Qcur", il);
  4555. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4556. cb(Kcur, "Kcur", il);
  4557. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4558. cb(Vcur, "Vcur", il);
  4559. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  4560. LLM_NORM_RMS, cb, il);
  4561. cb(Qcur, "Qcur_normed", il);
  4562. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  4563. LLM_NORM_RMS, cb, il);
  4564. cb(Kcur, "Kcur_normed", il);
  4565. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4566. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4567. Qcur = ggml_rope_ext(
  4568. ctx0, Qcur, inp_pos, nullptr,
  4569. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4570. ext_factor, attn_factor, beta_fast, beta_slow
  4571. );
  4572. cb(Qcur, "Qcur_rope", il);
  4573. Kcur = ggml_rope_ext(
  4574. ctx0, Kcur, inp_pos, nullptr,
  4575. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4576. ext_factor, attn_factor, beta_fast, beta_slow
  4577. );
  4578. cb(Kcur, "Kcur_rope", il);
  4579. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4580. model.layers[il].wo, NULL,
  4581. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4582. }
  4583. if (il == n_layer - 1) {
  4584. // skip computing output for unused tokens
  4585. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4586. n_tokens = n_outputs;
  4587. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4588. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  4589. }
  4590. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4591. cb(ffn_inp, "ffn_inp", il);
  4592. // MoE branch
  4593. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4594. model.layers[il].ffn_norm, NULL,
  4595. LLM_NORM_RMS, cb, il);
  4596. cb(cur, "ffn_norm", il);
  4597. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  4598. model.layers[il].ffn_gate_inp,
  4599. model.layers[il].ffn_up_exps,
  4600. model.layers[il].ffn_gate_exps,
  4601. model.layers[il].ffn_down_exps,
  4602. nullptr,
  4603. n_expert, n_expert_used,
  4604. LLM_FFN_SILU, false,
  4605. false, 0.0,
  4606. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  4607. cb, il);
  4608. cb(cur, "ffn_moe_out", il);
  4609. cur = ggml_add(ctx0, cur, ffn_inp);
  4610. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4611. cb(cur, "l_out", il);
  4612. // input for next layer
  4613. inpL = cur;
  4614. }
  4615. cur = inpL;
  4616. cur = llm_build_norm(ctx0, cur, hparams,
  4617. model.output_norm, NULL,
  4618. LLM_NORM_RMS, cb, -1);
  4619. cb(cur, "result_norm", -1);
  4620. // lm_head
  4621. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4622. cb(cur, "result_output", -1);
  4623. ggml_build_forward_expand(gf, cur);
  4624. return gf;
  4625. }
  4626. struct ggml_cgraph * build_openelm() {
  4627. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4628. const int64_t n_embd_head = hparams.n_embd_head_v;
  4629. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4630. struct ggml_tensor * cur;
  4631. struct ggml_tensor * inpL;
  4632. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4633. // inp_pos - contains the positions
  4634. struct ggml_tensor * inp_pos = build_inp_pos();
  4635. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4636. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4637. for (int il = 0; il < n_layer; ++il) {
  4638. const int64_t n_head = hparams.n_head(il);
  4639. const int64_t n_head_kv = hparams.n_head_kv(il);
  4640. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  4641. cur = inpL;
  4642. struct ggml_tensor * residual = cur;
  4643. // norm
  4644. cur = llm_build_norm(ctx0, inpL, hparams,
  4645. model.layers[il].attn_norm, NULL,
  4646. LLM_NORM_RMS, cb, il);
  4647. cb(cur, "attn_norm", il);
  4648. // self-attention
  4649. {
  4650. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  4651. cb(cur, "wqkv", il);
  4652. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  4653. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd_head, n_head, n_tokens, cur->nb[1], cur->nb[2], 0));
  4654. cb(Qcur, "Qcur", il);
  4655. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd_head, n_head_kv, n_tokens, cur->nb[1], cur->nb[2], cur->nb[1]*n_head));
  4656. cb(Kcur, "Kcur", il);
  4657. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd_head, n_head_kv, n_tokens, cur->nb[1], cur->nb[2], cur->nb[1]*(n_head+n_head_kv)));
  4658. cb(Vcur, "Vcur", il);
  4659. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  4660. model.layers[il].attn_q_norm, NULL,
  4661. LLM_NORM_RMS, cb, il);
  4662. cb(Qcur, "Qcur", il);
  4663. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  4664. model.layers[il].attn_k_norm, NULL,
  4665. LLM_NORM_RMS, cb, il);
  4666. cb(Kcur, "Kcur", il);
  4667. Qcur = ggml_rope_ext(
  4668. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  4669. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4670. );
  4671. cb(Qcur, "Qcur", il);
  4672. Kcur = ggml_rope_ext(
  4673. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  4674. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4675. );
  4676. cb(Kcur, "Kcur", il);
  4677. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  4678. cb(Qcur, "Vcur", il);
  4679. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4680. model.layers[il].wo, NULL,
  4681. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4682. }
  4683. if (il == n_layer - 1) {
  4684. // skip computing output for unused tokens
  4685. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4686. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  4687. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4688. }
  4689. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4690. cb(ffn_inp, "ffn_inp", il);
  4691. // feed-forward network
  4692. {
  4693. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4694. model.layers[il].ffn_norm, NULL,
  4695. LLM_NORM_RMS, cb, il);
  4696. cb(cur, "ffn_norm", il);
  4697. cur = llm_build_ffn(ctx0, lctx, cur,
  4698. model.layers[il].ffn_up, NULL, NULL,
  4699. model.layers[il].ffn_gate, NULL, NULL,
  4700. model.layers[il].ffn_down, NULL, NULL,
  4701. NULL,
  4702. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4703. cb(cur, "ffn_out", il);
  4704. }
  4705. cur = ggml_add(ctx0, cur, ffn_inp);
  4706. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4707. cb(cur, "l_out", il);
  4708. inpL = cur;
  4709. }
  4710. cur = inpL;
  4711. // norm
  4712. cur = llm_build_norm(ctx0, cur, hparams,
  4713. model.output_norm, NULL,
  4714. LLM_NORM_RMS, cb, -1);
  4715. cb(cur, "result_norm", -1);
  4716. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4717. cb(cur, "result_output", -1);
  4718. ggml_build_forward_expand(gf, cur);
  4719. return gf;
  4720. }
  4721. struct ggml_cgraph * build_gptneox() {
  4722. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4723. const int64_t n_embd_head = hparams.n_embd_head_v;
  4724. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4725. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4726. struct ggml_tensor * cur;
  4727. struct ggml_tensor * inpL;
  4728. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4729. // inp_pos - contains the positions
  4730. struct ggml_tensor * inp_pos = build_inp_pos();
  4731. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4732. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4733. for (int il = 0; il < n_layer; ++il) {
  4734. cur = llm_build_norm(ctx0, inpL, hparams,
  4735. model.layers[il].attn_norm,
  4736. model.layers[il].attn_norm_b,
  4737. LLM_NORM, cb, il);
  4738. cb(cur, "attn_norm", il);
  4739. // self-attention
  4740. {
  4741. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  4742. cb(cur, "wqkv", il);
  4743. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4744. cb(cur, "bqkv", il);
  4745. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4746. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4747. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  4748. cb(Qcur, "Qcur", il);
  4749. cb(Kcur, "Kcur", il);
  4750. cb(Vcur, "Vcur", il);
  4751. Qcur = ggml_rope_ext(
  4752. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  4753. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4754. ext_factor, attn_factor, beta_fast, beta_slow
  4755. );
  4756. cb(Qcur, "Qcur", il);
  4757. Kcur = ggml_rope_ext(
  4758. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  4759. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4760. ext_factor, attn_factor, beta_fast, beta_slow
  4761. );
  4762. cb(Kcur, "Kcur", il);
  4763. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4764. model.layers[il].wo, model.layers[il].bo,
  4765. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4766. }
  4767. if (il == n_layer - 1) {
  4768. // skip computing output for unused tokens
  4769. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4770. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4771. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  4772. }
  4773. // ffn
  4774. if (hparams.use_par_res) {
  4775. // attention and ffn are computed in parallel
  4776. // x = x + attn(ln1(x)) + ffn(ln2(x))
  4777. struct ggml_tensor * attn_out = cur;
  4778. cur = llm_build_norm(ctx0, inpL, hparams,
  4779. model.layers[il].ffn_norm,
  4780. model.layers[il].ffn_norm_b,
  4781. LLM_NORM, cb, il);
  4782. cb(cur, "ffn_norm", il);
  4783. cur = llm_build_ffn(ctx0, lctx, cur,
  4784. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  4785. NULL, NULL, NULL,
  4786. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  4787. NULL,
  4788. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4789. cb(cur, "ffn_out", il);
  4790. cur = ggml_add(ctx0, cur, inpL);
  4791. cb(cur, "ffn_out", il);
  4792. cur = ggml_add(ctx0, cur, attn_out);
  4793. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4794. cb(cur, "l_out", il);
  4795. // input for next layer
  4796. inpL = cur;
  4797. } else {
  4798. // attention and ffn are computed sequentially
  4799. // x = x + attn(ln1(x))
  4800. // x = x + ffn(ln2(x))
  4801. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4802. cb(ffn_inp, "ffn_inp", il);
  4803. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4804. model.layers[il].ffn_norm,
  4805. model.layers[il].ffn_norm_b,
  4806. LLM_NORM, cb, il);
  4807. cb(cur, "ffn_norm", il);
  4808. cur = llm_build_ffn(ctx0, lctx, cur,
  4809. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  4810. NULL, NULL, NULL,
  4811. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  4812. NULL,
  4813. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4814. cb(cur, "ffn_out", il);
  4815. cur = ggml_add(ctx0, cur, ffn_inp);
  4816. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4817. cb(cur, "l_out", il);
  4818. // input for next layer
  4819. inpL = cur;
  4820. }
  4821. }
  4822. cur = llm_build_norm(ctx0, inpL, hparams,
  4823. model.output_norm,
  4824. model.output_norm_b,
  4825. LLM_NORM, cb, -1);
  4826. cb(cur, "result_norm", -1);
  4827. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4828. cb(cur, "result_output", -1);
  4829. ggml_build_forward_expand(gf, cur);
  4830. return gf;
  4831. }
  4832. struct ggml_cgraph * build_arctic() {
  4833. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4834. // mutable variable, needed during the last layer of the computation to skip unused tokens
  4835. int32_t n_tokens = this->n_tokens;
  4836. const int64_t n_embd_head = hparams.n_embd_head_v;
  4837. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4838. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4839. struct ggml_tensor * cur;
  4840. struct ggml_tensor * inpL;
  4841. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4842. // inp_pos - contains the positions
  4843. struct ggml_tensor * inp_pos = build_inp_pos();
  4844. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4845. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4846. for (int il = 0; il < n_layer; ++il) {
  4847. struct ggml_tensor * inpSA = inpL;
  4848. // norm
  4849. cur = llm_build_norm(ctx0, inpL, hparams,
  4850. model.layers[il].attn_norm, NULL,
  4851. LLM_NORM_RMS, cb, il);
  4852. cb(cur, "attn_norm", il);
  4853. // self-attention
  4854. {
  4855. // compute Q and K and RoPE them
  4856. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  4857. cb(Qcur, "Qcur", il);
  4858. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4859. cb(Kcur, "Kcur", il);
  4860. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4861. cb(Vcur, "Vcur", il);
  4862. Qcur = ggml_rope_ext(
  4863. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  4864. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4865. ext_factor, attn_factor, beta_fast, beta_slow
  4866. );
  4867. cb(Qcur, "Qcur", il);
  4868. Kcur = ggml_rope_ext(
  4869. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  4870. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4871. ext_factor, attn_factor, beta_fast, beta_slow
  4872. );
  4873. cb(Kcur, "Kcur", il);
  4874. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4875. model.layers[il].wo, NULL,
  4876. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4877. }
  4878. if (il == n_layer - 1) {
  4879. // skip computing output for unused tokens
  4880. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  4881. n_tokens = n_outputs;
  4882. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  4883. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  4884. }
  4885. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4886. cb(ffn_inp, "ffn_inp", il);
  4887. // feed-forward network
  4888. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4889. model.layers[il].ffn_norm, NULL,
  4890. LLM_NORM_RMS, cb, il);
  4891. cb(cur, "ffn_norm", il);
  4892. cur = llm_build_ffn(ctx0, lctx, cur,
  4893. model.layers[il].ffn_up, NULL, NULL,
  4894. model.layers[il].ffn_gate, NULL, NULL,
  4895. model.layers[il].ffn_down, NULL, NULL,
  4896. NULL,
  4897. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4898. cb(cur, "ffn_out", il);
  4899. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  4900. cb(ffn_out, "ffn_out", il);
  4901. // MoE
  4902. cur = llm_build_norm(ctx0, inpSA, hparams,
  4903. model.layers[il].ffn_norm_exps, NULL,
  4904. LLM_NORM_RMS, cb, il);
  4905. cb(cur, "ffn_norm_exps", il);
  4906. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  4907. model.layers[il].ffn_gate_inp,
  4908. model.layers[il].ffn_up_exps,
  4909. model.layers[il].ffn_gate_exps,
  4910. model.layers[il].ffn_down_exps,
  4911. nullptr,
  4912. n_expert, n_expert_used,
  4913. LLM_FFN_SILU, true,
  4914. false, 0.0,
  4915. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  4916. cb, il);
  4917. cb(cur, "ffn_moe_out", il);
  4918. cur = ggml_add(ctx0, cur, ffn_out);
  4919. cb(cur, "ffn_out", il);
  4920. cur = lctx.cvec.apply_to(ctx0, cur, il);
  4921. cb(cur, "l_out", il);
  4922. // input for next layer
  4923. inpL = cur;
  4924. }
  4925. cur = inpL;
  4926. cur = llm_build_norm(ctx0, cur, hparams,
  4927. model.output_norm, NULL,
  4928. LLM_NORM_RMS, cb, -1);
  4929. cb(cur, "result_norm", -1);
  4930. // lm_head
  4931. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  4932. cb(cur, "result_output", -1);
  4933. ggml_build_forward_expand(gf, cur);
  4934. return gf;
  4935. }
  4936. struct ggml_cgraph * build_deepseek() {
  4937. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  4938. // mutable variable, needed during the last layer of the computation to skip unused tokens
  4939. int32_t n_tokens = this->n_tokens;
  4940. const int64_t n_embd_head = hparams.n_embd_head_v;
  4941. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4942. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4943. struct ggml_tensor * cur;
  4944. struct ggml_tensor * inpL;
  4945. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  4946. // inp_pos - contains the positions
  4947. struct ggml_tensor * inp_pos = build_inp_pos();
  4948. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4949. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4950. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  4951. for (int il = 0; il < n_layer; ++il) {
  4952. struct ggml_tensor * inpSA = inpL;
  4953. // norm
  4954. cur = llm_build_norm(ctx0, inpL, hparams,
  4955. model.layers[il].attn_norm, NULL,
  4956. LLM_NORM_RMS, cb, il);
  4957. cb(cur, "attn_norm", il);
  4958. // self-attention
  4959. {
  4960. // rope freq factors for llama3; may return nullptr for llama2 and other models
  4961. struct ggml_tensor * rope_factors = build_rope_factors(il);
  4962. // compute Q and K and RoPE them
  4963. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  4964. cb(Qcur, "Qcur", il);
  4965. if (model.layers[il].bq) {
  4966. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4967. cb(Qcur, "Qcur", il);
  4968. }
  4969. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  4970. cb(Kcur, "Kcur", il);
  4971. if (model.layers[il].bk) {
  4972. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4973. cb(Kcur, "Kcur", il);
  4974. }
  4975. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  4976. cb(Vcur, "Vcur", il);
  4977. if (model.layers[il].bv) {
  4978. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4979. cb(Vcur, "Vcur", il);
  4980. }
  4981. Qcur = ggml_rope_ext(
  4982. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  4983. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4984. ext_factor, attn_factor, beta_fast, beta_slow
  4985. );
  4986. cb(Qcur, "Qcur", il);
  4987. Kcur = ggml_rope_ext(
  4988. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  4989. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  4990. ext_factor, attn_factor, beta_fast, beta_slow
  4991. );
  4992. cb(Kcur, "Kcur", il);
  4993. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  4994. model.layers[il].wo, model.layers[il].bo,
  4995. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  4996. }
  4997. if (il == n_layer - 1) {
  4998. // skip computing output for unused tokens
  4999. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5000. n_tokens = n_outputs;
  5001. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5002. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5003. }
  5004. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5005. cb(ffn_inp, "ffn_inp", il);
  5006. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5007. model.layers[il].ffn_norm, NULL,
  5008. LLM_NORM_RMS, cb, il);
  5009. cb(cur, "ffn_norm", il);
  5010. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  5011. cur = llm_build_ffn(ctx0, lctx, cur,
  5012. model.layers[il].ffn_up, NULL, NULL,
  5013. model.layers[il].ffn_gate, NULL, NULL,
  5014. model.layers[il].ffn_down, NULL, NULL,
  5015. NULL,
  5016. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5017. cb(cur, "ffn_out", il);
  5018. } else {
  5019. // MoE branch
  5020. ggml_tensor * moe_out =
  5021. llm_build_moe_ffn(ctx0, lctx, cur,
  5022. model.layers[il].ffn_gate_inp,
  5023. model.layers[il].ffn_up_exps,
  5024. model.layers[il].ffn_gate_exps,
  5025. model.layers[il].ffn_down_exps,
  5026. nullptr,
  5027. n_expert, n_expert_used,
  5028. LLM_FFN_SILU, false,
  5029. false, hparams.expert_weights_scale,
  5030. LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,
  5031. cb, il);
  5032. cb(moe_out, "ffn_moe_out", il);
  5033. // FFN shared expert
  5034. {
  5035. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  5036. model.layers[il].ffn_up_shexp, NULL, NULL,
  5037. model.layers[il].ffn_gate_shexp, NULL, NULL,
  5038. model.layers[il].ffn_down_shexp, NULL, NULL,
  5039. NULL,
  5040. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5041. cb(ffn_shexp, "ffn_shexp", il);
  5042. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  5043. cb(cur, "ffn_out", il);
  5044. }
  5045. }
  5046. cur = ggml_add(ctx0, cur, ffn_inp);
  5047. cur = lctx.cvec.apply_to(ctx0, cur, il);
  5048. cb(cur, "l_out", il);
  5049. // input for next layer
  5050. inpL = cur;
  5051. }
  5052. cur = inpL;
  5053. cur = llm_build_norm(ctx0, cur, hparams,
  5054. model.output_norm, NULL,
  5055. LLM_NORM_RMS, cb, -1);
  5056. cb(cur, "result_norm", -1);
  5057. // lm_head
  5058. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  5059. cb(cur, "result_output", -1);
  5060. ggml_build_forward_expand(gf, cur);
  5061. return gf;
  5062. }
  5063. struct ggml_cgraph * build_deepseek2() {
  5064. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5065. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5066. int32_t n_tokens = this->n_tokens;
  5067. bool is_lite = (hparams.n_layer == 27);
  5068. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  5069. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  5070. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  5071. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  5072. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  5073. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  5074. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  5075. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  5076. struct ggml_tensor * cur;
  5077. struct ggml_tensor * inpL;
  5078. // {n_embd, n_tokens}
  5079. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5080. // inp_pos - contains the positions
  5081. struct ggml_tensor * inp_pos = build_inp_pos();
  5082. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5083. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5084. for (int il = 0; il < n_layer; ++il) {
  5085. struct ggml_tensor * inpSA = inpL;
  5086. // norm
  5087. cur = llm_build_norm(ctx0, inpL, hparams,
  5088. model.layers[il].attn_norm, NULL,
  5089. LLM_NORM_RMS, cb, il);
  5090. cb(cur, "attn_norm", il);
  5091. // self_attention
  5092. {
  5093. struct ggml_tensor * q = NULL;
  5094. if (!is_lite) {
  5095. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  5096. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  5097. cb(q, "q", il);
  5098. q = llm_build_norm(ctx0, q, hparams,
  5099. model.layers[il].attn_q_a_norm, NULL,
  5100. LLM_NORM_RMS, cb, il);
  5101. cb(q, "q", il);
  5102. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  5103. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  5104. cb(q, "q", il);
  5105. } else {
  5106. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5107. cb(q, "q", il);
  5108. }
  5109. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  5110. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  5111. ggml_row_size(q->type, hparams.n_embd_head_k),
  5112. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  5113. 0);
  5114. cb(q_nope, "q_nope", il);
  5115. // and {n_head * n_embd_head_qk_rope, n_tokens}
  5116. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  5117. ggml_row_size(q->type, hparams.n_embd_head_k),
  5118. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  5119. ggml_row_size(q->type, n_embd_head_qk_nope));
  5120. cb(q_pe, "q_pe", il);
  5121. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  5122. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  5123. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  5124. // split into {kv_lora_rank, n_tokens}
  5125. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  5126. kv_pe_compresseed->nb[1],
  5127. 0);
  5128. cb(kv_compressed, "kv_compressed", il);
  5129. // and {n_embd_head_qk_rope, n_tokens}
  5130. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  5131. kv_pe_compresseed->nb[1],
  5132. kv_pe_compresseed->nb[1],
  5133. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  5134. cb(k_pe, "k_pe", il);
  5135. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  5136. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  5137. model.layers[il].attn_kv_a_norm, NULL,
  5138. LLM_NORM_RMS, cb, il);
  5139. cb(kv_compressed, "kv_compressed", il);
  5140. // {kv_lora_rank, n_head * (n_embd_head_qk_nope + n_embd_head_v)} * {kv_lora_rank, n_tokens} -> {n_head * (n_embd_head_qk_nope + n_embd_head_v), n_tokens}
  5141. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  5142. cb(kv, "kv", il);
  5143. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  5144. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  5145. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  5146. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  5147. 0);
  5148. cb(k_nope, "k_nope", il);
  5149. // and {n_head * n_embd_head_v, n_tokens}
  5150. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  5151. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  5152. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  5153. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  5154. cb(v_states, "v_states", il);
  5155. v_states = ggml_cont(ctx0, v_states);
  5156. cb(v_states, "v_states", il);
  5157. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  5158. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  5159. 0);
  5160. cb(v_states, "v_states", il);
  5161. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend used to not support non-cont. RoPE, investigate removing this
  5162. q_pe = ggml_rope_ext(
  5163. ctx0, q_pe, inp_pos, nullptr,
  5164. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5165. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  5166. );
  5167. cb(q_pe, "q_pe", il);
  5168. // shared RoPE key
  5169. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend used to not support non-cont. RoPE, investigate removing this
  5170. k_pe = ggml_rope_ext(
  5171. ctx0, k_pe, inp_pos, nullptr,
  5172. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5173. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  5174. );
  5175. cb(k_pe, "k_pe", il);
  5176. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  5177. cb(q_states, "q_states", il);
  5178. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  5179. cb(k_states, "k_states", il);
  5180. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  5181. model.layers[il].wo, NULL,
  5182. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  5183. }
  5184. if (il == n_layer - 1) {
  5185. // skip computing output for unused tokens
  5186. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5187. n_tokens = n_outputs;
  5188. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5189. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5190. }
  5191. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5192. cb(ffn_inp, "ffn_inp", il);
  5193. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5194. model.layers[il].ffn_norm, NULL,
  5195. LLM_NORM_RMS, cb, il);
  5196. cb(cur, "ffn_norm", il);
  5197. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  5198. cur = llm_build_ffn(ctx0, lctx, cur,
  5199. model.layers[il].ffn_up, NULL, NULL,
  5200. model.layers[il].ffn_gate, NULL, NULL,
  5201. model.layers[il].ffn_down, NULL, NULL,
  5202. NULL,
  5203. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5204. cb(cur, "ffn_out", il);
  5205. } else {
  5206. // MoE branch
  5207. ggml_tensor * moe_out =
  5208. llm_build_moe_ffn(ctx0, lctx, cur,
  5209. model.layers[il].ffn_gate_inp,
  5210. model.layers[il].ffn_up_exps,
  5211. model.layers[il].ffn_gate_exps,
  5212. model.layers[il].ffn_down_exps,
  5213. model.layers[il].ffn_exp_probs_b,
  5214. n_expert, n_expert_used,
  5215. LLM_FFN_SILU, hparams.expert_weights_norm,
  5216. true, hparams.expert_weights_scale,
  5217. (enum llama_expert_gating_func_type) hparams.expert_gating_func,
  5218. cb, il);
  5219. cb(moe_out, "ffn_moe_out", il);
  5220. // FFN shared expert
  5221. {
  5222. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  5223. model.layers[il].ffn_up_shexp, NULL, NULL,
  5224. model.layers[il].ffn_gate_shexp, NULL, NULL,
  5225. model.layers[il].ffn_down_shexp, NULL, NULL,
  5226. NULL,
  5227. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5228. cb(ffn_shexp, "ffn_shexp", il);
  5229. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  5230. cb(cur, "ffn_out", il);
  5231. }
  5232. }
  5233. cur = ggml_add(ctx0, cur, ffn_inp);
  5234. cur = lctx.cvec.apply_to(ctx0, cur, il);
  5235. cb(cur, "l_out", il);
  5236. // input for next layer
  5237. inpL = cur;
  5238. }
  5239. cur = inpL;
  5240. cur = llm_build_norm(ctx0, cur, hparams,
  5241. model.output_norm, NULL,
  5242. LLM_NORM_RMS, cb, -1);
  5243. cb(cur, "result_norm", -1);
  5244. // lm_head
  5245. cur = ggml_mul_mat(ctx0, model.output, cur);
  5246. cb(cur, "result_output", -1);
  5247. ggml_build_forward_expand(gf, cur);
  5248. return gf;
  5249. }
  5250. struct ggml_cgraph * build_bitnet() {
  5251. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5252. const int64_t n_embd_head = hparams.n_embd_head_v;
  5253. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5254. struct ggml_tensor * cur;
  5255. struct ggml_tensor * inpL;
  5256. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5257. // inp_pos - contains the positions
  5258. struct ggml_tensor * inp_pos = build_inp_pos();
  5259. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5260. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5261. for (int il = 0; il < n_layer; ++il) {
  5262. struct ggml_tensor * inpSA = inpL;
  5263. cur = llm_build_norm(ctx0, inpL, hparams,
  5264. model.layers[il].attn_norm, NULL,
  5265. LLM_NORM_RMS, cb, il);
  5266. cb(cur, "attn_norm", il);
  5267. // self-attention
  5268. {
  5269. // compute Q and K and RoPE them
  5270. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  5271. if (model.layers[il].wq_scale) {
  5272. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  5273. }
  5274. cb(Qcur, "Qcur", il);
  5275. if (model.layers[il].bq) {
  5276. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5277. cb(Qcur, "Qcur", il);
  5278. }
  5279. // B1.K
  5280. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  5281. if (model.layers[il].wk_scale) {
  5282. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  5283. }
  5284. cb(Kcur, "Kcur", il);
  5285. if (model.layers[il].bk) {
  5286. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5287. cb(Kcur, "Kcur", il);
  5288. }
  5289. // B1.V
  5290. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  5291. if (model.layers[il].wv_scale) {
  5292. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  5293. }
  5294. cb(Vcur, "Vcur", il);
  5295. if (model.layers[il].bv) {
  5296. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5297. cb(Vcur, "Vcur", il);
  5298. }
  5299. Qcur = ggml_rope_ext(
  5300. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  5301. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5302. ext_factor, attn_factor, beta_fast, beta_slow
  5303. );
  5304. cb(Qcur, "Qcur", il);
  5305. Kcur = ggml_rope_ext(
  5306. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  5307. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5308. ext_factor, attn_factor, beta_fast, beta_slow
  5309. );
  5310. cb(Kcur, "Kcur", il);
  5311. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  5312. NULL, NULL,
  5313. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5314. cur = llm_build_norm(ctx0, cur, hparams,
  5315. model.layers[il].attn_sub_norm, NULL,
  5316. LLM_NORM_RMS, cb, il);
  5317. cb(cur, "attn_sub_norm", il);
  5318. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  5319. if (model.layers[il].wo_scale) {
  5320. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  5321. }
  5322. if (model.layers[il].bo) {
  5323. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  5324. }
  5325. cb(cur, "attn_o_out", il);
  5326. }
  5327. if (il == n_layer - 1) {
  5328. // skip computing output for unused tokens
  5329. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5330. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5331. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5332. }
  5333. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5334. cb(ffn_inp, "ffn_inp", il);
  5335. // feed-forward forward
  5336. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5337. model.layers[il].ffn_norm, NULL,
  5338. LLM_NORM_RMS, cb, il);
  5339. cb(cur, "ffn_norm", il);
  5340. cur = llm_build_ffn(ctx0, lctx, cur,
  5341. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  5342. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  5343. NULL, NULL, NULL,
  5344. NULL,
  5345. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5346. cb(cur, "ffn_sub_out", il);
  5347. cur = llm_build_norm(ctx0, cur, hparams,
  5348. model.layers[il].ffn_sub_norm, NULL,
  5349. LLM_NORM_RMS, cb, il);
  5350. cb(cur, "ffn_sub_norm", il);
  5351. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  5352. if (model.layers[il].ffn_down_scale) {
  5353. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  5354. }
  5355. cb(cur, "ffn_down", il);
  5356. cur = ggml_add(ctx0, cur, ffn_inp);
  5357. cb(cur, "l_out", il);
  5358. // input for next layer
  5359. inpL = cur;
  5360. }
  5361. cur = inpL;
  5362. cur = llm_build_norm(ctx0, cur, hparams,
  5363. model.output_norm, NULL,
  5364. LLM_NORM_RMS, cb, -1);
  5365. cb(cur, "result_norm", -1);
  5366. // lm_head
  5367. // FIXME: do not use model.tok_embd directly, duplicate as model.output
  5368. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  5369. cb(cur, "result_output", -1);
  5370. ggml_build_forward_expand(gf, cur);
  5371. return gf;
  5372. }
  5373. struct ggml_cgraph * build_t5_enc() {
  5374. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5375. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5376. int32_t n_tokens = this->n_tokens;
  5377. const int64_t n_embd_head = hparams.n_embd_head_v;
  5378. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5379. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5380. struct ggml_tensor * cur;
  5381. struct ggml_tensor * inpL;
  5382. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5383. GGML_ASSERT(lctx.is_encoding);
  5384. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  5385. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5386. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  5387. for (int il = 0; il < n_layer; ++il) {
  5388. struct ggml_tensor * inpSA = inpL;
  5389. // norm
  5390. cur = llm_build_norm(ctx0, inpL, hparams,
  5391. model.layers[il].attn_norm_enc, NULL,
  5392. LLM_NORM_RMS, cb, il);
  5393. cb(cur, "attn_norm", il);
  5394. // self-attention
  5395. {
  5396. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  5397. cb(Qcur, "Qcur", il);
  5398. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  5399. cb(Kcur, "Kcur", il);
  5400. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  5401. cb(Vcur, "Vcur", il);
  5402. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5403. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5404. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5405. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  5406. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5407. cb(kq, "kq", il);
  5408. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b_enc ? model.layers[il].attn_rel_b_enc : model.layers[0].attn_rel_b_enc;
  5409. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  5410. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  5411. cb(kq_b, "kq_b", il);
  5412. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  5413. cb(kq, "kq_soft_max_ext", il);
  5414. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  5415. cb(v, "v", il);
  5416. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  5417. cb(kqv, "kqv", il);
  5418. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5419. cb(kqv_merged, "kqv_merged", il);
  5420. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5421. cb(cur, "kqv_merged_cont", il);
  5422. ggml_build_forward_expand(gf, cur);
  5423. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  5424. cb(cur, "kqv_out", il);
  5425. }
  5426. if (il == n_layer - 1) {
  5427. // skip computing output for unused tokens
  5428. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5429. n_tokens = n_outputs;
  5430. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5431. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5432. }
  5433. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5434. cb(ffn_inp, "ffn_inp", il);
  5435. // feed-forward network
  5436. {
  5437. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5438. model.layers[il].ffn_norm_enc, NULL,
  5439. LLM_NORM_RMS, cb, il);
  5440. cb(cur, "ffn_norm", il);
  5441. // T5 uses relu, flan-T5 uses gelu-gated
  5442. cur = llm_build_ffn(ctx0, lctx, cur,
  5443. model.layers[il].ffn_up_enc, NULL, NULL,
  5444. model.layers[il].ffn_gate_enc, NULL, NULL,
  5445. model.layers[il].ffn_down_enc, NULL, NULL,
  5446. NULL,
  5447. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  5448. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  5449. cb, il);
  5450. cb(cur, "ffn_out", il);
  5451. }
  5452. cur = ggml_add(ctx0, cur, ffn_inp);
  5453. cb(cur, "ffn_out", il);
  5454. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5455. if (layer_dir != nullptr) {
  5456. cur = ggml_add(ctx0, cur, layer_dir);
  5457. }
  5458. cb(cur, "l_out", il);
  5459. // input for next layer
  5460. inpL = cur;
  5461. }
  5462. cur = inpL;
  5463. cb(cur, "result_embd", -1);
  5464. cur = llm_build_norm(ctx0, cur, hparams,
  5465. model.output_norm_enc, NULL,
  5466. LLM_NORM_RMS, cb, -1);
  5467. cb(cur, "result_norm", -1);
  5468. ggml_build_forward_expand(gf, cur);
  5469. return gf;
  5470. }
  5471. struct ggml_cgraph * build_t5_dec() {
  5472. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5473. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5474. int32_t n_tokens = this->n_tokens;
  5475. const int64_t n_embd_head = hparams.n_embd_head_v;
  5476. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5477. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5478. struct ggml_tensor * cur;
  5479. struct ggml_tensor * inpL;
  5480. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5481. GGML_ASSERT(!lctx.is_encoding);
  5482. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  5483. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  5484. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  5485. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  5486. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  5487. for (int il = 0; il < n_layer; ++il) {
  5488. struct ggml_tensor * inpSA = inpL;
  5489. // norm
  5490. cur = llm_build_norm(ctx0, inpL, hparams,
  5491. model.layers[il].attn_norm, NULL,
  5492. LLM_NORM_RMS, cb, il);
  5493. cb(cur, "attn_norm", il);
  5494. // self-attention
  5495. {
  5496. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  5497. cb(Qcur, "Qcur", il);
  5498. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  5499. cb(Kcur, "Kcur", il);
  5500. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  5501. cb(Vcur, "Vcur", il);
  5502. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  5503. struct ggml_tensor * k =
  5504. ggml_view_3d(ctx0, kv_self.k_l[il],
  5505. n_embd_head_k, n_kv, n_head_kv,
  5506. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5507. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5508. 0);
  5509. cb(k, "k", il);
  5510. struct ggml_tensor * v =
  5511. ggml_view_3d(ctx0, kv_self.v_l[il],
  5512. n_kv, n_embd_head_v, n_head_kv,
  5513. ggml_element_size(kv_self.v_l[il])*n_ctx,
  5514. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  5515. 0);
  5516. cb(v, "v", il);
  5517. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5518. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5519. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5520. cb(kq, "kq", il);
  5521. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  5522. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  5523. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  5524. cb(kq_b, "kq_b", il);
  5525. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  5526. cb(kq, "kq_soft_max_ext", il);
  5527. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  5528. cb(kqv, "kqv", il);
  5529. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5530. cb(kqv_merged, "kqv_merged", il);
  5531. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5532. cb(cur, "kqv_merged_cont", il);
  5533. ggml_build_forward_expand(gf, cur);
  5534. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  5535. cb(cur, "kqv_out", il);
  5536. }
  5537. cur = ggml_add(ctx0, cur, inpSA);
  5538. cb(cur, "cross_inp", il);
  5539. struct ggml_tensor * inpCA = cur;
  5540. // norm
  5541. cur = llm_build_norm(ctx0, cur, hparams,
  5542. model.layers[il].attn_norm_cross, NULL,
  5543. LLM_NORM_RMS, cb, il);
  5544. cb(cur, "attn_norm_cross", il);
  5545. // cross-attention
  5546. {
  5547. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  5548. cb(Qcur, "Qcur", il);
  5549. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  5550. cb(Kcur, "Kcur", il);
  5551. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  5552. cb(Vcur, "Vcur", il);
  5553. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5554. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  5555. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5556. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  5557. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5558. cb(kq, "kq", il);
  5559. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  5560. cb(kq, "kq_soft_max_ext", il);
  5561. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  5562. cb(v, "v", il);
  5563. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  5564. cb(kqv, "kqv", il);
  5565. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5566. cb(kqv_merged, "kqv_merged", il);
  5567. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5568. cb(cur, "kqv_merged_cont", il);
  5569. ggml_build_forward_expand(gf, cur);
  5570. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  5571. cb(cur, "kqv_out", il);
  5572. }
  5573. if (il == n_layer - 1) {
  5574. // skip computing output for unused tokens
  5575. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5576. n_tokens = n_outputs;
  5577. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5578. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5579. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  5580. }
  5581. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  5582. cb(ffn_inp, "ffn_inp", il);
  5583. // feed-forward network
  5584. {
  5585. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5586. model.layers[il].ffn_norm, NULL,
  5587. LLM_NORM_RMS, cb, il);
  5588. cb(cur, "ffn_norm", il);
  5589. // T5 uses relu, flan-T5 uses gelu-gated
  5590. cur = llm_build_ffn(ctx0, lctx, cur,
  5591. model.layers[il].ffn_up, NULL, NULL,
  5592. model.layers[il].ffn_gate, NULL, NULL,
  5593. model.layers[il].ffn_down, NULL, NULL,
  5594. NULL,
  5595. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  5596. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  5597. cb, il);
  5598. cb(cur, "ffn_out", il);
  5599. }
  5600. cur = ggml_add(ctx0, cur, ffn_inp);
  5601. cb(cur, "ffn_out", il);
  5602. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5603. if (layer_dir != nullptr) {
  5604. cur = ggml_add(ctx0, cur, layer_dir);
  5605. }
  5606. cb(cur, "l_out", il);
  5607. // input for next layer
  5608. inpL = cur;
  5609. }
  5610. cur = inpL;
  5611. cb(cur, "result_embd", -1);
  5612. cur = llm_build_norm(ctx0, cur, hparams,
  5613. model.output_norm, NULL,
  5614. LLM_NORM_RMS, cb, -1);
  5615. cb(cur, "result_norm", -1);
  5616. // lm_head
  5617. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  5618. cb(cur, "result_output", -1);
  5619. ggml_build_forward_expand(gf, cur);
  5620. return gf;
  5621. }
  5622. struct ggml_cgraph * build_jais() {
  5623. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5624. const int64_t n_embd_head = hparams.n_embd_head_v;
  5625. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5626. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5627. struct ggml_tensor * cur;
  5628. struct ggml_tensor * inpL;
  5629. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5630. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5631. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5632. for (int il = 0; il < n_layer; ++il) {
  5633. cur = llm_build_norm(ctx0, inpL, hparams,
  5634. model.layers[il].attn_norm,
  5635. model.layers[il].attn_norm_b,
  5636. LLM_NORM, cb, il);
  5637. cb(cur, "attn_norm", il);
  5638. // self-attention
  5639. {
  5640. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  5641. cb(cur, "wqkv", il);
  5642. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5643. cb(cur, "bqkv", il);
  5644. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*cur->nb[0]*(n_embd)));
  5645. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*cur->nb[0]*(n_embd)));
  5646. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*cur->nb[0]*(n_embd + n_embd_gqa)));
  5647. cb(Qcur, "Qcur", il);
  5648. cb(Kcur, "Kcur", il);
  5649. cb(Vcur, "Vcur", il);
  5650. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5651. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  5652. model.layers[il].wo, model.layers[il].bo,
  5653. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  5654. }
  5655. if (il == n_layer - 1) {
  5656. // skip computing output for unused tokens
  5657. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5658. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5659. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5660. }
  5661. // add the input
  5662. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5663. cb(ffn_inp, "ffn_inp", il);
  5664. // FF
  5665. {
  5666. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5667. model.layers[il].ffn_norm,
  5668. model.layers[il].ffn_norm_b,
  5669. LLM_NORM, cb, il);
  5670. cb(cur, "ffn_norm", il);
  5671. cur = llm_build_ffn(ctx0, lctx, cur,
  5672. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  5673. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  5674. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  5675. NULL,
  5676. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5677. cb(cur, "ffn_out", il);
  5678. }
  5679. inpL = ggml_add(ctx0, cur, ffn_inp);
  5680. cb(inpL, "l_out", il);
  5681. }
  5682. cur = llm_build_norm(ctx0, inpL, hparams,
  5683. model.output_norm,
  5684. model.output_norm_b,
  5685. LLM_NORM, cb, -1);
  5686. cb(cur, "result_norm", -1);
  5687. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  5688. cb(cur, "result_output", -1);
  5689. ggml_build_forward_expand(gf, cur);
  5690. return gf;
  5691. }
  5692. struct ggml_cgraph * build_chatglm() {
  5693. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5694. const int64_t n_embd_head = hparams.n_embd_head_v;
  5695. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5696. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5697. struct ggml_tensor * cur;
  5698. struct ggml_tensor * inpL;
  5699. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5700. // inp_pos - contains the positions
  5701. struct ggml_tensor * inp_pos = build_inp_pos();
  5702. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5703. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5704. for (int il = 0; il < n_layer; ++il) {
  5705. struct ggml_tensor * inpSA = inpL;
  5706. cur = llm_build_norm(ctx0, inpL, hparams,
  5707. model.layers[il].attn_norm,
  5708. NULL,
  5709. LLM_NORM_RMS, cb, il);
  5710. cb(cur, "attn_norm", il);
  5711. // self-attention
  5712. {
  5713. struct ggml_tensor * Qcur = nullptr;
  5714. struct ggml_tensor * Kcur = nullptr;
  5715. struct ggml_tensor * Vcur = nullptr;
  5716. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  5717. cb(cur, "wqkv", il);
  5718. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5719. cb(cur, "bqkv", il);
  5720. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5721. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5722. Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  5723. cb(Qcur, "Qcur", il);
  5724. cb(Kcur, "Kcur", il);
  5725. cb(Vcur, "Vcur", il);
  5726. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  5727. Qcur = ggml_rope_ext(
  5728. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  5729. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5730. ext_factor, attn_factor, beta_fast, beta_slow
  5731. );
  5732. cb(Qcur, "Qcur_rope", il);
  5733. Kcur = ggml_rope_ext(
  5734. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  5735. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5736. ext_factor, attn_factor, beta_fast, beta_slow
  5737. );
  5738. cb(Kcur, "Kcur_rope", il);
  5739. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  5740. model.layers[il].wo, NULL,
  5741. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5742. }
  5743. if (il == n_layer - 1) {
  5744. // skip computing output for unused tokens
  5745. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5746. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5747. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5748. }
  5749. // Add the input
  5750. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5751. cb(ffn_inp, "ffn_inp", il);
  5752. // FF
  5753. {
  5754. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5755. model.layers[il].ffn_norm,
  5756. NULL,
  5757. LLM_NORM_RMS, cb, il);
  5758. cb(cur, "ffn_norm", il);
  5759. cur = llm_build_ffn(ctx0, lctx, cur,
  5760. model.layers[il].ffn_up, NULL, NULL,
  5761. NULL, NULL, NULL,
  5762. model.layers[il].ffn_down, NULL, NULL,
  5763. NULL,
  5764. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  5765. cb(cur, "ffn_out", il);
  5766. }
  5767. inpL = ggml_add(ctx0, cur, ffn_inp);
  5768. cb(inpL, "l_out", il);
  5769. }
  5770. cur = llm_build_norm(ctx0, inpL, hparams,
  5771. model.output_norm,
  5772. NULL,
  5773. LLM_NORM_RMS, cb, -1);
  5774. cb(cur, "result_norm", -1);
  5775. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  5776. cb(cur, "result_output", -1);
  5777. ggml_build_forward_expand(gf, cur);
  5778. return gf;
  5779. }
  5780. struct ggml_cgraph * build_nemotron() {
  5781. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5782. const int64_t n_embd_head = hparams.n_embd_head_v;
  5783. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5784. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  5785. struct ggml_tensor * cur;
  5786. struct ggml_tensor * inpL;
  5787. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5788. // inp_pos - contains the positions
  5789. struct ggml_tensor * inp_pos = build_inp_pos();
  5790. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5791. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5792. for (int il = 0; il < n_layer; ++il) {
  5793. struct ggml_tensor * inpSA = inpL;
  5794. // norm
  5795. cur = llm_build_norm(ctx0, inpL, hparams,
  5796. model.layers[il].attn_norm,
  5797. model.layers[il].attn_norm_b,
  5798. LLM_NORM, cb, il);
  5799. cb(cur, "attn_norm", il);
  5800. // self-attention
  5801. {
  5802. // compute Q and K and RoPE them
  5803. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  5804. cb(Qcur, "Qcur", il);
  5805. if (model.layers[il].bq) {
  5806. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5807. cb(Qcur, "Qcur", il);
  5808. }
  5809. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  5810. cb(Kcur, "Kcur", il);
  5811. if (model.layers[il].bk) {
  5812. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5813. cb(Kcur, "Kcur", il);
  5814. }
  5815. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  5816. cb(Vcur, "Vcur", il);
  5817. if (model.layers[il].bv) {
  5818. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5819. cb(Vcur, "Vcur", il);
  5820. }
  5821. Qcur = ggml_rope_ext(
  5822. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  5823. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5824. ext_factor, attn_factor, beta_fast, beta_slow
  5825. );
  5826. cb(Qcur, "Qcur", il);
  5827. Kcur = ggml_rope_ext(
  5828. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  5829. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5830. ext_factor, attn_factor, beta_fast, beta_slow
  5831. );
  5832. cb(Kcur, "Kcur", il);
  5833. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  5834. model.layers[il].wo, model.layers[il].bo,
  5835. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5836. }
  5837. if (il == n_layer - 1) {
  5838. // skip computing output for unused tokens
  5839. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5840. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5841. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5842. }
  5843. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5844. cb(ffn_inp, "ffn_inp", il);
  5845. // feed-forward network
  5846. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5847. model.layers[il].ffn_norm,
  5848. model.layers[il].ffn_norm_b,
  5849. LLM_NORM, cb, il);
  5850. cb(cur, "ffn_norm", il);
  5851. cur = llm_build_ffn(ctx0, lctx, cur,
  5852. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  5853. NULL, NULL, NULL,
  5854. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  5855. NULL,
  5856. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5857. cur = ggml_add(ctx0, cur, ffn_inp);
  5858. cb(cur, "ffn_out", il);
  5859. cur = lctx.cvec.apply_to(ctx0, cur, il);
  5860. cb(cur, "l_out", il);
  5861. // input for next layer
  5862. inpL = cur;
  5863. }
  5864. cur = inpL;
  5865. cur = llm_build_norm(ctx0, cur, hparams,
  5866. model.output_norm, model.output_norm_b,
  5867. LLM_NORM, cb, -1);
  5868. cb(cur, "result_norm", -1);
  5869. // lm_head
  5870. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  5871. cb(cur, "result_output", -1);
  5872. ggml_build_forward_expand(gf, cur);
  5873. return gf;
  5874. }
  5875. struct ggml_cgraph * build_exaone() {
  5876. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5877. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5878. int32_t n_tokens = this->n_tokens;
  5879. const int64_t n_embd_head = hparams.n_embd_head_v;
  5880. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5881. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5882. struct ggml_tensor * cur;
  5883. struct ggml_tensor * inpL;
  5884. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5885. // inp_pos - contains the positions
  5886. struct ggml_tensor * inp_pos = build_inp_pos();
  5887. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5888. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5889. for (int il = 0; il < n_layer; ++il) {
  5890. struct ggml_tensor * inpSA = inpL;
  5891. // norm
  5892. cur = llm_build_norm(ctx0, inpL, hparams,
  5893. model.layers[il].attn_norm, NULL,
  5894. LLM_NORM_RMS, cb, il);
  5895. cb(cur, "attn_norm", il);
  5896. // self-attention
  5897. {
  5898. // rope freq factors for llama3; may return nullptr for llama2 and other models
  5899. struct ggml_tensor * rope_factors = build_rope_factors(il);
  5900. // compute Q and K and RoPE them
  5901. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  5902. cb(Qcur, "Qcur", il);
  5903. if (model.layers[il].bq) {
  5904. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5905. cb(Qcur, "Qcur", il);
  5906. }
  5907. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  5908. cb(Kcur, "Kcur", il);
  5909. if (model.layers[il].bk) {
  5910. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5911. cb(Kcur, "Kcur", il);
  5912. }
  5913. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  5914. cb(Vcur, "Vcur", il);
  5915. if (model.layers[il].bv) {
  5916. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5917. cb(Vcur, "Vcur", il);
  5918. }
  5919. Qcur = ggml_rope_ext(
  5920. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  5921. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5922. ext_factor, attn_factor, beta_fast, beta_slow
  5923. );
  5924. cb(Qcur, "Qcur", il);
  5925. Kcur = ggml_rope_ext(
  5926. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  5927. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  5928. ext_factor, attn_factor, beta_fast, beta_slow
  5929. );
  5930. cb(Kcur, "Kcur", il);
  5931. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  5932. model.layers[il].wo, model.layers[il].bo,
  5933. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5934. }
  5935. if (il == n_layer - 1) {
  5936. // skip computing output for unused tokens
  5937. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5938. n_tokens = n_outputs;
  5939. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5940. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5941. }
  5942. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5943. cb(ffn_inp, "ffn_inp", il);
  5944. // feed-forward network
  5945. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5946. model.layers[il].ffn_norm, NULL,
  5947. LLM_NORM_RMS, cb, il);
  5948. cb(cur, "ffn_norm", il);
  5949. cur = llm_build_ffn(ctx0, lctx, cur,
  5950. model.layers[il].ffn_up, NULL, NULL,
  5951. model.layers[il].ffn_gate, NULL, NULL,
  5952. model.layers[il].ffn_down, NULL, NULL,
  5953. NULL,
  5954. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5955. cb(cur, "ffn_out", il);
  5956. cur = ggml_add(ctx0, cur, ffn_inp);
  5957. cb(cur, "ffn_out", il);
  5958. cur = lctx.cvec.apply_to(ctx0, cur, il);
  5959. cb(cur, "l_out", il);
  5960. // input for next layer
  5961. inpL = cur;
  5962. }
  5963. cur = inpL;
  5964. cur = llm_build_norm(ctx0, cur, hparams,
  5965. model.output_norm, NULL,
  5966. LLM_NORM_RMS, cb, -1);
  5967. cb(cur, "result_norm", -1);
  5968. // lm_head
  5969. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  5970. cb(cur, "result_output", -1);
  5971. ggml_build_forward_expand(gf, cur);
  5972. return gf;
  5973. }
  5974. ggml_cgraph * build_rwkv6() {
  5975. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  5976. // Token shift state dimensions should be 2 * n_emb
  5977. GGML_ASSERT(n_embd == hparams.n_embd_k_s() / 2);
  5978. const int64_t n_seqs = ubatch.n_seqs;
  5979. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  5980. const int64_t n_tokens = ubatch.n_tokens;
  5981. GGML_ASSERT(n_seqs != 0);
  5982. GGML_ASSERT(ubatch.equal_seqs);
  5983. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  5984. struct ggml_tensor * cur;
  5985. struct ggml_tensor * inpL;
  5986. struct ggml_tensor * state_copy = build_inp_s_copy();
  5987. struct ggml_tensor * state_mask = build_inp_s_mask();
  5988. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  5989. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5990. for (int il = 0; il < n_layer; ++il) {
  5991. const llama_layer * layer = &model.layers[il];
  5992. // (ab)using the KV cache to store the states
  5993. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  5994. gf, kv_self.k_l[il], state_copy, state_mask,
  5995. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  5996. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  5997. gf, kv_self.v_l[il], state_copy, state_mask,
  5998. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  5999. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  6000. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 2, n_seqs);
  6001. struct ggml_tensor * att_shift = ggml_view_3d(ctx0, token_shift, n_embd, 1, n_seqs, token_shift->nb[1], token_shift->nb[2], 0);
  6002. struct ggml_tensor * ffn_shift = ggml_view_3d(ctx0, token_shift, n_embd, 1, n_seqs, token_shift->nb[1], token_shift->nb[2], n_embd * ggml_element_size(token_shift));
  6003. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM, cb, il);
  6004. struct ggml_tensor * x_prev = ggml_concat(
  6005. ctx0,
  6006. att_shift,
  6007. ggml_view_3d(ctx0, x_norm_att, n_embd, n_seq_tokens - 1, n_seqs, x_norm_att->nb[1], x_norm_att->nb[2], 0),
  6008. 1
  6009. );
  6010. cur = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states, hparams.wkv_head_size, n_embd / hparams.wkv_head_size));
  6011. ggml_build_forward_expand(gf, cur);
  6012. ggml_build_forward_expand(
  6013. gf,
  6014. ggml_cpy(
  6015. ctx0,
  6016. wkv_states,
  6017. ggml_view_1d(
  6018. ctx0,
  6019. kv_self.v_l[il],
  6020. hparams.n_embd_v_s() * n_seqs,
  6021. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  6022. )
  6023. )
  6024. );
  6025. struct ggml_tensor * x_norm_ffn = llm_build_norm(ctx0, cur, hparams, layer->attn_norm_2, layer->attn_norm_2_b, LLM_NORM, cb, il);
  6026. x_prev = ggml_concat(
  6027. ctx0,
  6028. ffn_shift,
  6029. ggml_view_3d(ctx0, x_norm_ffn, n_embd, n_seq_tokens - 1, n_seqs, x_norm_ffn->nb[1], x_norm_ffn->nb[2], 0),
  6030. 1
  6031. );
  6032. cur = ggml_add(ctx0, cur, llm_build_rwkv6_channel_mix(lctx, ctx0, layer, x_norm_ffn, x_prev));
  6033. ggml_build_forward_expand(gf, cur);
  6034. struct ggml_tensor * last_norm_att = ggml_view_3d(ctx0, x_norm_att, n_embd, 1, n_seqs, x_norm_att->nb[1], x_norm_att->nb[2], (n_seq_tokens-1)*n_embd*ggml_element_size(x_norm_att));
  6035. struct ggml_tensor * last_norm_ffn = ggml_view_3d(ctx0, x_norm_ffn, n_embd, 1, n_seqs, x_norm_ffn->nb[1], x_norm_ffn->nb[2], (n_seq_tokens-1)*n_embd*ggml_element_size(x_norm_ffn));
  6036. token_shift = ggml_concat(ctx0, last_norm_att, last_norm_ffn, 1);
  6037. ggml_build_forward_expand(
  6038. gf,
  6039. ggml_cpy(
  6040. ctx0,
  6041. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * 2, 0),
  6042. ggml_view_1d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s() * n_seqs, hparams.n_embd_k_s() * kv_head * ggml_element_size(kv_self.k_l[il]))
  6043. )
  6044. );
  6045. if (hparams.rescale_every_n_layers != 0 && (il + 1) % hparams.rescale_every_n_layers == 0) {
  6046. cur = ggml_scale(ctx0, cur, 0.5F);
  6047. }
  6048. cur = lctx.cvec.apply_to(ctx0, cur, il);
  6049. cb(cur, "l_out", il);
  6050. // input for next layer
  6051. inpL = cur;
  6052. }
  6053. cur = inpL;
  6054. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6055. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  6056. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6057. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM, cb, -1);
  6058. cb(cur, "result_norm", -1);
  6059. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  6060. cb(cur, "result_output", -1);
  6061. ggml_build_forward_expand(gf, cur);
  6062. return gf;
  6063. }
  6064. // ref: https://huggingface.co/recursal/QRWKV6-32B-Instruct-Preview-v0.1/blob/main/modeling_rwkv6qwen2.py
  6065. ggml_cgraph * build_rwkv6qwen2() {
  6066. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  6067. GGML_ASSERT(n_embd == hparams.n_embd_k_s());
  6068. const int64_t n_seqs = ubatch.n_seqs;
  6069. const int64_t n_seq_tokens = ubatch.n_seq_tokens;
  6070. const int64_t n_tokens = ubatch.n_tokens;
  6071. GGML_ASSERT(n_seqs != 0);
  6072. GGML_ASSERT(ubatch.equal_seqs);
  6073. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  6074. struct ggml_tensor * cur;
  6075. struct ggml_tensor * inpL;
  6076. struct ggml_tensor * state_copy = build_inp_s_copy();
  6077. struct ggml_tensor * state_mask = build_inp_s_mask();
  6078. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  6079. for (int il = 0; il < n_layer; ++il) {
  6080. const llama_layer * layer = &model.layers[il];
  6081. // (ab)using the KV cache to store the states
  6082. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  6083. gf, kv_self.k_l[il], state_copy, state_mask,
  6084. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  6085. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  6086. gf, kv_self.v_l[il], state_copy, state_mask,
  6087. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  6088. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  6089. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 1, n_seqs);
  6090. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM_RMS, cb, il);
  6091. struct ggml_tensor * x_prev = ggml_concat(
  6092. ctx0,
  6093. token_shift,
  6094. ggml_view_3d(ctx0, x_norm_att, n_embd, n_seq_tokens - 1, n_seqs, x_norm_att->nb[1], x_norm_att->nb[2], 0),
  6095. 1
  6096. );
  6097. ggml_build_forward_expand(
  6098. gf,
  6099. ggml_cpy(
  6100. ctx0,
  6101. wkv_states,
  6102. ggml_view_1d(
  6103. ctx0,
  6104. kv_self.v_l[il],
  6105. hparams.n_embd_v_s() * n_seqs,
  6106. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  6107. )
  6108. )
  6109. );
  6110. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states, hparams.wkv_head_size, hparams.n_head_kv()));
  6111. ggml_build_forward_expand(gf, ffn_inp);
  6112. ggml_build_forward_expand(
  6113. gf,
  6114. ggml_cpy(
  6115. ctx0,
  6116. wkv_states,
  6117. ggml_view_1d(
  6118. ctx0,
  6119. kv_self.v_l[il],
  6120. hparams.n_embd_v_s() * n_seqs,
  6121. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  6122. )
  6123. )
  6124. );
  6125. cb(ffn_inp, "ffn_inp", il);
  6126. // feed-forward network
  6127. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6128. model.layers[il].ffn_norm, NULL,
  6129. LLM_NORM_RMS, cb, il);
  6130. cb(cur, "ffn_norm", il);
  6131. cur = llm_build_ffn(ctx0, lctx, cur,
  6132. model.layers[il].ffn_up, NULL, NULL,
  6133. model.layers[il].ffn_gate, NULL, NULL,
  6134. model.layers[il].ffn_down, NULL, NULL,
  6135. NULL,
  6136. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6137. cb(cur, "ffn_out", il);
  6138. cur = ggml_add(ctx0, cur, ffn_inp);
  6139. cur = lctx.cvec.apply_to(ctx0, cur, il);
  6140. cb(cur, "l_out", il);
  6141. // input for next layer
  6142. inpL = cur;
  6143. }
  6144. cur = inpL;
  6145. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6146. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  6147. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6148. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM_RMS, cb, -1);
  6149. cb(cur, "result_norm", -1);
  6150. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  6151. cb(cur, "result_output", -1);
  6152. ggml_build_forward_expand(gf, cur);
  6153. return gf;
  6154. }
  6155. // ref: https://github.com/facebookresearch/chameleon
  6156. // based on the original build_llama() function, changes:
  6157. // * qk-norm
  6158. // * swin-norm
  6159. // * removed bias
  6160. // * removed MoE
  6161. struct ggml_cgraph * build_chameleon() {
  6162. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  6163. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6164. int32_t n_tokens = this->n_tokens;
  6165. const int64_t n_embd_head = hparams.n_embd_head_v;
  6166. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6167. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6168. struct ggml_tensor * cur;
  6169. struct ggml_tensor * inpL;
  6170. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  6171. // inp_pos - contains the positions
  6172. struct ggml_tensor * inp_pos = build_inp_pos();
  6173. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6174. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6175. for (int il = 0; il < n_layer; ++il) {
  6176. struct ggml_tensor * inpSA = inpL;
  6177. // norm
  6178. if (hparams.swin_norm) {
  6179. cur = inpL;
  6180. } else {
  6181. cur = llm_build_norm(ctx0, inpL, hparams,
  6182. model.layers[il].attn_norm, NULL,
  6183. LLM_NORM_RMS, cb, il);
  6184. cb(cur, "attn_norm", il);
  6185. }
  6186. // self-attention
  6187. {
  6188. // compute Q and K and RoPE them
  6189. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  6190. cb(Qcur, "Qcur", il);
  6191. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  6192. cb(Kcur, "Kcur", il);
  6193. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  6194. cb(Vcur, "Vcur", il);
  6195. if (model.layers[il].attn_q_norm) {
  6196. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  6197. ggml_element_size(Qcur) * n_embd_head,
  6198. ggml_element_size(Qcur) * n_embd_head * n_head,
  6199. 0);
  6200. cb(Qcur, "Qcur", il);
  6201. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  6202. model.layers[il].attn_q_norm,
  6203. model.layers[il].attn_q_norm_b,
  6204. LLM_NORM, cb, il);
  6205. cb(Qcur, "Qcur", il);
  6206. }
  6207. if (model.layers[il].attn_k_norm) {
  6208. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  6209. ggml_element_size(Kcur) * n_embd_head,
  6210. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  6211. 0);
  6212. cb(Kcur, "Kcur", il);
  6213. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  6214. model.layers[il].attn_k_norm,
  6215. model.layers[il].attn_k_norm_b,
  6216. LLM_NORM, cb, il);
  6217. cb(Kcur, "Kcur", il);
  6218. }
  6219. Qcur = ggml_rope_ext(
  6220. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  6221. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  6222. ext_factor, attn_factor, beta_fast, beta_slow
  6223. );
  6224. cb(Qcur, "Qcur", il);
  6225. Kcur = ggml_rope_ext(
  6226. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  6227. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  6228. ext_factor, attn_factor, beta_fast, beta_slow
  6229. );
  6230. cb(Kcur, "Kcur", il);
  6231. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  6232. model.layers[il].wo, nullptr,
  6233. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6234. if (hparams.swin_norm) {
  6235. cur = llm_build_norm(ctx0, cur, hparams,
  6236. model.layers[il].attn_norm, NULL,
  6237. LLM_NORM_RMS, cb, il);
  6238. }
  6239. }
  6240. if (il == n_layer - 1) {
  6241. // skip computing output for unused tokens
  6242. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6243. n_tokens = n_outputs;
  6244. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6245. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6246. }
  6247. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6248. cb(ffn_inp, "ffn_inp", il);
  6249. // feed-forward network
  6250. if (!hparams.swin_norm) {
  6251. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6252. model.layers[il].ffn_norm, NULL,
  6253. LLM_NORM_RMS, cb, il);
  6254. cb(cur, "ffn_norm", il);
  6255. }
  6256. cur = llm_build_ffn(ctx0, lctx, cur,
  6257. model.layers[il].ffn_up, NULL, NULL,
  6258. model.layers[il].ffn_gate, NULL, NULL,
  6259. model.layers[il].ffn_down, NULL, NULL,
  6260. NULL,
  6261. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6262. cb(cur, "ffn_out", il);
  6263. if (hparams.swin_norm) {
  6264. cur = llm_build_norm(ctx0, cur, hparams,
  6265. model.layers[il].ffn_norm, NULL,
  6266. LLM_NORM_RMS, cb, il);
  6267. cb(cur, "ffn_norm", il);
  6268. }
  6269. cur = ggml_add(ctx0, cur, ffn_inp);
  6270. cb(cur, "ffn_out", il);
  6271. cur = lctx.cvec.apply_to(ctx0, cur, il);
  6272. cb(cur, "l_out", il);
  6273. // input for next layer
  6274. inpL = cur;
  6275. }
  6276. cur = inpL;
  6277. cur = llm_build_norm(ctx0, cur, hparams,
  6278. model.output_norm, NULL,
  6279. LLM_NORM_RMS, cb, -1);
  6280. cb(cur, "result_norm", -1);
  6281. // lm_head
  6282. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  6283. cb(cur, "result_output_with_img_logits", -1);
  6284. // TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
  6285. // Needs to be removed once image outputs are supported.
  6286. int img_token_end_idx = 8196;
  6287. int img_token_start_idx = 4;
  6288. int num_img_tokens = img_token_end_idx - img_token_start_idx;
  6289. // creates 1d tensor of size num_img_tokens and values -FLT_MAX,
  6290. // which ensures that text token values are always at least larger than image token values
  6291. struct ggml_tensor * img_logits = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, num_img_tokens);
  6292. img_logits = ggml_clamp(ctx0, img_logits, -FLT_MAX, -FLT_MAX);
  6293. cb(img_logits, "img_logits", -1);
  6294. cur = ggml_set_1d(ctx0, cur, img_logits, ggml_element_size(cur) * img_token_start_idx);
  6295. cb(cur, "result_output", -1);
  6296. ggml_build_forward_expand(gf, cur);
  6297. return gf;
  6298. }
  6299. struct ggml_cgraph * build_wavtokenizer_dec() {
  6300. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, model.max_nodes(), false);
  6301. struct ggml_tensor * cur;
  6302. struct ggml_tensor * inpL;
  6303. inpL = llm_build_inp_embd(ctx0, lctx, hparams, ubatch, model.tok_embd, cb);
  6304. cur = ggml_cont(ctx0, ggml_transpose(ctx0, inpL));
  6305. cur = ggml_conv_1d_ph(ctx0, model.conv1d, cur, 1, 1);
  6306. cur = ggml_add(ctx0, cur, model.conv1d_b);
  6307. // posnet
  6308. for (uint32_t il = 0; il < hparams.posnet.n_layer; ++il) {
  6309. const auto & layer = model.layers[il].posnet;
  6310. inpL = cur;
  6311. switch (il) {
  6312. case 0:
  6313. case 1:
  6314. case 3:
  6315. case 4:
  6316. {
  6317. cur = llm_build_norm(ctx0, cur, hparams,
  6318. layer.norm1,
  6319. layer.norm1_b,
  6320. LLM_NORM_GROUP, cb, 0);
  6321. cur = ggml_mul(ctx0, ggml_sigmoid(ctx0, cur), cur);
  6322. cur = ggml_conv_1d_ph(ctx0, layer.conv1, cur, 1, 1);
  6323. cur = ggml_add(ctx0, cur, layer.conv1_b);
  6324. cur = llm_build_norm(ctx0, cur, hparams,
  6325. layer.norm2,
  6326. layer.norm2_b,
  6327. LLM_NORM_GROUP, cb, 0);
  6328. cur = ggml_mul(ctx0, ggml_sigmoid(ctx0, cur), cur);
  6329. cur = ggml_conv_1d_ph(ctx0, layer.conv2, cur, 1, 1);
  6330. cur = ggml_add(ctx0, cur, layer.conv2_b);
  6331. cur = ggml_add(ctx0, cur, inpL);
  6332. } break;
  6333. case 2:
  6334. {
  6335. cur = llm_build_norm(ctx0, cur, hparams,
  6336. layer.attn_norm,
  6337. layer.attn_norm_b,
  6338. LLM_NORM_GROUP, cb, 0);
  6339. struct ggml_tensor * q;
  6340. struct ggml_tensor * k;
  6341. struct ggml_tensor * v;
  6342. q = ggml_conv_1d_ph(ctx0, layer.attn_q, cur, 1, 1);
  6343. k = ggml_conv_1d_ph(ctx0, layer.attn_k, cur, 1, 1);
  6344. v = ggml_conv_1d_ph(ctx0, layer.attn_v, cur, 1, 1);
  6345. q = ggml_add(ctx0, q, layer.attn_q_b);
  6346. k = ggml_add(ctx0, k, layer.attn_k_b);
  6347. v = ggml_add(ctx0, v, layer.attn_v_b);
  6348. q = ggml_cont(ctx0, ggml_transpose(ctx0, q));
  6349. k = ggml_cont(ctx0, ggml_transpose(ctx0, k));
  6350. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6351. kq = ggml_soft_max_ext(ctx0, kq, nullptr, 1.0f/sqrtf(float(hparams.posnet.n_embd)), 0.0f);
  6352. cur = ggml_mul_mat(ctx0, kq, v);
  6353. cur = ggml_conv_1d_ph(ctx0, layer.attn_o, cur, 1, 1);
  6354. cur = ggml_add(ctx0, cur, layer.attn_o_b);
  6355. cur = ggml_add(ctx0, cur, inpL);
  6356. } break;
  6357. case 5:
  6358. {
  6359. cur = llm_build_norm(ctx0, cur, hparams,
  6360. layer.norm,
  6361. layer.norm_b,
  6362. LLM_NORM_GROUP, cb, 0);
  6363. } break;
  6364. default: GGML_ABORT("unknown posnet layer");
  6365. };
  6366. }
  6367. cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
  6368. cur = llm_build_norm(ctx0, cur, hparams,
  6369. model.tok_norm,
  6370. model.tok_norm_b,
  6371. LLM_NORM, cb, -1);
  6372. cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
  6373. inpL = cur;
  6374. // convnext
  6375. for (uint32_t il = 0; il < hparams.convnext.n_layer; ++il) {
  6376. const auto & layer = model.layers[il].convnext;
  6377. cur = inpL;
  6378. cur = ggml_conv_1d_dw_ph(ctx0, layer.dw, cur, 1, 1);
  6379. cur = ggml_add(ctx0, cur, layer.dw_b);
  6380. cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
  6381. cur = llm_build_norm(ctx0, cur, hparams,
  6382. layer.norm,
  6383. layer.norm_b,
  6384. LLM_NORM, cb, -1);
  6385. cur = llm_build_ffn(ctx0, lctx, cur,
  6386. layer.pw1, layer.pw1_b, NULL,
  6387. NULL, NULL, NULL,
  6388. layer.pw2, layer.pw2_b, NULL,
  6389. NULL,
  6390. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6391. cur = ggml_mul(ctx0, cur, layer.gamma);
  6392. cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
  6393. inpL = ggml_add(ctx0, cur, inpL);
  6394. }
  6395. cur = inpL;
  6396. cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur));
  6397. cur = llm_build_norm(ctx0, cur, hparams,
  6398. model.output_norm,
  6399. model.output_norm_b,
  6400. LLM_NORM, cb, -1);
  6401. // lm_head
  6402. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  6403. cur = ggml_add(ctx0, cur, model.output_b);
  6404. cb(cur, "result_embd", -1);
  6405. ggml_build_forward_expand(gf, cur);
  6406. return gf;
  6407. }
  6408. };
  6409. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  6410. llama_ubatch dummy = {};
  6411. dummy.equal_seqs = true;
  6412. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6413. struct llm_build_context llm(lctx, dummy, cb, false);
  6414. llm.init();
  6415. struct ggml_cgraph * result = llm.build_defrag(ids);
  6416. llm.free();
  6417. return result;
  6418. }
  6419. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  6420. llama_ubatch dummy = {};
  6421. dummy.equal_seqs = true;
  6422. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6423. struct llm_build_context llm(lctx, dummy, cb, false);
  6424. llm.init();
  6425. struct ggml_cgraph * result = llm.build_k_shift();
  6426. llm.free();
  6427. return result;
  6428. }
  6429. static struct ggml_cgraph * llama_build_graph(
  6430. llama_context & lctx,
  6431. const llama_ubatch & ubatch,
  6432. bool worst_case) {
  6433. const auto & model = lctx.model;
  6434. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6435. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6436. if (il >= 0) {
  6437. ggml_format_name(cur, "%s-%d", name, il);
  6438. } else {
  6439. ggml_set_name(cur, name);
  6440. }
  6441. if (!lctx.cparams.offload_kqv) {
  6442. if (strcmp(name, "kqv_merged_cont") == 0) {
  6443. // all nodes between the KV store and the attention output are run on the CPU
  6444. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, lctx.backend_cpu);
  6445. }
  6446. }
  6447. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  6448. // FIXME: fix in ggml_backend_sched
  6449. const bool full_offload = lctx.model.params.n_gpu_layers > (int) lctx.model.hparams.n_layer;
  6450. if (ubatch.n_tokens < 32 || full_offload) {
  6451. if (il != -1 && strcmp(name, "norm") == 0) {
  6452. const auto & dev_layer = lctx.model.dev_layer(il);
  6453. for (auto & backend : lctx.backends) {
  6454. if (ggml_backend_get_device(backend.get()) == dev_layer) {
  6455. if (ggml_backend_supports_op(backend.get(), cur)) {
  6456. ggml_backend_sched_set_tensor_backend(lctx.sched.get(), cur, backend.get());
  6457. }
  6458. }
  6459. }
  6460. }
  6461. }
  6462. };
  6463. struct ggml_cgraph * result = NULL;
  6464. struct llm_build_context llm(lctx, ubatch, cb, worst_case);
  6465. llm.init();
  6466. switch (model.arch) {
  6467. case LLM_ARCH_LLAMA:
  6468. case LLM_ARCH_MINICPM:
  6469. case LLM_ARCH_GRANITE:
  6470. case LLM_ARCH_GRANITE_MOE:
  6471. {
  6472. result = llm.build_llama();
  6473. } break;
  6474. case LLM_ARCH_DECI:
  6475. {
  6476. result = llm.build_deci();
  6477. } break;
  6478. case LLM_ARCH_BAICHUAN:
  6479. {
  6480. result = llm.build_baichuan();
  6481. } break;
  6482. case LLM_ARCH_FALCON:
  6483. {
  6484. result = llm.build_falcon();
  6485. } break;
  6486. case LLM_ARCH_GROK:
  6487. {
  6488. result = llm.build_grok();
  6489. } break;
  6490. case LLM_ARCH_STARCODER:
  6491. {
  6492. result = llm.build_starcoder();
  6493. } break;
  6494. case LLM_ARCH_REFACT:
  6495. {
  6496. result = llm.build_refact();
  6497. } break;
  6498. case LLM_ARCH_BERT:
  6499. case LLM_ARCH_JINA_BERT_V2:
  6500. case LLM_ARCH_NOMIC_BERT:
  6501. {
  6502. result = llm.build_bert();
  6503. } break;
  6504. case LLM_ARCH_BLOOM:
  6505. {
  6506. result = llm.build_bloom();
  6507. } break;
  6508. case LLM_ARCH_MPT:
  6509. {
  6510. result = llm.build_mpt();
  6511. } break;
  6512. case LLM_ARCH_STABLELM:
  6513. {
  6514. result = llm.build_stablelm();
  6515. } break;
  6516. case LLM_ARCH_QWEN:
  6517. {
  6518. result = llm.build_qwen();
  6519. } break;
  6520. case LLM_ARCH_QWEN2:
  6521. {
  6522. result = llm.build_qwen2();
  6523. } break;
  6524. case LLM_ARCH_QWEN2VL:
  6525. {
  6526. lctx.n_pos_per_token = 4;
  6527. result = llm.build_qwen2vl();
  6528. } break;
  6529. case LLM_ARCH_QWEN2MOE:
  6530. {
  6531. result = llm.build_qwen2moe();
  6532. } break;
  6533. case LLM_ARCH_PHI2:
  6534. {
  6535. result = llm.build_phi2();
  6536. } break;
  6537. case LLM_ARCH_PHI3:
  6538. case LLM_ARCH_PHIMOE:
  6539. {
  6540. result = llm.build_phi3();
  6541. } break;
  6542. case LLM_ARCH_PLAMO:
  6543. {
  6544. result = llm.build_plamo();
  6545. } break;
  6546. case LLM_ARCH_GPT2:
  6547. {
  6548. result = llm.build_gpt2();
  6549. } break;
  6550. case LLM_ARCH_CODESHELL:
  6551. {
  6552. result = llm.build_codeshell();
  6553. } break;
  6554. case LLM_ARCH_ORION:
  6555. {
  6556. result = llm.build_orion();
  6557. } break;
  6558. case LLM_ARCH_INTERNLM2:
  6559. {
  6560. result = llm.build_internlm2();
  6561. } break;
  6562. case LLM_ARCH_MINICPM3:
  6563. {
  6564. result = llm.build_minicpm3();
  6565. } break;
  6566. case LLM_ARCH_GEMMA:
  6567. {
  6568. result = llm.build_gemma();
  6569. } break;
  6570. case LLM_ARCH_GEMMA2:
  6571. {
  6572. result = llm.build_gemma2();
  6573. } break;
  6574. case LLM_ARCH_STARCODER2:
  6575. {
  6576. result = llm.build_starcoder2();
  6577. } break;
  6578. case LLM_ARCH_MAMBA:
  6579. {
  6580. result = llm.build_mamba();
  6581. } break;
  6582. case LLM_ARCH_XVERSE:
  6583. {
  6584. result = llm.build_xverse();
  6585. } break;
  6586. case LLM_ARCH_COMMAND_R:
  6587. {
  6588. result = llm.build_command_r();
  6589. } break;
  6590. case LLM_ARCH_COHERE2:
  6591. {
  6592. result = llm.build_cohere2();
  6593. } break;
  6594. case LLM_ARCH_DBRX:
  6595. {
  6596. result = llm.build_dbrx();
  6597. } break;
  6598. case LLM_ARCH_OLMO:
  6599. {
  6600. result = llm.build_olmo();
  6601. } break;
  6602. case LLM_ARCH_OLMO2:
  6603. {
  6604. result = llm.build_olmo2();
  6605. } break;
  6606. case LLM_ARCH_OLMOE:
  6607. {
  6608. result = llm.build_olmoe();
  6609. } break;
  6610. case LLM_ARCH_OPENELM:
  6611. {
  6612. result = llm.build_openelm();
  6613. } break;
  6614. case LLM_ARCH_GPTNEOX:
  6615. {
  6616. result = llm.build_gptneox();
  6617. } break;
  6618. case LLM_ARCH_ARCTIC:
  6619. {
  6620. result = llm.build_arctic();
  6621. } break;
  6622. case LLM_ARCH_DEEPSEEK:
  6623. {
  6624. result = llm.build_deepseek();
  6625. } break;
  6626. case LLM_ARCH_DEEPSEEK2:
  6627. {
  6628. result = llm.build_deepseek2();
  6629. } break;
  6630. case LLM_ARCH_CHATGLM:
  6631. {
  6632. result = llm.build_chatglm();
  6633. } break;
  6634. case LLM_ARCH_BITNET:
  6635. {
  6636. result = llm.build_bitnet();
  6637. } break;
  6638. case LLM_ARCH_T5:
  6639. {
  6640. if (lctx.is_encoding) {
  6641. result = llm.build_t5_enc();
  6642. } else {
  6643. result = llm.build_t5_dec();
  6644. }
  6645. } break;
  6646. case LLM_ARCH_T5ENCODER:
  6647. {
  6648. result = llm.build_t5_enc();
  6649. } break;
  6650. case LLM_ARCH_JAIS:
  6651. {
  6652. result = llm.build_jais();
  6653. } break;
  6654. case LLM_ARCH_NEMOTRON:
  6655. {
  6656. result = llm.build_nemotron();
  6657. } break;
  6658. case LLM_ARCH_EXAONE:
  6659. {
  6660. result = llm.build_exaone();
  6661. } break;
  6662. case LLM_ARCH_RWKV6:
  6663. {
  6664. result = llm.build_rwkv6();
  6665. } break;
  6666. case LLM_ARCH_RWKV6QWEN2:
  6667. {
  6668. result = llm.build_rwkv6qwen2();
  6669. } break;
  6670. case LLM_ARCH_CHAMELEON:
  6671. {
  6672. result = llm.build_chameleon();
  6673. } break;
  6674. case LLM_ARCH_WAVTOKENIZER_DEC:
  6675. {
  6676. result = llm.build_wavtokenizer_dec();
  6677. } break;
  6678. default:
  6679. GGML_ABORT("fatal error");
  6680. }
  6681. // add on pooling layer
  6682. if (lctx.cparams.embeddings) {
  6683. result = llm.append_pooling(result);
  6684. }
  6685. llm.free();
  6686. return result;
  6687. }
  6688. // returns the result of ggml_backend_sched_graph_compute_async execution
  6689. static enum ggml_status llama_graph_compute(
  6690. llama_context & lctx,
  6691. ggml_cgraph * gf,
  6692. int n_threads,
  6693. ggml_threadpool * threadpool) {
  6694. if (lctx.backend_cpu != nullptr) {
  6695. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(lctx.backend_cpu));
  6696. auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
  6697. set_threadpool_fn(lctx.backend_cpu, threadpool);
  6698. }
  6699. // set the number of threads for all the backends
  6700. for (const auto & set_n_threads_fn : lctx.set_n_threads_fns) {
  6701. set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
  6702. }
  6703. auto status = ggml_backend_sched_graph_compute_async(lctx.sched.get(), gf);
  6704. if (status != GGML_STATUS_SUCCESS) {
  6705. LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
  6706. }
  6707. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6708. return status;
  6709. }
  6710. static int llama_prepare_sbatch(
  6711. llama_context & lctx,
  6712. const llama_batch & batch,
  6713. uint32_t & n_outputs) {
  6714. const auto & model = lctx.model;
  6715. const auto & hparams = model.hparams;
  6716. const auto & cparams = lctx.cparams;
  6717. const uint32_t n_tokens_all = batch.n_tokens;
  6718. const int64_t n_embd = hparams.n_embd;
  6719. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  6720. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  6721. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6722. if (batch.token) {
  6723. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  6724. if (batch.token[i] < 0 || uint32_t(batch.token[i]) >= model.vocab.n_tokens()) {
  6725. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  6726. return -1;
  6727. }
  6728. }
  6729. }
  6730. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  6731. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  6732. lctx.n_queued_tokens += n_tokens_all;
  6733. lctx.embd_seq.clear();
  6734. // count outputs
  6735. if (batch.logits && !embd_pooled) {
  6736. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  6737. n_outputs += batch.logits[i] != 0;
  6738. }
  6739. } else if (lctx.logits_all || embd_pooled) {
  6740. n_outputs = n_tokens_all;
  6741. } else {
  6742. // keep last output only
  6743. n_outputs = 1;
  6744. }
  6745. lctx.sbatch.from_batch(batch, n_embd,
  6746. /* simple_split */ !lctx.kv_self.recurrent,
  6747. /* logits_all */ n_outputs == n_tokens_all);
  6748. // reserve output buffer
  6749. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  6750. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  6751. return -2;
  6752. };
  6753. return 0;
  6754. }
  6755. static int llama_prepare_ubatch(
  6756. llama_context & lctx,
  6757. llama_kv_slot_restorer & kv_slot_restorer,
  6758. llama_ubatch & ubatch,
  6759. const uint32_t n_outputs,
  6760. const uint32_t n_tokens_all) {
  6761. GGML_ASSERT(lctx.sbatch.n_tokens > 0);
  6762. auto & kv_self = lctx.kv_self;
  6763. const auto & cparams = lctx.cparams;
  6764. const auto & hparams = lctx.model.hparams;
  6765. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  6766. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  6767. if (lctx.kv_self.recurrent) {
  6768. if (embd_pooled) {
  6769. // Pooled embeddings cannot be split across ubatches (yet)
  6770. ubatch = lctx.sbatch.split_seq(cparams.n_ubatch);
  6771. } else {
  6772. // recurrent model architectures are easier to implement
  6773. // with equal-length sequences
  6774. ubatch = lctx.sbatch.split_equal(cparams.n_ubatch);
  6775. }
  6776. } else {
  6777. ubatch = lctx.sbatch.split_simple(cparams.n_ubatch);
  6778. }
  6779. // count the outputs in this u_batch
  6780. {
  6781. int32_t n_outputs_new = 0;
  6782. if (n_outputs == n_tokens_all) {
  6783. n_outputs_new = ubatch.n_tokens;
  6784. } else {
  6785. GGML_ASSERT(ubatch.output);
  6786. for (uint32_t i = 0; i < ubatch.n_tokens; i++) {
  6787. n_outputs_new += int32_t(ubatch.output[i] != 0);
  6788. }
  6789. }
  6790. // needs to happen before the graph is built
  6791. lctx.n_outputs = n_outputs_new;
  6792. }
  6793. // non-causal masks do not use the KV cache
  6794. if (hparams.causal_attn) {
  6795. llama_kv_cache_update(&lctx);
  6796. // if we have enough unused cells before the current head ->
  6797. // better to start searching from the beginning of the cache, hoping to fill it
  6798. if (kv_self.head > kv_self.used + 2*ubatch.n_tokens) {
  6799. kv_self.head = 0;
  6800. }
  6801. const auto slot = llama_kv_cache_find_slot(kv_self, ubatch);
  6802. if (!slot) {
  6803. return 1;
  6804. }
  6805. kv_slot_restorer.save(slot);
  6806. if (!kv_self.recurrent) {
  6807. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6808. // after enough generations, the benefit from this heuristic disappears
  6809. // if we start defragmenting the cache, the benefit from this will be more important
  6810. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  6811. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  6812. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6813. }
  6814. }
  6815. return 0;
  6816. }
  6817. // decode a batch of tokens by evaluating the transformer
  6818. // in case of unsuccessful decoding (error or warning),
  6819. // the kv_cache state will be returned to its original state
  6820. // (for non-recurrent models) or cleaned (for recurrent models)
  6821. //
  6822. // - lctx: llama context
  6823. // - inp_batch: batch to evaluate
  6824. //
  6825. // return 0 on success
  6826. // return positive int on warning
  6827. // return negative int on error
  6828. //
  6829. static int llama_decode_impl(
  6830. llama_context & lctx,
  6831. llama_batch inp_batch) {
  6832. lctx.is_encoding = false;
  6833. if (inp_batch.n_tokens == 0) {
  6834. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  6835. return -1;
  6836. }
  6837. // temporarily allocate memory for the input batch if needed
  6838. llama_batch_allocr batch_allocr(inp_batch, inp_batch.pos ? -1 : lctx.kv_self.max_pos() + 1);
  6839. const llama_batch & batch = batch_allocr.batch;
  6840. const auto & model = lctx.model;
  6841. const auto & vocab = model.vocab;
  6842. const auto & hparams = model.hparams;
  6843. const auto & cparams = lctx.cparams;
  6844. if (lctx.t_compute_start_us == 0) {
  6845. lctx.t_compute_start_us = ggml_time_us();
  6846. }
  6847. auto & kv_self = lctx.kv_self;
  6848. llama_kv_slot_restorer kv_slot_restorer(kv_self);
  6849. const int64_t n_embd = hparams.n_embd;
  6850. const int64_t n_vocab = vocab.n_tokens();
  6851. uint32_t n_outputs = 0;
  6852. uint32_t n_outputs_prev = 0;
  6853. {
  6854. const int ret = llama_prepare_sbatch(lctx, batch, n_outputs);
  6855. if (ret != 0) {
  6856. return ret;
  6857. }
  6858. }
  6859. while (lctx.sbatch.n_tokens > 0) {
  6860. llama_ubatch ubatch;
  6861. {
  6862. const int ret = llama_prepare_ubatch(lctx, kv_slot_restorer, ubatch, n_outputs, batch.n_tokens);
  6863. if (ret != 0) {
  6864. return ret;
  6865. }
  6866. }
  6867. const int n_threads = ubatch.n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6868. ggml_threadpool_t threadpool = ubatch.n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  6869. GGML_ASSERT(n_threads > 0);
  6870. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6871. ggml_backend_sched_reset(lctx.sched.get());
  6872. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6873. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  6874. // the output is always the last tensor in the graph
  6875. struct ggml_tensor * res = ggml_graph_node(gf, -1);
  6876. struct ggml_tensor * embd = ggml_graph_node(gf, -2);
  6877. if (lctx.n_outputs == 0) {
  6878. // no output
  6879. res = nullptr;
  6880. embd = nullptr;
  6881. } else if (cparams.embeddings) {
  6882. res = nullptr; // do not extract logits for embedding case
  6883. embd = nullptr;
  6884. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  6885. if (strcmp(ggml_graph_node(gf, i)->name, "result_embd_pooled") == 0) {
  6886. embd = ggml_graph_node(gf, i);
  6887. break;
  6888. }
  6889. }
  6890. GGML_ASSERT(embd != nullptr && "missing embeddings tensor");
  6891. } else {
  6892. embd = nullptr; // do not extract embeddings when not needed
  6893. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  6894. }
  6895. // LLAMA_LOG_INFO("graph build time: %.3f ms (%d nodes, %d leafs)\n", (ggml_time_us() - t_start_us)/1000.0, gf->n_nodes, gf->n_leafs);
  6896. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  6897. llama_set_inputs(lctx, ubatch);
  6898. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  6899. if (compute_status != GGML_STATUS_SUCCESS) {
  6900. kv_slot_restorer.restore(kv_self);
  6901. switch (compute_status) {
  6902. case GGML_STATUS_ABORTED:
  6903. return 2;
  6904. case GGML_STATUS_ALLOC_FAILED:
  6905. return -2;
  6906. case GGML_STATUS_FAILED:
  6907. default:
  6908. return -3;
  6909. }
  6910. }
  6911. // update the kv ring buffer
  6912. {
  6913. kv_self.head += ubatch.n_tokens;
  6914. // Ensure kv cache head points to a valid index.
  6915. if (kv_self.head >= kv_self.size) {
  6916. kv_self.head = 0;
  6917. }
  6918. }
  6919. // plot the computation graph in dot format (for debugging purposes)
  6920. //if (n_past%100 == 0) {
  6921. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6922. //}
  6923. // extract logits
  6924. if (res) {
  6925. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), res);
  6926. GGML_ASSERT(backend_res != nullptr);
  6927. GGML_ASSERT(lctx.logits != nullptr);
  6928. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  6929. const int32_t n_outputs_new = lctx.n_outputs;
  6930. if (n_outputs_new) {
  6931. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  6932. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  6933. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  6934. }
  6935. }
  6936. // extract embeddings
  6937. if (embd) {
  6938. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  6939. GGML_ASSERT(backend_embd != nullptr);
  6940. switch (cparams.pooling_type) {
  6941. case LLAMA_POOLING_TYPE_NONE:
  6942. {
  6943. // extract token embeddings
  6944. GGML_ASSERT(lctx.embd != nullptr);
  6945. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  6946. const int32_t n_outputs_new = lctx.n_outputs;
  6947. if (n_outputs_new) {
  6948. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  6949. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  6950. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  6951. }
  6952. } break;
  6953. case LLAMA_POOLING_TYPE_MEAN:
  6954. case LLAMA_POOLING_TYPE_CLS:
  6955. case LLAMA_POOLING_TYPE_LAST:
  6956. {
  6957. // extract sequence embeddings (cleared before processing each batch)
  6958. auto & embd_seq_out = lctx.embd_seq;
  6959. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  6960. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  6961. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  6962. continue;
  6963. }
  6964. embd_seq_out[seq_id].resize(n_embd);
  6965. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  6966. }
  6967. } break;
  6968. case LLAMA_POOLING_TYPE_RANK:
  6969. {
  6970. // extract the rerank score - a single float per sequence
  6971. auto & embd_seq_out = lctx.embd_seq;
  6972. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  6973. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  6974. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  6975. continue;
  6976. }
  6977. embd_seq_out[seq_id].resize(1);
  6978. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (seq_id)*sizeof(float), sizeof(float));
  6979. }
  6980. } break;
  6981. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6982. {
  6983. GGML_ABORT("unknown pooling type");
  6984. }
  6985. }
  6986. }
  6987. n_outputs_prev += lctx.n_outputs;
  6988. }
  6989. // set output mappings
  6990. {
  6991. bool sorted_output = true;
  6992. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  6993. for (size_t i = 0; i < n_outputs; ++i) {
  6994. size_t out_id = lctx.sbatch.out_ids[i];
  6995. lctx.output_ids[out_id] = i;
  6996. if (out_id != i) {
  6997. sorted_output = false;
  6998. }
  6999. }
  7000. if (sorted_output) {
  7001. lctx.sbatch.out_ids.clear();
  7002. }
  7003. }
  7004. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  7005. lctx.n_outputs = n_outputs;
  7006. // wait for the computation to finish (automatically done when obtaining the model output)
  7007. //llama_synchronize(&lctx);
  7008. // decide if we need to defrag the kv cache
  7009. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  7010. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  7011. // queue defragmentation for next llama_kv_cache_update
  7012. if (fragmentation > cparams.defrag_thold) {
  7013. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  7014. llama_kv_cache_defrag(kv_self);
  7015. }
  7016. }
  7017. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  7018. // overlap with device computation.
  7019. ggml_backend_sched_reset(lctx.sched.get());
  7020. return 0;
  7021. }
  7022. // encode a batch of tokens by evaluating the encoder part of the transformer
  7023. //
  7024. // - lctx: llama context
  7025. // - batch: batch to evaluate
  7026. //
  7027. // return 0 on success
  7028. // return positive int on warning
  7029. // return negative int on error
  7030. //
  7031. static int llama_encode_impl(
  7032. llama_context & lctx,
  7033. llama_batch inp_batch) {
  7034. lctx.is_encoding = true;
  7035. if (inp_batch.n_tokens == 0) {
  7036. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  7037. return -1;
  7038. }
  7039. // temporary allocate memory for the input batch if needed
  7040. llama_batch_allocr batch_allocr(inp_batch, inp_batch.pos ? -1 : lctx.kv_self.max_pos() + 1);
  7041. const llama_batch & batch = batch_allocr.batch;
  7042. const uint32_t n_tokens = batch.n_tokens;
  7043. const auto & model = lctx.model;
  7044. const auto & hparams = model.hparams;
  7045. const auto & cparams = lctx.cparams;
  7046. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  7047. if (batch.token) {
  7048. for (uint32_t i = 0; i < n_tokens; ++i) {
  7049. if (batch.token[i] < 0 || (uint32_t) batch.token[i] >= model.vocab.n_tokens()) {
  7050. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  7051. return -1;
  7052. }
  7053. }
  7054. }
  7055. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  7056. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  7057. if (lctx.t_compute_start_us == 0) {
  7058. lctx.t_compute_start_us = ggml_time_us();
  7059. }
  7060. lctx.n_queued_tokens += n_tokens;
  7061. const int64_t n_embd = hparams.n_embd;
  7062. lctx.sbatch.from_batch(batch, n_embd, /* simple_split */ true, /* logits_all */ true);
  7063. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  7064. // reserve output buffer
  7065. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  7066. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  7067. return -2;
  7068. };
  7069. for (uint32_t i = 0; i < n_tokens; ++i) {
  7070. lctx.output_ids[i] = i;
  7071. }
  7072. lctx.inp_embd_enc = NULL;
  7073. lctx.n_outputs = n_tokens;
  7074. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  7075. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  7076. GGML_ASSERT(n_threads > 0);
  7077. ggml_backend_sched_reset(lctx.sched.get());
  7078. ggml_backend_sched_set_eval_callback(lctx.sched.get(), lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  7079. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  7080. // the output embeddings after the final encoder normalization
  7081. struct ggml_tensor * embd = nullptr;
  7082. // there are two cases here
  7083. if (llama_model_has_decoder(&lctx.model)) {
  7084. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  7085. embd = ggml_graph_node(gf, -1);
  7086. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  7087. } else {
  7088. // second case is an encoder-only T5 model
  7089. if (cparams.embeddings) {
  7090. // only output embeddings if required
  7091. embd = ggml_graph_node(gf, -1);
  7092. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  7093. embd = ggml_graph_node(gf, -2);
  7094. }
  7095. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  7096. }
  7097. }
  7098. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  7099. llama_set_inputs(lctx, ubatch);
  7100. const auto compute_status = llama_graph_compute(lctx, gf, n_threads, threadpool);
  7101. switch (compute_status) {
  7102. case GGML_STATUS_SUCCESS:
  7103. break;
  7104. case GGML_STATUS_ABORTED:
  7105. return 2;
  7106. case GGML_STATUS_ALLOC_FAILED:
  7107. return -2;
  7108. case GGML_STATUS_FAILED:
  7109. default:
  7110. return -3;
  7111. }
  7112. // extract embeddings
  7113. if (embd) {
  7114. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched.get(), embd);
  7115. GGML_ASSERT(backend_embd != nullptr);
  7116. if (llama_model_has_decoder(&lctx.model)) {
  7117. lctx.embd_enc.resize(n_tokens*n_embd);
  7118. float * embd_out = lctx.embd_enc.data();
  7119. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  7120. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  7121. // remember the sequence ids used during the encoding - needed for cross attention later
  7122. lctx.seq_ids_enc.resize(n_tokens);
  7123. for (uint32_t i = 0; i < n_tokens; i++) {
  7124. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  7125. llama_seq_id seq_id = ubatch.seq_id[i][s];
  7126. lctx.seq_ids_enc[i].insert(seq_id);
  7127. }
  7128. }
  7129. } else {
  7130. GGML_ASSERT(lctx.embd != nullptr);
  7131. switch (cparams.pooling_type) {
  7132. case LLAMA_POOLING_TYPE_NONE:
  7133. {
  7134. // extract token embeddings
  7135. GGML_ASSERT(lctx.embd != nullptr);
  7136. float * embd_out = lctx.embd;
  7137. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  7138. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  7139. } break;
  7140. case LLAMA_POOLING_TYPE_MEAN:
  7141. case LLAMA_POOLING_TYPE_CLS:
  7142. case LLAMA_POOLING_TYPE_LAST:
  7143. {
  7144. // extract sequence embeddings
  7145. auto & embd_seq_out = lctx.embd_seq;
  7146. embd_seq_out.clear();
  7147. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  7148. for (uint32_t i = 0; i < n_tokens; i++) {
  7149. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  7150. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  7151. continue;
  7152. }
  7153. embd_seq_out[seq_id].resize(n_embd);
  7154. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  7155. }
  7156. } break;
  7157. case LLAMA_POOLING_TYPE_RANK:
  7158. {
  7159. // TODO: this likely should be the same logic as in llama_decoder_internal, but better to
  7160. // wait for an encoder model that requires this pooling type in order to test it
  7161. // https://github.com/ggerganov/llama.cpp/pull/9510
  7162. GGML_ABORT("RANK pooling not implemented yet");
  7163. }
  7164. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  7165. {
  7166. GGML_ABORT("unknown pooling type");
  7167. }
  7168. }
  7169. }
  7170. }
  7171. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  7172. // overlap with device computation.
  7173. ggml_backend_sched_reset(lctx.sched.get());
  7174. return 0;
  7175. }
  7176. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  7177. static void llama_kv_cache_defrag_impl(struct llama_context & lctx) {
  7178. auto & kv_self = lctx.kv_self;
  7179. const auto & hparams = lctx.model.hparams;
  7180. const uint32_t n_layer = hparams.n_layer;
  7181. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  7182. const uint32_t n_used = kv_self.used;
  7183. assert(n_used <= n_kv);
  7184. //const int64_t t_start = ggml_time_us();
  7185. // number of cells moved
  7186. uint32_t n_moves = 0;
  7187. // each move requires 6*n_layer tensors (see build_defrag)
  7188. // - source view, destination view, copy operation
  7189. // - x2 for keys and values
  7190. //const uint32_t max_moves = model.max_nodes()/(6*n_layer);
  7191. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  7192. const uint32_t max_moves = (lctx.model.max_nodes() - 2*n_layer)/(6*n_layer);
  7193. // determine which KV cells to move where
  7194. //
  7195. // cell i moves to ids[i]
  7196. //
  7197. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  7198. //
  7199. std::vector<uint32_t> ids(n_kv, n_kv);
  7200. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  7201. const auto & cell0 = kv_self.cells[i0];
  7202. if (!cell0.is_empty()) {
  7203. ids[i0] = i0;
  7204. continue;
  7205. }
  7206. // found a hole - fill it with data from the end of the cache
  7207. uint32_t nh = 1;
  7208. // determine the size of the hole
  7209. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  7210. nh++;
  7211. }
  7212. uint32_t nf = 0;
  7213. uint32_t is = n_kv - 1;
  7214. // starting from the end, find nh non-empty cells
  7215. for (; is > i0; --is) {
  7216. const auto & cell1 = kv_self.cells[is];
  7217. if (cell1.is_empty() || ids[is] != n_kv) {
  7218. continue;
  7219. }
  7220. // non-empty cell which is not yet moved
  7221. nf++;
  7222. if (nf == nh) {
  7223. break;
  7224. }
  7225. }
  7226. // this can only happen if `n_used` is not accurate, which would be a bug
  7227. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  7228. nf = 0;
  7229. uint32_t i1 = is;
  7230. // are we moving a continuous block of memory?
  7231. bool cont = false;
  7232. // should we stop searching for the next move?
  7233. bool stop = false;
  7234. // go back and move the nf cells to the hole
  7235. for (; i1 < n_kv; ++i1) {
  7236. auto & cell1 = kv_self.cells[i1];
  7237. if (cell1.is_empty() || ids[i1] != n_kv) {
  7238. if (n_moves == max_moves) {
  7239. stop = true;
  7240. break;
  7241. }
  7242. cont = false;
  7243. continue;
  7244. }
  7245. // this cell goes to (i0 + nf)
  7246. ids[i1] = i0 + nf;
  7247. // move the cell meta data
  7248. kv_self.cells[i0 + nf] = cell1;
  7249. // clear the old cell and move the head there
  7250. cell1 = llama_kv_cell();
  7251. kv_self.head = n_used;
  7252. if (!cont) {
  7253. n_moves++;
  7254. cont = true;
  7255. }
  7256. nf++;
  7257. if (nf == nh) {
  7258. break;
  7259. }
  7260. }
  7261. if (stop || n_moves == max_moves) {
  7262. break;
  7263. }
  7264. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  7265. i0 += nh - 1;
  7266. }
  7267. if (n_moves == 0) {
  7268. return;
  7269. }
  7270. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  7271. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  7272. #if 0
  7273. // CPU defrag
  7274. //
  7275. // TODO: optimizations are possible:
  7276. // - multiple threads
  7277. // - avoid copying to the host memory when already there
  7278. //
  7279. // likely not worth the effort, as we have ggml_graph based defrag
  7280. //
  7281. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  7282. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  7283. const uint32_t kv_size = kv_self.size;
  7284. std::vector<uint8_t> buf_k;
  7285. std::vector<uint8_t> buf_v;
  7286. for (uint32_t il = 0; il < n_layer; ++il) {
  7287. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  7288. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  7289. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  7290. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  7291. buf_k.resize(k_size);
  7292. buf_v.resize(v_size);
  7293. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7294. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7295. // batch move [i, i+nm) to [id, id+nm)
  7296. // note: cells can move only to a lower index
  7297. for (uint32_t i = 0; i < n_kv; ++i) {
  7298. const uint32_t id = ids[i];
  7299. if (i == id || id == n_kv) {
  7300. continue;
  7301. }
  7302. uint32_t nm = 1;
  7303. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  7304. nm++;
  7305. }
  7306. // move keys
  7307. {
  7308. const int64_t os = i*k_size_row;
  7309. const int64_t od = id*k_size_row;
  7310. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  7311. }
  7312. // move values (note: they are transposed)
  7313. {
  7314. const int64_t os = i;
  7315. const int64_t od = id;
  7316. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  7317. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  7318. }
  7319. }
  7320. i += nm - 1;
  7321. }
  7322. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7323. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7324. }
  7325. #else
  7326. // ggml_graph defrag
  7327. ggml_backend_sched_reset(lctx.sched.get());
  7328. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  7329. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  7330. #endif
  7331. //const int64_t t_end = ggml_time_us();
  7332. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  7333. }
  7334. static void llama_kv_cache_update_impl(struct llama_context & lctx) {
  7335. bool need_reserve = false;
  7336. if (lctx.kv_self.has_shift) {
  7337. if (!llama_kv_cache_can_shift(&lctx)) {
  7338. GGML_ABORT("The current context does not support K-shift");
  7339. }
  7340. // apply K-shift if needed
  7341. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
  7342. ggml_backend_sched_reset(lctx.sched.get());
  7343. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  7344. ggml_backend_sched_alloc_graph(lctx.sched.get(), gf);
  7345. llama_set_k_shift(lctx);
  7346. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  7347. need_reserve = true;
  7348. }
  7349. {
  7350. auto & kv_self = lctx.kv_self;
  7351. kv_self.has_shift = false;
  7352. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7353. kv_self.cells[i].delta = 0;
  7354. }
  7355. }
  7356. }
  7357. // defragment the KV cache if needed
  7358. if (lctx.kv_self.do_defrag) {
  7359. llama_kv_cache_defrag_impl(lctx);
  7360. need_reserve = true;
  7361. lctx.kv_self.do_defrag = false;
  7362. }
  7363. // reserve a worst case graph again
  7364. if (need_reserve) {
  7365. // TODO: extract to a function
  7366. // build worst-case graph
  7367. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  7368. uint32_t n_tokens = std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  7369. llama_token token = lctx.model.vocab.token_bos(); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  7370. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  7371. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, true);
  7372. // initialize scheduler with the worst-case graph
  7373. ggml_backend_sched_reset(lctx.sched.get());
  7374. if (!ggml_backend_sched_reserve(lctx.sched.get(), gf)) {
  7375. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  7376. }
  7377. }
  7378. }
  7379. int32_t llama_set_adapter_lora(
  7380. struct llama_context * ctx,
  7381. struct llama_adapter_lora * adapter,
  7382. float scale) {
  7383. ctx->lora[adapter] = scale;
  7384. return 0;
  7385. }
  7386. int32_t llama_rm_adapter_lora(
  7387. struct llama_context * ctx,
  7388. struct llama_adapter_lora * adapter) {
  7389. auto pos = ctx->lora.find(adapter);
  7390. if (pos != ctx->lora.end()) {
  7391. ctx->lora.erase(pos);
  7392. return 0;
  7393. }
  7394. return -1;
  7395. }
  7396. void llama_clear_adapter_lora(struct llama_context * ctx) {
  7397. ctx->lora.clear();
  7398. }
  7399. int32_t llama_apply_adapter_cvec(
  7400. struct llama_context * ctx,
  7401. const float * data,
  7402. size_t len,
  7403. int32_t n_embd,
  7404. int32_t il_start,
  7405. int32_t il_end) {
  7406. return ctx->cvec.apply(ctx->model, data, len, n_embd, il_start, il_end);
  7407. }
  7408. //
  7409. // interface implementation
  7410. //
  7411. struct llama_context_params llama_context_default_params() {
  7412. struct llama_context_params result = {
  7413. /*.n_ctx =*/ 512,
  7414. /*.n_batch =*/ 2048,
  7415. /*.n_ubatch =*/ 512,
  7416. /*.n_seq_max =*/ 1,
  7417. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  7418. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  7419. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  7420. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  7421. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  7422. /*.rope_freq_base =*/ 0.0f,
  7423. /*.rope_freq_scale =*/ 0.0f,
  7424. /*.yarn_ext_factor =*/ -1.0f,
  7425. /*.yarn_attn_factor =*/ 1.0f,
  7426. /*.yarn_beta_fast =*/ 32.0f,
  7427. /*.yarn_beta_slow =*/ 1.0f,
  7428. /*.yarn_orig_ctx =*/ 0,
  7429. /*.defrag_thold =*/ -1.0f,
  7430. /*.cb_eval =*/ nullptr,
  7431. /*.cb_eval_user_data =*/ nullptr,
  7432. /*.type_k =*/ GGML_TYPE_F16,
  7433. /*.type_v =*/ GGML_TYPE_F16,
  7434. /*.logits_all =*/ false,
  7435. /*.embeddings =*/ false,
  7436. /*.offload_kqv =*/ true,
  7437. /*.flash_attn =*/ false,
  7438. /*.no_perf =*/ true,
  7439. /*.abort_callback =*/ nullptr,
  7440. /*.abort_callback_data =*/ nullptr,
  7441. };
  7442. return result;
  7443. }
  7444. struct llama_sampler_chain_params llama_sampler_chain_default_params() {
  7445. struct llama_sampler_chain_params result = {
  7446. /*.no_perf =*/ true,
  7447. };
  7448. return result;
  7449. }
  7450. size_t llama_max_devices(void) {
  7451. return 16;
  7452. }
  7453. bool llama_supports_mmap(void) {
  7454. return llama_mmap::SUPPORTED;
  7455. }
  7456. bool llama_supports_mlock(void) {
  7457. return llama_mlock::SUPPORTED;
  7458. }
  7459. bool llama_supports_gpu_offload(void) {
  7460. return ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nullptr ||
  7461. llama_supports_rpc();
  7462. }
  7463. bool llama_supports_rpc(void) {
  7464. return ggml_backend_reg_by_name("RPC") != nullptr;
  7465. }
  7466. void llama_backend_init(void) {
  7467. ggml_time_init();
  7468. // needed to initialize f16 tables
  7469. {
  7470. struct ggml_init_params params = { 0, NULL, false };
  7471. struct ggml_context * ctx = ggml_init(params);
  7472. ggml_free(ctx);
  7473. }
  7474. }
  7475. void llama_numa_init(enum ggml_numa_strategy numa) {
  7476. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  7477. auto * dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  7478. GGML_ASSERT(dev && "CPU backend is not loaded");
  7479. auto * reg = ggml_backend_dev_backend_reg(dev);
  7480. auto * numa_init_fn = (decltype(ggml_numa_init) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_numa_init");
  7481. numa_init_fn(numa);
  7482. }
  7483. }
  7484. void llama_backend_free(void) {
  7485. ggml_quantize_free();
  7486. }
  7487. int64_t llama_time_us(void) {
  7488. return ggml_time_us();
  7489. }
  7490. static struct llama_model * llama_model_load_from_file_impl(
  7491. const std::string & path_model,
  7492. std::vector<std::string> & splits,
  7493. struct llama_model_params params) {
  7494. ggml_time_init();
  7495. llama_model * model = new llama_model(params);
  7496. unsigned cur_percentage = 0;
  7497. if (params.progress_callback == NULL) {
  7498. params.progress_callback_user_data = &cur_percentage;
  7499. params.progress_callback = [](float progress, void * ctx) {
  7500. unsigned * cur_percentage_p = (unsigned *) ctx;
  7501. unsigned percentage = (unsigned) (100 * progress);
  7502. while (percentage > *cur_percentage_p) {
  7503. *cur_percentage_p = percentage;
  7504. LLAMA_LOG_CONT(".");
  7505. if (percentage >= 100) {
  7506. LLAMA_LOG_CONT("\n");
  7507. }
  7508. }
  7509. return true;
  7510. };
  7511. }
  7512. // create list of devices to use with this model
  7513. if (params.devices) {
  7514. for (ggml_backend_dev_t * dev = params.devices; *dev; ++dev) {
  7515. model->devices.push_back(*dev);
  7516. }
  7517. } else {
  7518. std::vector<ggml_backend_dev_t> rpc_servers;
  7519. // use all available devices
  7520. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  7521. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  7522. switch (ggml_backend_dev_type(dev)) {
  7523. case GGML_BACKEND_DEVICE_TYPE_CPU:
  7524. case GGML_BACKEND_DEVICE_TYPE_ACCEL:
  7525. // skip CPU backends since they are handled separately
  7526. break;
  7527. case GGML_BACKEND_DEVICE_TYPE_GPU:
  7528. ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
  7529. if (ggml_backend_reg_name(reg) == std::string("RPC")) {
  7530. rpc_servers.push_back(dev);
  7531. } else {
  7532. model->devices.push_back(dev);
  7533. }
  7534. break;
  7535. }
  7536. }
  7537. // add RPC servers at the front of the list
  7538. if (!rpc_servers.empty()) {
  7539. model->devices.insert(model->devices.begin(), rpc_servers.begin(), rpc_servers.end());
  7540. }
  7541. }
  7542. // if using single GPU mode, remove all except the main GPU
  7543. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  7544. if (params.main_gpu < 0 || params.main_gpu >= (int)model->devices.size()) {
  7545. LLAMA_LOG_ERROR("%s: invalid value for main_gpu: %d (available devices: %d)\n", __func__, params.main_gpu, (int)model->devices.size());
  7546. llama_model_free(model);
  7547. return nullptr;
  7548. }
  7549. ggml_backend_dev_t main_gpu = model->devices[params.main_gpu];
  7550. model->devices.clear();
  7551. model->devices.push_back(main_gpu);
  7552. }
  7553. for (auto * dev : model->devices) {
  7554. size_t free, total; // NOLINT
  7555. ggml_backend_dev_memory(dev, &free, &total);
  7556. LLAMA_LOG_INFO("%s: using device %s (%s) - %zu MiB free\n", __func__, ggml_backend_dev_name(dev), ggml_backend_dev_description(dev), free/1024/1024);
  7557. }
  7558. const int status = llama_model_load(path_model, splits, *model, params);
  7559. GGML_ASSERT(status <= 0);
  7560. if (status < 0) {
  7561. if (status == -1) {
  7562. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  7563. } else if (status == -2) {
  7564. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  7565. }
  7566. llama_model_free(model);
  7567. return nullptr;
  7568. }
  7569. return model;
  7570. }
  7571. // deprecated
  7572. struct llama_model * llama_load_model_from_file(
  7573. const char * path_model,
  7574. struct llama_model_params params) {
  7575. return llama_model_load_from_file(path_model, params);
  7576. }
  7577. struct llama_model * llama_model_load_from_file(
  7578. const char * path_model,
  7579. struct llama_model_params params) {
  7580. std::vector<std::string> splits = {};
  7581. return llama_model_load_from_file_impl(path_model, splits, params);
  7582. }
  7583. struct llama_model * llama_model_load_from_splits(
  7584. const char ** paths,
  7585. size_t n_paths,
  7586. struct llama_model_params params) {
  7587. std::vector<std::string> splits;
  7588. if (n_paths == 0) {
  7589. LLAMA_LOG_ERROR("%s: list of splits is empty\n", __func__);
  7590. return nullptr;
  7591. }
  7592. for (size_t i = 0; i < n_paths; ++i) {
  7593. splits.push_back(paths[i]);
  7594. }
  7595. return llama_model_load_from_file_impl(splits.front(), splits, params);
  7596. }
  7597. struct llama_context * llama_init_from_model(
  7598. struct llama_model * model,
  7599. struct llama_context_params params) {
  7600. if (!model) {
  7601. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  7602. return nullptr;
  7603. }
  7604. if (params.n_batch == 0 && params.n_ubatch == 0) {
  7605. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  7606. return nullptr;
  7607. }
  7608. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  7609. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  7610. return nullptr;
  7611. }
  7612. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  7613. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  7614. params.flash_attn = false;
  7615. }
  7616. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  7617. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  7618. params.flash_attn = false;
  7619. }
  7620. if (ggml_is_quantized(params.type_v) && !params.flash_attn) {
  7621. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  7622. return nullptr;
  7623. }
  7624. llama_context * ctx = new llama_context(*model);
  7625. const auto & hparams = model->hparams;
  7626. auto & cparams = ctx->cparams;
  7627. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  7628. cparams.n_threads = params.n_threads;
  7629. cparams.n_threads_batch = params.n_threads_batch;
  7630. cparams.yarn_ext_factor = params.yarn_ext_factor;
  7631. cparams.yarn_attn_factor = params.yarn_attn_factor;
  7632. cparams.yarn_beta_fast = params.yarn_beta_fast;
  7633. cparams.yarn_beta_slow = params.yarn_beta_slow;
  7634. cparams.defrag_thold = params.defrag_thold;
  7635. cparams.embeddings = params.embeddings;
  7636. cparams.offload_kqv = params.offload_kqv;
  7637. cparams.flash_attn = params.flash_attn;
  7638. cparams.no_perf = params.no_perf;
  7639. cparams.pooling_type = params.pooling_type;
  7640. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  7641. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  7642. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  7643. // this is necessary due to kv_self.n being padded later during inference
  7644. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  7645. // with causal attention, the batch size is limited by the context size
  7646. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  7647. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  7648. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  7649. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  7650. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  7651. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  7652. cparams.n_batch = GGML_KQ_MASK_PAD;
  7653. }
  7654. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  7655. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  7656. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  7657. hparams.n_ctx_train;
  7658. cparams.cb_eval = params.cb_eval;
  7659. cparams.cb_eval_user_data = params.cb_eval_user_data;
  7660. auto rope_scaling_type = params.rope_scaling_type;
  7661. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  7662. rope_scaling_type = hparams.rope_scaling_type_train;
  7663. }
  7664. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  7665. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  7666. }
  7667. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  7668. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  7669. }
  7670. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  7671. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  7672. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  7673. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  7674. } else {
  7675. cparams.pooling_type = hparams.pooling_type;
  7676. }
  7677. }
  7678. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  7679. cparams.causal_attn = hparams.causal_attn;
  7680. } else {
  7681. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  7682. }
  7683. const uint32_t n_ctx_per_seq = cparams.n_ctx / cparams.n_seq_max;
  7684. LLAMA_LOG_INFO("%s: n_seq_max = %u\n", __func__, cparams.n_seq_max);
  7685. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  7686. LLAMA_LOG_INFO("%s: n_ctx_per_seq = %u\n", __func__, n_ctx_per_seq);
  7687. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  7688. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  7689. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  7690. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  7691. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  7692. if (n_ctx_per_seq < hparams.n_ctx_train) {
  7693. LLAMA_LOG_WARN("%s: n_ctx_per_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n",
  7694. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  7695. }
  7696. if (n_ctx_per_seq > hparams.n_ctx_train) {
  7697. LLAMA_LOG_WARN("%s: n_ctx_pre_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n",
  7698. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  7699. }
  7700. ctx->logits_all = params.logits_all;
  7701. // build worst-case graph for encoder if a model contains encoder
  7702. ctx->is_encoding = llama_model_has_encoder(model);
  7703. uint32_t kv_size = cparams.n_ctx;
  7704. ggml_type type_k = params.type_k;
  7705. ggml_type type_v = params.type_v;
  7706. // Mamba only needs a constant number of KV cache cells per sequence
  7707. if (llama_model_is_recurrent(model)) {
  7708. // Mamba needs at least as many KV cells as there are sequences kept at any time
  7709. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  7710. // it's probably best to keep as much precision as possible for the states
  7711. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  7712. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  7713. }
  7714. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  7715. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  7716. if (!hparams.vocab_only) {
  7717. // GPU backends
  7718. for (auto * dev : model->devices) {
  7719. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  7720. if (backend == nullptr) {
  7721. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
  7722. llama_free(ctx);
  7723. return nullptr;
  7724. }
  7725. ctx->backends.emplace_back(backend);
  7726. }
  7727. // add ACCEL backends (such as BLAS)
  7728. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  7729. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  7730. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  7731. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  7732. if (backend == nullptr) {
  7733. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
  7734. llama_free(ctx);
  7735. return nullptr;
  7736. }
  7737. ctx->backends.emplace_back(backend);
  7738. }
  7739. }
  7740. // add CPU backend
  7741. ctx->backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  7742. if (ctx->backend_cpu == nullptr) {
  7743. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  7744. llama_free(ctx);
  7745. return nullptr;
  7746. }
  7747. ctx->backends.emplace_back(ctx->backend_cpu);
  7748. // create a list of the set_n_threads functions in the backends
  7749. for (auto & backend : ctx->backends) {
  7750. ggml_backend_dev_t dev = ggml_backend_get_device(backend.get());
  7751. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  7752. if (reg) {
  7753. auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
  7754. if (ggml_backend_set_n_threads_fn) {
  7755. ctx->set_n_threads_fns.emplace_back(backend.get(), ggml_backend_set_n_threads_fn);
  7756. }
  7757. }
  7758. }
  7759. llama_set_abort_callback(ctx, params.abort_callback, params.abort_callback_data);
  7760. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, ctx->cparams, type_k, type_v, kv_size, cparams.offload_kqv)) {
  7761. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  7762. llama_free(ctx);
  7763. return nullptr;
  7764. }
  7765. {
  7766. size_t memory_size_k = 0;
  7767. size_t memory_size_v = 0;
  7768. for (auto & k : ctx->kv_self.k_l) {
  7769. memory_size_k += ggml_nbytes(k);
  7770. }
  7771. for (auto & v : ctx->kv_self.v_l) {
  7772. memory_size_v += ggml_nbytes(v);
  7773. }
  7774. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  7775. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  7776. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  7777. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  7778. }
  7779. // graph outputs buffer
  7780. {
  7781. // resized during inference when a batch uses more outputs
  7782. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  7783. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  7784. llama_free(ctx);
  7785. return nullptr;
  7786. }
  7787. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  7788. ggml_backend_buffer_name(ctx->buf_output.get()),
  7789. ggml_backend_buffer_get_size(ctx->buf_output.get()) / 1024.0 / 1024.0);
  7790. }
  7791. // scheduler and compute buffers
  7792. {
  7793. // buffer types used for the compute buffer of each backend
  7794. std::vector<ggml_backend_buffer_type_t> backend_buft;
  7795. std::vector<ggml_backend_t> backend_ptrs;
  7796. for (auto & backend : ctx->backends) {
  7797. auto * buft = ggml_backend_get_default_buffer_type(backend.get());
  7798. auto backend_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  7799. if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model->devices.empty()) {
  7800. // use the host buffer of the first device CPU for faster transfer of the intermediate state
  7801. auto * dev = model->devices[0];
  7802. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  7803. if (host_buft) {
  7804. buft = host_buft;
  7805. }
  7806. }
  7807. backend_buft.push_back(buft);
  7808. backend_ptrs.push_back(backend.get());
  7809. }
  7810. const size_t max_nodes = model->max_nodes();
  7811. // buffer used to store the computation graph and the tensor meta data
  7812. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  7813. // TODO: move these checks to ggml_backend_sched
  7814. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  7815. bool pipeline_parallel =
  7816. model->n_devices() > 1 &&
  7817. model->params.n_gpu_layers > (int)model->hparams.n_layer &&
  7818. model->params.split_mode == LLAMA_SPLIT_MODE_LAYER &&
  7819. params.offload_kqv;
  7820. // pipeline parallelism requires support for async compute and events in all devices
  7821. if (pipeline_parallel) {
  7822. for (auto & backend : ctx->backends) {
  7823. auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  7824. if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU) {
  7825. // ignore CPU backend
  7826. continue;
  7827. }
  7828. auto * dev = ggml_backend_get_device(backend.get());
  7829. ggml_backend_dev_props props;
  7830. ggml_backend_dev_get_props(dev, &props);
  7831. if (!props.caps.async || !props.caps.events) {
  7832. // device does not support async compute or events
  7833. pipeline_parallel = false;
  7834. break;
  7835. }
  7836. }
  7837. }
  7838. ctx->sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, pipeline_parallel));
  7839. if (pipeline_parallel) {
  7840. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched.get()));
  7841. }
  7842. // initialize scheduler with the worst-case graph
  7843. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  7844. uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  7845. llama_token token = ctx->model.vocab.token_bos(); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  7846. llama_ubatch ubatch_pp = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  7847. ggml_cgraph * gf_pp = llama_build_graph(*ctx, ubatch_pp, true);
  7848. // reserve pp graph first so that buffers are only allocated once
  7849. ggml_backend_sched_reserve(ctx->sched.get(), gf_pp);
  7850. int n_splits_pp = ggml_backend_sched_get_n_splits(ctx->sched.get());
  7851. int n_nodes_pp = ggml_graph_n_nodes(gf_pp);
  7852. // reserve with tg graph to get the number of splits and nodes
  7853. llama_ubatch ubatch_tg = { true, 1, 1, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  7854. ggml_cgraph * gf_tg = llama_build_graph(*ctx, ubatch_tg, true);
  7855. ggml_backend_sched_reserve(ctx->sched.get(), gf_tg);
  7856. int n_splits_tg = ggml_backend_sched_get_n_splits(ctx->sched.get());
  7857. int n_nodes_tg = ggml_graph_n_nodes(gf_tg);
  7858. // reserve again with pp graph to avoid ggml-alloc reallocations during inference
  7859. gf_pp = llama_build_graph(*ctx, ubatch_pp, true);
  7860. if (!ggml_backend_sched_reserve(ctx->sched.get(), gf_pp)) {
  7861. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  7862. llama_free(ctx);
  7863. return nullptr;
  7864. }
  7865. for (size_t i = 0; i < backend_ptrs.size(); ++i) {
  7866. ggml_backend_t backend = backend_ptrs[i];
  7867. ggml_backend_buffer_type_t buft = backend_buft[i];
  7868. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched.get(), backend);
  7869. if (size > 1) {
  7870. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  7871. ggml_backend_buft_name(buft),
  7872. size / 1024.0 / 1024.0);
  7873. }
  7874. }
  7875. if (n_nodes_pp == n_nodes_tg) {
  7876. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, n_nodes_pp);
  7877. } else {
  7878. LLAMA_LOG_INFO("%s: graph nodes = %d (with bs=%d), %d (with bs=1)\n", __func__, n_nodes_pp, n_tokens, n_nodes_tg);
  7879. }
  7880. if (n_splits_pp == n_splits_tg) {
  7881. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits_pp);
  7882. } else {
  7883. LLAMA_LOG_INFO("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n", __func__, n_splits_pp, n_tokens, n_splits_tg);
  7884. }
  7885. }
  7886. }
  7887. return ctx;
  7888. }
  7889. struct llama_context * llama_new_context_with_model(
  7890. struct llama_model * model,
  7891. struct llama_context_params params) {
  7892. return llama_init_from_model(model, params);
  7893. }
  7894. //
  7895. // kv cache
  7896. //
  7897. // TODO: tmp bridges below until `struct llama_kv_cache` is exposed through the public API
  7898. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  7899. return llama_kv_cache_view_init(ctx->kv_self, n_seq_max);
  7900. }
  7901. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  7902. llama_kv_cache_view_update(view, ctx->kv_self);
  7903. }
  7904. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  7905. return llama_get_kv_cache_token_count(ctx->kv_self);
  7906. }
  7907. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  7908. return llama_get_kv_cache_used_cells(ctx->kv_self);
  7909. }
  7910. void llama_kv_cache_clear(struct llama_context * ctx) {
  7911. llama_kv_cache_clear(ctx->kv_self);
  7912. }
  7913. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  7914. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  7915. }
  7916. void llama_kv_cache_seq_cp(struct llama_context * ctx, llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
  7917. if (seq_id_src == seq_id_dst) {
  7918. return;
  7919. }
  7920. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  7921. }
  7922. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  7923. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  7924. }
  7925. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  7926. if (delta == 0) {
  7927. return;
  7928. }
  7929. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  7930. }
  7931. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  7932. if (d == 1) {
  7933. return;
  7934. }
  7935. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  7936. }
  7937. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  7938. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  7939. }
  7940. void llama_kv_cache_defrag(struct llama_context * ctx) {
  7941. llama_kv_cache_defrag(ctx->kv_self);
  7942. }
  7943. void llama_kv_cache_update(struct llama_context * ctx) {
  7944. llama_kv_cache_update_impl(*ctx);
  7945. }
  7946. bool llama_kv_cache_can_shift(struct llama_context * ctx) {
  7947. return llama_kv_cache_can_shift(ctx->kv_self);
  7948. }
  7949. ///
  7950. int32_t llama_encode(
  7951. struct llama_context * ctx,
  7952. struct llama_batch batch) {
  7953. const int ret = llama_encode_impl(*ctx, batch);
  7954. if (ret != 0) {
  7955. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  7956. }
  7957. return ret;
  7958. }
  7959. int32_t llama_decode(
  7960. struct llama_context * ctx,
  7961. struct llama_batch batch) {
  7962. const int ret = llama_decode_impl(*ctx, batch);
  7963. if (ret != 0) {
  7964. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  7965. }
  7966. return ret;
  7967. }
  7968. //
  7969. // chat templates
  7970. //
  7971. int32_t llama_chat_apply_template(
  7972. const char * tmpl,
  7973. const struct llama_chat_message * chat,
  7974. size_t n_msg,
  7975. bool add_ass,
  7976. char * buf,
  7977. int32_t length) {
  7978. const std::string curr_tmpl(tmpl == nullptr ? "chatml" : tmpl);
  7979. // format the chat to string
  7980. std::vector<const llama_chat_message *> chat_vec;
  7981. chat_vec.resize(n_msg);
  7982. for (size_t i = 0; i < n_msg; i++) {
  7983. chat_vec[i] = &chat[i];
  7984. }
  7985. std::string formatted_chat;
  7986. llm_chat_template detected_tmpl = llm_chat_detect_template(curr_tmpl);
  7987. if (detected_tmpl == LLM_CHAT_TEMPLATE_UNKNOWN) {
  7988. return -1;
  7989. }
  7990. int32_t res = llm_chat_apply_template(detected_tmpl, chat_vec, formatted_chat, add_ass);
  7991. if (res < 0) {
  7992. return res;
  7993. }
  7994. if (buf && length > 0) {
  7995. strncpy(buf, formatted_chat.c_str(), length);
  7996. }
  7997. return res;
  7998. }
  7999. //
  8000. // model split
  8001. //
  8002. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  8003. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  8004. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  8005. return strlen(split_path);
  8006. }
  8007. return 0;
  8008. }
  8009. int llama_split_prefix(char * split_prefix, size_t maxlen, const char * split_path, int split_no, int split_count) {
  8010. std::string str_split_path(split_path);
  8011. char postfix[32];
  8012. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  8013. std::string str_postfix(postfix);
  8014. // check if split_prefix ends with postfix
  8015. int size_prefix = str_split_path.size() - str_postfix.size();
  8016. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  8017. snprintf(split_prefix, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  8018. return size_prefix;
  8019. }
  8020. return 0;
  8021. }
  8022. const char * llama_print_system_info(void) {
  8023. static std::string s;
  8024. s.clear(); // Clear the string, since it's static, otherwise it will accumulate data from previous calls.
  8025. for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
  8026. auto * reg = ggml_backend_reg_get(i);
  8027. auto * get_features_fn = (ggml_backend_get_features_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_features");
  8028. if (get_features_fn) {
  8029. ggml_backend_feature * features = get_features_fn(reg);
  8030. s += ggml_backend_reg_name(reg);
  8031. s += " : ";
  8032. for (; features->name; features++) {
  8033. s += features->name;
  8034. s += " = ";
  8035. s += features->value;
  8036. s += " | ";
  8037. }
  8038. }
  8039. }
  8040. return s.c_str();
  8041. }
  8042. //
  8043. // perf
  8044. //
  8045. struct llama_perf_context_data llama_perf_context(const struct llama_context * ctx) {
  8046. struct llama_perf_context_data data = {};
  8047. if (ctx == nullptr) {
  8048. return data;
  8049. }
  8050. data.t_start_ms = 1e-3 * ctx->t_start_us;
  8051. data.t_load_ms = 1e-3 * ctx->t_load_us;
  8052. data.t_p_eval_ms = 1e-3 * ctx->t_p_eval_us;
  8053. data.t_eval_ms = 1e-3 * ctx->t_eval_us;
  8054. data.n_p_eval = std::max(1, ctx->n_p_eval);
  8055. data.n_eval = std::max(1, ctx->n_eval);
  8056. return data;
  8057. }
  8058. void llama_perf_context_print(const struct llama_context * ctx) {
  8059. const auto data = llama_perf_context(ctx);
  8060. const double t_end_ms = 1e-3 * ggml_time_us();
  8061. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  8062. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  8063. __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
  8064. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  8065. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  8066. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
  8067. }
  8068. void llama_perf_context_reset(struct llama_context * ctx) {
  8069. ctx->t_start_us = ggml_time_us();
  8070. ctx->t_eval_us = ctx->n_eval = 0;
  8071. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  8072. }