clip.cpp 165 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752
  1. #include "clip.h"
  2. #include "clip-impl.h"
  3. #include "clip-model.h"
  4. #include "clip-graph.h"
  5. #include "models/models.h"
  6. #include "ggml.h"
  7. #include "ggml-cpp.h"
  8. #include "ggml-alloc.h"
  9. #include "ggml-backend.h"
  10. #include "gguf.h"
  11. #include <cassert>
  12. #include <cmath>
  13. #include <cstdlib>
  14. #include <cstring>
  15. #include <fstream>
  16. #include <map>
  17. #include <stdexcept>
  18. #include <unordered_set>
  19. #include <vector>
  20. #include <cinttypes>
  21. #include <limits>
  22. #include <array>
  23. #include <functional>
  24. struct clip_logger_state g_logger_state = {clip_log_callback_default, NULL};
  25. //#define CLIP_DEBUG_FUNCTIONS
  26. #ifdef CLIP_DEBUG_FUNCTIONS
  27. static void clip_image_write_image_to_ppm(const clip_image_u8& img, const std::string& filename) {
  28. std::ofstream file(filename, std::ios::binary);
  29. if (!file.is_open()) {
  30. LOG_ERR("Failed to open file for writing: %s\n", filename.c_str());
  31. return;
  32. }
  33. // PPM header: P6 format, width, height, and max color value
  34. file << "P6\n" << img.nx << " " << img.ny << "\n255\n";
  35. // Write pixel data
  36. for (size_t i = 0; i < img.buf.size(); i += 3) {
  37. // PPM expects binary data in RGB format, which matches our image buffer
  38. file.write(reinterpret_cast<const char*>(&img.buf[i]), 3);
  39. }
  40. file.close();
  41. }
  42. static void clip_image_save_to_bmp(const clip_image_u8& img, const std::string& filename) {
  43. std::ofstream file(filename, std::ios::binary);
  44. if (!file.is_open()) {
  45. LOG_ERR("Failed to open file for writing: %s\n", filename.c_str());
  46. return;
  47. }
  48. int fileSize = 54 + 3 * img.nx * img.ny; // File header + info header + pixel data
  49. int bytesPerPixel = 3;
  50. int widthInBytes = img.nx * bytesPerPixel;
  51. int paddingAmount = (4 - (widthInBytes % 4)) % 4;
  52. int stride = widthInBytes + paddingAmount;
  53. // Bitmap file header
  54. unsigned char fileHeader[14] = {
  55. 'B','M', // Signature
  56. 0,0,0,0, // Image file size in bytes
  57. 0,0,0,0, // Reserved
  58. 54,0,0,0 // Start of pixel array
  59. };
  60. // Total file size
  61. fileSize = 54 + (stride * img.ny);
  62. fileHeader[2] = (unsigned char)(fileSize);
  63. fileHeader[3] = (unsigned char)(fileSize >> 8);
  64. fileHeader[4] = (unsigned char)(fileSize >> 16);
  65. fileHeader[5] = (unsigned char)(fileSize >> 24);
  66. // Bitmap information header (BITMAPINFOHEADER)
  67. unsigned char infoHeader[40] = {
  68. 40,0,0,0, // Size of this header (40 bytes)
  69. 0,0,0,0, // Image width
  70. 0,0,0,0, // Image height
  71. 1,0, // Number of color planes
  72. 24,0, // Bits per pixel
  73. 0,0,0,0, // No compression
  74. 0,0,0,0, // Image size (can be 0 for no compression)
  75. 0,0,0,0, // X pixels per meter (not specified)
  76. 0,0,0,0, // Y pixels per meter (not specified)
  77. 0,0,0,0, // Total colors (color table not used)
  78. 0,0,0,0 // Important colors (all are important)
  79. };
  80. // Width and height in the information header
  81. infoHeader[4] = (unsigned char)(img.nx);
  82. infoHeader[5] = (unsigned char)(img.nx >> 8);
  83. infoHeader[6] = (unsigned char)(img.nx >> 16);
  84. infoHeader[7] = (unsigned char)(img.nx >> 24);
  85. infoHeader[8] = (unsigned char)(img.ny);
  86. infoHeader[9] = (unsigned char)(img.ny >> 8);
  87. infoHeader[10] = (unsigned char)(img.ny >> 16);
  88. infoHeader[11] = (unsigned char)(img.ny >> 24);
  89. // Write file headers
  90. file.write(reinterpret_cast<char*>(fileHeader), sizeof(fileHeader));
  91. file.write(reinterpret_cast<char*>(infoHeader), sizeof(infoHeader));
  92. // Pixel data
  93. std::vector<unsigned char> padding(3, 0); // Max padding size to be added to each row
  94. for (int y = img.ny - 1; y >= 0; --y) { // BMP files are stored bottom-to-top
  95. for (int x = 0; x < img.nx; ++x) {
  96. // Each pixel
  97. size_t pixelIndex = (y * img.nx + x) * 3;
  98. unsigned char pixel[3] = {
  99. img.buf[pixelIndex + 2], // BMP stores pixels in BGR format
  100. img.buf[pixelIndex + 1],
  101. img.buf[pixelIndex]
  102. };
  103. file.write(reinterpret_cast<char*>(pixel), 3);
  104. }
  105. // Write padding for the row
  106. file.write(reinterpret_cast<char*>(padding.data()), paddingAmount);
  107. }
  108. file.close();
  109. }
  110. // debug function to convert f32 to u8
  111. static void clip_image_convert_f32_to_u8(const clip_image_f32& src, clip_image_u8& dst) {
  112. dst.nx = src.nx;
  113. dst.ny = src.ny;
  114. dst.buf.resize(3 * src.nx * src.ny);
  115. for (size_t i = 0; i < src.buf.size(); ++i) {
  116. dst.buf[i] = static_cast<uint8_t>(std::min(std::max(int(src.buf[i] * 255.0f), 0), 255));
  117. }
  118. }
  119. #endif
  120. struct clip_ctx {
  121. clip_model model;
  122. gguf_context_ptr ctx_gguf;
  123. ggml_context_ptr ctx_data;
  124. std::vector<uint8_t> buf_compute_meta;
  125. std::vector<ggml_backend_t> backend_ptrs;
  126. std::vector<ggml_backend_buffer_type_t> backend_buft;
  127. ggml_backend_t backend = nullptr;
  128. ggml_backend_t backend_cpu = nullptr;
  129. ggml_backend_buffer_ptr buf;
  130. int max_nodes = 8192;
  131. ggml_backend_sched_ptr sched;
  132. clip_flash_attn_type flash_attn_type = CLIP_FLASH_ATTN_TYPE_AUTO;
  133. bool is_allocated = false;
  134. // for debugging
  135. bool debug_graph = false;
  136. std::vector<ggml_tensor *> debug_print_tensors;
  137. clip_ctx(clip_context_params & ctx_params) {
  138. flash_attn_type = ctx_params.flash_attn_type;
  139. debug_graph = std::getenv("MTMD_DEBUG_GRAPH") != nullptr;
  140. backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  141. if (!backend_cpu) {
  142. throw std::runtime_error("failed to initialize CPU backend");
  143. }
  144. if (ctx_params.use_gpu) {
  145. auto backend_name = std::getenv("MTMD_BACKEND_DEVICE");
  146. if (backend_name != nullptr) {
  147. backend = ggml_backend_init_by_name(backend_name, nullptr);
  148. if (!backend) {
  149. LOG_WRN("%s: Warning: Failed to initialize \"%s\" backend, falling back to default GPU backend\n", __func__, backend_name);
  150. }
  151. }
  152. if (!backend) {
  153. backend = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr);
  154. backend = backend ? backend : ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU, nullptr);
  155. }
  156. }
  157. if (backend) {
  158. LOG_INF("%s: CLIP using %s backend\n", __func__, ggml_backend_name(backend));
  159. backend_ptrs.push_back(backend);
  160. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  161. } else {
  162. backend = backend_cpu;
  163. LOG_INF("%s: CLIP using CPU backend\n", __func__);
  164. }
  165. if (ctx_params.image_min_tokens > 0) {
  166. model.hparams.custom_image_min_tokens = ctx_params.image_min_tokens;
  167. }
  168. if (ctx_params.image_max_tokens > 0) {
  169. model.hparams.custom_image_max_tokens = ctx_params.image_max_tokens;
  170. }
  171. backend_ptrs.push_back(backend_cpu);
  172. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend_cpu));
  173. sched.reset(
  174. ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), 8192, false, true)
  175. );
  176. }
  177. ~clip_ctx() {
  178. ggml_backend_free(backend);
  179. if (backend != backend_cpu) {
  180. ggml_backend_free(backend_cpu);
  181. }
  182. }
  183. // this function is added so that we don't change too much of the existing code
  184. projector_type proj_type() const {
  185. return model.proj_type;
  186. }
  187. };
  188. //
  189. // clip_graph
  190. //
  191. clip_graph::clip_graph(clip_ctx * ctx, const clip_image_f32 & img) :
  192. model(ctx->model),
  193. hparams(model.hparams),
  194. proj_type(ctx->proj_type()),
  195. img(img),
  196. patch_size(hparams.patch_size),
  197. n_patches_x(img.nx / patch_size),
  198. n_patches_y(img.ny / patch_size),
  199. n_patches(n_patches_x * n_patches_y),
  200. n_embd(hparams.n_embd),
  201. n_head(hparams.n_head),
  202. d_head(n_embd / n_head),
  203. n_layer(hparams.n_layer),
  204. n_mmproj_embd(clip_n_mmproj_embd(ctx)),
  205. eps(hparams.eps),
  206. kq_scale(1.0f / sqrtf((float)d_head)),
  207. flash_attn_type(ctx->flash_attn_type),
  208. debug_graph(ctx->debug_graph),
  209. debug_print_tensors(ctx->debug_print_tensors) {
  210. struct ggml_init_params params = {
  211. /*.mem_size =*/ ctx->buf_compute_meta.size(),
  212. /*.mem_buffer =*/ ctx->buf_compute_meta.data(),
  213. /*.no_alloc =*/ true,
  214. };
  215. ctx0_ptr.reset(ggml_init(params));
  216. ctx0 = ctx0_ptr.get();
  217. gf = ggml_new_graph_custom(ctx0, ctx->max_nodes, false);
  218. }
  219. void clip_graph::cb(ggml_tensor * cur0, const char * name, int il) const {
  220. if (debug_graph) {
  221. ggml_tensor * cur = ggml_cpy(ctx0, cur0, ggml_dup_tensor(ctx0, cur0));
  222. std::string cur_name = il >= 0 ? std::string(name) + "_" + std::to_string(il) : name;
  223. ggml_set_name(cur, cur_name.c_str());
  224. ggml_set_output(cur);
  225. ggml_build_forward_expand(gf, cur);
  226. debug_print_tensors.push_back(cur);
  227. }
  228. }
  229. // siglip2 naflex
  230. ggml_tensor * clip_graph::resize_position_embeddings(uint32_t interpolation_mode) {
  231. ggml_tensor * pos_embd = model.position_embeddings;
  232. const int height = img.ny / patch_size;
  233. const int width = img.nx / patch_size;
  234. const uint32_t mode = interpolation_mode;
  235. const int n_per_side = (int)std::sqrt(pos_embd->ne[1]);
  236. GGML_ASSERT(pos_embd);
  237. if (height == n_per_side && width == n_per_side) {
  238. return pos_embd;
  239. }
  240. pos_embd = ggml_reshape_3d(ctx0, pos_embd, n_embd, n_per_side, n_per_side); // -> (n_embd, n_per_side, n_per_side)
  241. pos_embd = ggml_permute(ctx0, pos_embd, 2, 0, 1, 3); // -> (n_per_side, n_per_side, n_embd)
  242. pos_embd = ggml_interpolate(ctx0, pos_embd, width, height, n_embd, 1, mode); // -> (width, height, n_embd)
  243. pos_embd = ggml_permute(ctx0, pos_embd, 1, 2, 0, 3); // -> (n_embd, width, height)
  244. pos_embd = ggml_cont_2d(ctx0, pos_embd, n_embd, width * height); // -> (n_embd, width * height)
  245. return pos_embd;
  246. }
  247. // build vision transformer (ViT) cgraph
  248. // this function should cover most of the models
  249. // if your model has specific features, you should probably duplicate this function
  250. ggml_tensor * clip_graph::build_vit(
  251. ggml_tensor * inp,
  252. int64_t n_pos,
  253. norm_type norm_t,
  254. ffn_op_type ffn_t,
  255. ggml_tensor * learned_pos_embd,
  256. std::function<ggml_tensor *(ggml_tensor *, const clip_layer &)> add_pos
  257. ) {
  258. if (learned_pos_embd) {
  259. inp = ggml_add(ctx0, inp, learned_pos_embd);
  260. cb(inp, "pos_embed", -1);
  261. }
  262. ggml_tensor * inpL = inp;
  263. // pre-layernorm
  264. if (model.pre_ln_w) {
  265. inpL = build_norm(inpL, model.pre_ln_w, model.pre_ln_b, norm_t, eps, -1);
  266. cb(inpL, "pre_ln", -1);
  267. }
  268. // loop over layers
  269. for (int il = 0; il < n_layer; il++) {
  270. auto & layer = model.layers[il];
  271. ggml_tensor * cur = inpL; // inpL = residual, cur = hidden_states
  272. // layernorm1
  273. cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, norm_t, eps, il);
  274. cb(cur, "layer_inp_normed", il);
  275. // self-attention
  276. {
  277. ggml_tensor * Qcur = nullptr;
  278. ggml_tensor * Kcur = nullptr;
  279. ggml_tensor * Vcur = nullptr;
  280. if (layer.qkv_w != nullptr) {
  281. // fused qkv
  282. cur = ggml_mul_mat(ctx0, layer.qkv_w, cur);
  283. if (layer.qkv_b != nullptr) {
  284. cur = ggml_add(ctx0, cur, layer.qkv_b);
  285. }
  286. Qcur = ggml_view_3d(ctx0, cur, d_head, n_head, n_pos,
  287. /* nb1 */ ggml_row_size(cur->type, d_head),
  288. /* nb2 */ cur->nb[1],
  289. /* offset */ 0);
  290. Kcur = ggml_view_3d(ctx0, cur, d_head, n_head, n_pos,
  291. /* nb1 */ ggml_row_size(cur->type, d_head),
  292. /* nb2 */ cur->nb[1],
  293. /* offset */ ggml_row_size(cur->type, n_embd));
  294. Vcur = ggml_view_3d(ctx0, cur, d_head, n_head, n_pos,
  295. /* nb1 */ ggml_row_size(cur->type, d_head),
  296. /* nb2 */ cur->nb[1],
  297. /* offset */ ggml_row_size(cur->type, 2 * n_embd));
  298. // TODO: q/k norm requires row size == n_embd, while here it's d_head
  299. // we can add support in the future if needed
  300. GGML_ASSERT(layer.q_norm == nullptr && layer.k_norm == nullptr);
  301. } else {
  302. // separate q, k, v
  303. Qcur = ggml_mul_mat(ctx0, layer.q_w, cur);
  304. if (layer.q_b) {
  305. Qcur = ggml_add(ctx0, Qcur, layer.q_b);
  306. }
  307. Kcur = ggml_mul_mat(ctx0, layer.k_w, cur);
  308. if (layer.k_b) {
  309. Kcur = ggml_add(ctx0, Kcur, layer.k_b);
  310. }
  311. Vcur = ggml_mul_mat(ctx0, layer.v_w, cur);
  312. if (layer.v_b) {
  313. Vcur = ggml_add(ctx0, Vcur, layer.v_b);
  314. }
  315. if (layer.q_norm) {
  316. Qcur = build_norm(Qcur, layer.q_norm, NULL, norm_t, eps, il);
  317. cb(Qcur, "Qcur_norm", il);
  318. }
  319. if (layer.k_norm) {
  320. Kcur = build_norm(Kcur, layer.k_norm, NULL, norm_t, eps, il);
  321. cb(Kcur, "Kcur_norm", il);
  322. }
  323. Qcur = ggml_reshape_3d(ctx0, Qcur, d_head, n_head, n_pos);
  324. Kcur = ggml_reshape_3d(ctx0, Kcur, d_head, n_head, n_pos);
  325. Vcur = ggml_reshape_3d(ctx0, Vcur, d_head, n_head, n_pos);
  326. }
  327. cb(Qcur, "Qcur", il);
  328. cb(Kcur, "Kcur", il);
  329. cb(Vcur, "Vcur", il);
  330. if (add_pos) {
  331. Qcur = add_pos(Qcur, layer);
  332. Kcur = add_pos(Kcur, layer);
  333. cb(Qcur, "Qcur_pos", il);
  334. cb(Kcur, "Kcur_pos", il);
  335. }
  336. cur = build_attn(layer.o_w, layer.o_b,
  337. Qcur, Kcur, Vcur, nullptr, kq_scale, il);
  338. cb(cur, "attn_out", il);
  339. }
  340. if (layer.ls_1_w) {
  341. cur = ggml_mul(ctx0, cur, layer.ls_1_w);
  342. cb(cur, "attn_out_scaled", il);
  343. }
  344. // re-add the layer input, e.g., residual
  345. cur = ggml_add(ctx0, cur, inpL);
  346. inpL = cur; // inpL = residual, cur = hidden_states
  347. cb(cur, "ffn_inp", il);
  348. // layernorm2
  349. cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, norm_t, eps, il);
  350. cb(cur, "ffn_inp_normed", il);
  351. // ffn
  352. cur = build_ffn(cur,
  353. layer.ff_up_w, layer.ff_up_b,
  354. layer.ff_gate_w, layer.ff_gate_b,
  355. layer.ff_down_w, layer.ff_down_b,
  356. ffn_t, il);
  357. cb(cur, "ffn_out", il);
  358. if (layer.ls_2_w) {
  359. cur = ggml_mul(ctx0, cur, layer.ls_2_w);
  360. cb(cur, "ffn_out_scaled", il);
  361. }
  362. // residual 2
  363. cur = ggml_add(ctx0, inpL, cur);
  364. cb(cur, "layer_out", il);
  365. inpL = cur;
  366. }
  367. if (model.audio_has_avgpool()) {
  368. ggml_tensor * cur = inpL;
  369. cur = ggml_transpose(ctx0, cur);
  370. cur = ggml_cont(ctx0, cur);
  371. cur = ggml_pool_1d(ctx0, cur, GGML_OP_POOL_AVG, 2, 2, 0);
  372. cur = ggml_transpose(ctx0, cur);
  373. cur = ggml_cont(ctx0, cur);
  374. inpL = cur;
  375. }
  376. // post-layernorm
  377. if (model.post_ln_w) {
  378. inpL = build_norm(inpL, model.post_ln_w, model.post_ln_b, norm_t, eps, -1);
  379. }
  380. return inpL;
  381. }
  382. // build the input after conv2d (inp_raw --> patches)
  383. // returns tensor with shape [n_embd, n_patches]
  384. ggml_tensor * clip_graph::build_inp() {
  385. ggml_tensor * inp_raw = build_inp_raw();
  386. ggml_tensor * inp = ggml_conv_2d(ctx0, model.patch_embeddings_0, inp_raw, patch_size, patch_size, 0, 0, 1, 1);
  387. inp = ggml_reshape_2d(ctx0, inp, n_patches, n_embd);
  388. inp = ggml_cont(ctx0, ggml_transpose(ctx0, inp));
  389. if (model.patch_bias) {
  390. inp = ggml_add(ctx0, inp, model.patch_bias);
  391. cb(inp, "patch_bias", -1);
  392. }
  393. return inp;
  394. }
  395. ggml_tensor * clip_graph::build_inp_raw(int channels) {
  396. ggml_tensor * inp_raw = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, img.nx, img.ny, channels);
  397. ggml_set_name(inp_raw, "inp_raw");
  398. ggml_set_input(inp_raw);
  399. return inp_raw;
  400. }
  401. ggml_tensor * clip_graph::build_norm(
  402. ggml_tensor * cur,
  403. ggml_tensor * mw,
  404. ggml_tensor * mb,
  405. norm_type type,
  406. float norm_eps,
  407. int il) const {
  408. cur = type == NORM_TYPE_RMS
  409. ? ggml_rms_norm(ctx0, cur, norm_eps)
  410. : ggml_norm(ctx0, cur, norm_eps);
  411. if (mw) {
  412. cur = ggml_mul(ctx0, cur, mw);
  413. cb(cur, "norm_w", il);
  414. }
  415. if (mb) {
  416. cur = ggml_add(ctx0, cur, mb);
  417. cb(cur, "norm_b", il);
  418. }
  419. return cur;
  420. }
  421. ggml_tensor * clip_graph::build_ffn(
  422. ggml_tensor * cur,
  423. ggml_tensor * up,
  424. ggml_tensor * up_b,
  425. ggml_tensor * gate,
  426. ggml_tensor * gate_b,
  427. ggml_tensor * down,
  428. ggml_tensor * down_b,
  429. ffn_op_type type_op,
  430. int il) const {
  431. ggml_tensor * tmp = up ? ggml_mul_mat(ctx0, up, cur) : cur;
  432. cb(tmp, "ffn_up", il);
  433. if (up_b) {
  434. tmp = ggml_add(ctx0, tmp, up_b);
  435. cb(tmp, "ffn_up_b", il);
  436. }
  437. if (gate) {
  438. cur = ggml_mul_mat(ctx0, gate, cur);
  439. cb(cur, "ffn_gate", il);
  440. if (gate_b) {
  441. cur = ggml_add(ctx0, cur, gate_b);
  442. cb(cur, "ffn_gate_b", il);
  443. }
  444. } else {
  445. cur = tmp;
  446. }
  447. // we only support parallel ffn for now
  448. switch (type_op) {
  449. case FFN_SILU:
  450. if (gate) {
  451. cur = ggml_swiglu_split(ctx0, cur, tmp);
  452. cb(cur, "ffn_swiglu", il);
  453. } else {
  454. cur = ggml_silu(ctx0, cur);
  455. cb(cur, "ffn_silu", il);
  456. } break;
  457. case FFN_GELU:
  458. if (gate) {
  459. cur = ggml_geglu_split(ctx0, cur, tmp);
  460. cb(cur, "ffn_geglu", il);
  461. } else {
  462. cur = ggml_gelu(ctx0, cur);
  463. cb(cur, "ffn_gelu", il);
  464. } break;
  465. case FFN_GELU_ERF:
  466. if (gate) {
  467. cur = ggml_geglu_erf_split(ctx0, cur, tmp);
  468. cb(cur, "ffn_geglu_erf", il);
  469. } else {
  470. cur = ggml_gelu_erf(ctx0, cur);
  471. cb(cur, "ffn_gelu_erf", il);
  472. } break;
  473. case FFN_GELU_QUICK:
  474. if (gate) {
  475. cur = ggml_geglu_quick_split(ctx0, cur, tmp);
  476. cb(cur, "ffn_geglu_quick", il);
  477. } else {
  478. cur = ggml_gelu_quick(ctx0, cur);
  479. cb(cur, "ffn_gelu_quick", il);
  480. } break;
  481. }
  482. if (down) {
  483. cur = ggml_mul_mat(ctx0, down, cur);
  484. }
  485. if (down_b) {
  486. cb(cur, "ffn_down", il);
  487. }
  488. if (down_b) {
  489. cur = ggml_add(ctx0, cur, down_b);
  490. }
  491. return cur;
  492. }
  493. ggml_tensor * clip_graph::build_attn(
  494. ggml_tensor * wo,
  495. ggml_tensor * wo_b,
  496. ggml_tensor * q_cur,
  497. ggml_tensor * k_cur,
  498. ggml_tensor * v_cur,
  499. ggml_tensor * kq_mask,
  500. float kq_scale,
  501. int il) const {
  502. // these nodes are added to the graph together so that they are not reordered
  503. // by doing so, the number of splits in the graph is reduced
  504. ggml_build_forward_expand(gf, q_cur);
  505. ggml_build_forward_expand(gf, k_cur);
  506. ggml_build_forward_expand(gf, v_cur);
  507. ggml_tensor * q = ggml_permute(ctx0, q_cur, 0, 2, 1, 3);
  508. //cb(q, "q", il);
  509. ggml_tensor * k = ggml_permute(ctx0, k_cur, 0, 2, 1, 3);
  510. //cb(k, "k", il);
  511. ggml_tensor * cur;
  512. if (flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) {
  513. ggml_tensor * v = ggml_permute(ctx0, v_cur, 0, 2, 1, 3);
  514. k = ggml_cast(ctx0, k, GGML_TYPE_F16);
  515. v = ggml_cast(ctx0, v, GGML_TYPE_F16);
  516. cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, 0.0f, 0.0f);
  517. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  518. cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]);
  519. } else {
  520. ggml_tensor * v = ggml_permute(ctx0, v_cur, 1, 2, 0, 3);
  521. v = ggml_cont(ctx0, v);
  522. const auto n_tokens = q->ne[1];
  523. const auto n_head = q->ne[2];
  524. ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  525. // F32 may not needed for vision encoders?
  526. // ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  527. kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, 0.0f);
  528. ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  529. cur = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  530. cur = ggml_cont_2d(ctx0, cur, cur->ne[0]*n_head, n_tokens);
  531. }
  532. cb(cur, "kqv_out", il);
  533. if (wo) {
  534. cur = ggml_mul_mat(ctx0, wo, cur);
  535. }
  536. if (wo_b) {
  537. cur = ggml_add(ctx0, cur, wo_b);
  538. }
  539. return cur;
  540. }
  541. // implementation of the 2D RoPE without adding a new op in ggml
  542. // this is not efficient (use double the memory), but works on all backends
  543. // TODO: there was a more efficient which relies on ggml_view and ggml_rope_ext_inplace, but the rope inplace does not work well with non-contiguous tensors ; we should fix that and revert back to the original implementation in https://github.com/ggml-org/llama.cpp/pull/13065
  544. ggml_tensor * clip_graph::build_rope_2d(
  545. ggml_context * ctx0,
  546. ggml_tensor * cur,
  547. ggml_tensor * pos_a, // first half
  548. ggml_tensor * pos_b, // second half
  549. const float freq_base,
  550. const bool interleave_freq
  551. ) {
  552. const int64_t n_dim = cur->ne[0];
  553. const int64_t n_head = cur->ne[1];
  554. const int64_t n_pos = cur->ne[2];
  555. // for example, if we have cur tensor of shape (n_dim=8, n_head, n_pos)
  556. // we will have a list of 4 inv_freq: 1e-0, 1e-1, 1e-2, 1e-3
  557. // first half of cur will use 1e-0, 1e-2 (even)
  558. // second half of cur will use 1e-1, 1e-3 (odd)
  559. // the trick here is to rotate just half of n_dim, so inv_freq will automatically be even
  560. // ^ don't ask me why, it's math! -2(2i) / n_dim == -2i / (n_dim/2)
  561. // then for the second half, we use freq_scale to shift the inv_freq
  562. // ^ why? replace (2i) with (2i+1) in the above equation
  563. const float freq_scale_odd = interleave_freq
  564. ? std::pow(freq_base, (float)-2/n_dim)
  565. : 1.0;
  566. // first half
  567. ggml_tensor * first;
  568. {
  569. first = ggml_view_3d(ctx0, cur,
  570. n_dim/2, n_head, n_pos,
  571. ggml_row_size(cur->type, n_dim),
  572. ggml_row_size(cur->type, n_dim*n_head),
  573. 0);
  574. first = ggml_rope_ext(
  575. ctx0,
  576. first,
  577. pos_a, // positions
  578. nullptr, // freq factors
  579. n_dim/2, // n_dims
  580. 0, 0, freq_base,
  581. 1.0f, 0.0f, 1.0f, 0.0f, 0.0f
  582. );
  583. }
  584. // second half
  585. ggml_tensor * second;
  586. {
  587. second = ggml_view_3d(ctx0, cur,
  588. n_dim/2, n_head, n_pos,
  589. ggml_row_size(cur->type, n_dim),
  590. ggml_row_size(cur->type, n_dim*n_head),
  591. n_dim/2 * ggml_element_size(cur));
  592. second = ggml_rope_ext(
  593. ctx0,
  594. second,
  595. pos_b, // positions
  596. nullptr, // freq factors
  597. n_dim/2, // n_dims
  598. 0, 0, freq_base,
  599. freq_scale_odd,
  600. 0.0f, 1.0f, 0.0f, 0.0f
  601. );
  602. }
  603. cur = ggml_concat(ctx0, first, second, 0);
  604. return cur;
  605. }
  606. // Generic function to stack frames for audio processing
  607. // Abstracts out the StackAudioFrames logic used by ultravox
  608. ggml_tensor * clip_graph::build_stack(ggml_tensor * cur, int32_t stack_factor, int32_t n_embed) {
  609. if (stack_factor <= 1) {
  610. return cur;
  611. }
  612. int64_t total_elements = ggml_nelements(cur);
  613. int64_t stride = n_embed * stack_factor;
  614. // Calculate padded length
  615. int64_t padded_len = GGML_PAD(total_elements, stride);
  616. int64_t pad = padded_len - total_elements;
  617. if (pad > 0) {
  618. // Pad the tensor to make it divisible by stride
  619. cur = ggml_view_1d(ctx0, cur, total_elements, 0);
  620. cur = ggml_pad(ctx0, cur, pad, 0, 0, 0);
  621. }
  622. // Reshape to [stride, padded_len / stride]
  623. cur = ggml_view_2d(ctx0, cur, stride, padded_len / stride,
  624. ggml_row_size(cur->type, stride), 0);
  625. return cur;
  626. }
  627. // aka pixel_shuffle / pixel_unshuffle / patch_merger (Kimi-VL)
  628. // support dynamic resolution
  629. ggml_tensor * clip_graph::build_patch_merge_permute(ggml_tensor * cur, int scale_factor) {
  630. GGML_ASSERT(scale_factor > 1);
  631. const int n_embd = cur->ne[0];
  632. int width = img.nx / patch_size;
  633. int height = img.ny / patch_size;
  634. // pad width and height to factor
  635. const int64_t pad_width = CLIP_ALIGN(width, scale_factor) - width;
  636. const int64_t pad_height = CLIP_ALIGN(height, scale_factor) - height;
  637. cur = ggml_reshape_3d(ctx0, cur, n_embd, width, height);
  638. if (pad_width || pad_height) {
  639. cur = ggml_pad(ctx0, cur, 0, pad_width, pad_height, 0);
  640. width += pad_width;
  641. height += pad_height;
  642. }
  643. // unshuffle h
  644. cur = ggml_reshape_3d(ctx0, cur, n_embd * scale_factor, width / scale_factor, height);
  645. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  646. // unshuffle w
  647. cur = ggml_cont_3d(ctx0, cur, n_embd * scale_factor * scale_factor, height / scale_factor, width / scale_factor);
  648. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  649. cur = ggml_cont_2d(ctx0, cur, cur->ne[0], cur->ne[1] * cur->ne[2]);
  650. cb(cur, "pixel_shuffle", -1);
  651. return cur;
  652. }
  653. static ggml_cgraph * clip_image_build_graph(clip_ctx * ctx, const clip_image_f32_batch & imgs) {
  654. GGML_ASSERT(imgs.entries.size() == 1 && "n_batch > 1 is not supported");
  655. const clip_image_f32 & img = *imgs.entries[0];
  656. std::unique_ptr<clip_graph> builder;
  657. switch (ctx->proj_type()) {
  658. case PROJECTOR_TYPE_GEMMA3:
  659. case PROJECTOR_TYPE_IDEFICS3:
  660. case PROJECTOR_TYPE_LFM2:
  661. case PROJECTOR_TYPE_JANUS_PRO:
  662. {
  663. builder = std::make_unique<clip_graph_siglip>(ctx, img);
  664. } break;
  665. case PROJECTOR_TYPE_PIXTRAL:
  666. case PROJECTOR_TYPE_LIGHTONOCR:
  667. {
  668. builder = std::make_unique<clip_graph_pixtral>(ctx, img);
  669. } break;
  670. case PROJECTOR_TYPE_QWEN2VL:
  671. case PROJECTOR_TYPE_QWEN25VL:
  672. {
  673. builder = std::make_unique<clip_graph_qwen2vl>(ctx, img);
  674. } break;
  675. case PROJECTOR_TYPE_QWEN3VL:
  676. {
  677. builder = std::make_unique<clip_graph_qwen3vl>(ctx, img);
  678. } break;
  679. case PROJECTOR_TYPE_MINICPMV:
  680. {
  681. builder = std::make_unique<clip_graph_minicpmv>(ctx, img);
  682. } break;
  683. case PROJECTOR_TYPE_INTERNVL:
  684. {
  685. builder = std::make_unique<clip_graph_internvl>(ctx, img);
  686. } break;
  687. case PROJECTOR_TYPE_LLAMA4:
  688. {
  689. builder = std::make_unique<clip_graph_llama4>(ctx, img);
  690. } break;
  691. case PROJECTOR_TYPE_ULTRAVOX:
  692. case PROJECTOR_TYPE_VOXTRAL:
  693. case PROJECTOR_TYPE_QWEN2A:
  694. case PROJECTOR_TYPE_GLMA:
  695. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  696. {
  697. builder = std::make_unique<clip_graph_whisper_enc>(ctx, img);
  698. } break;
  699. case PROJECTOR_TYPE_KIMIVL:
  700. {
  701. builder = std::make_unique<clip_graph_kimivl>(ctx, img);
  702. } break;
  703. case PROJECTOR_TYPE_COGVLM:
  704. {
  705. builder = std::make_unique<clip_graph_cogvlm>(ctx, img);
  706. } break;
  707. case PROJECTOR_TYPE_MLP:
  708. case PROJECTOR_TYPE_MLP_NORM:
  709. case PROJECTOR_TYPE_LDP:
  710. case PROJECTOR_TYPE_LDPV2:
  711. case PROJECTOR_TYPE_GLM_EDGE:
  712. {
  713. builder = std::make_unique<clip_graph_llava>(ctx, img);
  714. } break;
  715. case PROJECTOR_TYPE_LFM2A:
  716. {
  717. builder = std::make_unique<clip_graph_conformer>(ctx, img);
  718. } break;
  719. case PROJECTOR_TYPE_GLM4V:
  720. {
  721. builder = std::make_unique<clip_graph_glm4v>(ctx, img);
  722. } break;
  723. case PROJECTOR_TYPE_YOUTUVL:
  724. {
  725. builder = std::make_unique<clip_graph_youtuvl>(ctx, img);
  726. } break;
  727. default:
  728. GGML_ABORT("missing cgraph builder");
  729. }
  730. return builder->build();
  731. }
  732. //
  733. // clip_model_loader
  734. //
  735. struct clip_model_loader {
  736. ggml_context_ptr ctx_meta;
  737. gguf_context_ptr ctx_gguf;
  738. std::string fname;
  739. size_t model_size = 0; // in bytes
  740. bool has_vision = false;
  741. bool has_audio = false;
  742. // TODO @ngxson : we should not pass clip_ctx here, it should be clip_model
  743. clip_model_loader(const char * fname) : fname(fname) {
  744. struct ggml_context * meta = nullptr;
  745. struct gguf_init_params params = {
  746. /*.no_alloc = */ true,
  747. /*.ctx = */ &meta,
  748. };
  749. ctx_gguf = gguf_context_ptr(gguf_init_from_file(fname, params));
  750. if (!ctx_gguf.get()) {
  751. throw std::runtime_error(string_format("%s: failed to load CLIP model from %s. Does this file exist?\n", __func__, fname));
  752. }
  753. ctx_meta.reset(meta);
  754. const int n_tensors = gguf_get_n_tensors(ctx_gguf.get());
  755. // print gguf info
  756. {
  757. std::string name;
  758. get_string(KEY_NAME, name, false);
  759. std::string description;
  760. get_string(KEY_DESCRIPTION, description, false);
  761. LOG_INF("%s: model name: %s\n", __func__, name.c_str());
  762. LOG_INF("%s: description: %s\n", __func__, description.c_str());
  763. LOG_INF("%s: GGUF version: %d\n", __func__, gguf_get_version(ctx_gguf.get()));
  764. LOG_INF("%s: alignment: %zu\n", __func__, gguf_get_alignment(ctx_gguf.get()));
  765. LOG_INF("%s: n_tensors: %d\n", __func__, n_tensors);
  766. LOG_INF("%s: n_kv: %d\n", __func__, (int)gguf_get_n_kv(ctx_gguf.get()));
  767. LOG_INF("\n");
  768. }
  769. // modalities
  770. {
  771. get_bool(KEY_HAS_VISION_ENC, has_vision, false);
  772. get_bool(KEY_HAS_AUDIO_ENC, has_audio, false);
  773. if (has_vision) {
  774. LOG_INF("%s: has vision encoder\n", __func__);
  775. }
  776. if (has_audio) {
  777. LOG_INF("%s: has audio encoder\n", __func__);
  778. }
  779. }
  780. // tensors
  781. {
  782. for (int i = 0; i < n_tensors; ++i) {
  783. const char * name = gguf_get_tensor_name(ctx_gguf.get(), i);
  784. const size_t offset = gguf_get_tensor_offset(ctx_gguf.get(), i);
  785. enum ggml_type type = gguf_get_tensor_type(ctx_gguf.get(), i);
  786. ggml_tensor * cur = ggml_get_tensor(meta, name);
  787. size_t tensor_size = ggml_nbytes(cur);
  788. model_size += tensor_size;
  789. LOG_DBG("%s: tensor[%d]: n_dims = %d, name = %s, tensor_size=%zu, offset=%zu, shape:[%" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "], type = %s\n",
  790. __func__, i, ggml_n_dims(cur), cur->name, tensor_size, offset, cur->ne[0], cur->ne[1], cur->ne[2], cur->ne[3], ggml_type_name(type));
  791. }
  792. }
  793. }
  794. void load_hparams(clip_model & model, clip_modality modality) {
  795. auto & hparams = model.hparams;
  796. std::string log_ffn_op; // for logging
  797. // sanity check
  798. if (modality == CLIP_MODALITY_VISION) {
  799. GGML_ASSERT(has_vision);
  800. } else if (modality == CLIP_MODALITY_AUDIO) {
  801. GGML_ASSERT(has_audio);
  802. }
  803. model.modality = modality;
  804. // projector type
  805. std::string proj_type;
  806. {
  807. // default key
  808. get_string(KEY_PROJ_TYPE, proj_type, false);
  809. // for models with mixed modalities
  810. if (proj_type.empty()) {
  811. if (modality == CLIP_MODALITY_VISION) {
  812. get_string(KEY_VISION_PROJ_TYPE, proj_type, false);
  813. } else if (modality == CLIP_MODALITY_AUDIO) {
  814. get_string(KEY_AUDIO_PROJ_TYPE, proj_type, false);
  815. } else {
  816. GGML_ABORT("unknown modality");
  817. }
  818. }
  819. model.proj_type = clip_projector_type_from_string(proj_type);
  820. if (model.proj_type == PROJECTOR_TYPE_UNKNOWN) {
  821. throw std::runtime_error(string_format("%s: unknown projector type: %s\n", __func__, proj_type.c_str()));
  822. }
  823. // correct arch for multimodal models (legacy method)
  824. if (model.proj_type == PROJECTOR_TYPE_QWEN25O) {
  825. model.proj_type = modality == CLIP_MODALITY_VISION
  826. ? PROJECTOR_TYPE_QWEN25VL
  827. : PROJECTOR_TYPE_QWEN2A;
  828. }
  829. }
  830. const bool is_vision = model.modality == CLIP_MODALITY_VISION;
  831. const bool is_audio = model.modality == CLIP_MODALITY_AUDIO;
  832. // other hparams
  833. {
  834. const char * prefix = is_vision ? "vision" : "audio";
  835. get_u32(string_format(KEY_N_EMBD, prefix), hparams.n_embd);
  836. get_u32(string_format(KEY_N_HEAD, prefix), hparams.n_head);
  837. get_u32(string_format(KEY_N_FF, prefix), hparams.n_ff);
  838. get_u32(string_format(KEY_N_BLOCK, prefix), hparams.n_layer);
  839. get_u32(string_format(KEY_PROJ_DIM, prefix), hparams.projection_dim);
  840. get_f32(string_format(KEY_LAYER_NORM_EPS, prefix), hparams.eps);
  841. if (is_vision) {
  842. get_u32(KEY_IMAGE_SIZE, hparams.image_size);
  843. get_u32(KEY_PATCH_SIZE, hparams.patch_size);
  844. get_u32(KEY_IMAGE_CROP_RESOLUTION, hparams.image_crop_resolution, false);
  845. get_i32(KEY_MINICPMV_VERSION, hparams.minicpmv_version, false); // legacy
  846. get_u32(KEY_MINICPMV_QUERY_NUM, hparams.minicpmv_query_num, false);
  847. if (hparams.minicpmv_query_num == 0) {
  848. // Fallback to hardcoded values for legacy models
  849. if (hparams.minicpmv_version == 3) {
  850. hparams.minicpmv_query_num = 64;
  851. } else if (hparams.minicpmv_version == 4) {
  852. hparams.minicpmv_query_num = 64;
  853. } else if (hparams.minicpmv_version == 5) {
  854. hparams.minicpmv_query_num = 64;
  855. } else if (hparams.minicpmv_version == 6) {
  856. hparams.minicpmv_query_num = 64;
  857. } else {
  858. hparams.minicpmv_query_num = 96;
  859. }
  860. }
  861. } else if (is_audio) {
  862. get_u32(KEY_A_NUM_MEL_BINS, hparams.n_mel_bins);
  863. // some hparams are unused, but still need to set to avoid issues
  864. hparams.image_size = 0;
  865. hparams.patch_size = 1;
  866. } else {
  867. GGML_ASSERT(false && "unknown modality");
  868. }
  869. // for pinpoints, we need to convert it into a list of resolution candidates
  870. {
  871. std::vector<int> pinpoints;
  872. get_arr_int(KEY_IMAGE_GRID_PINPOINTS, pinpoints, false);
  873. if (!pinpoints.empty()) {
  874. for (size_t i = 0; i < pinpoints.size(); i += 2) {
  875. hparams.image_res_candidates.push_back({
  876. pinpoints[i],
  877. pinpoints[i+1],
  878. });
  879. }
  880. }
  881. }
  882. // default warmup value
  883. hparams.warmup_image_size = hparams.image_size;
  884. hparams.has_llava_projector = model.proj_type == PROJECTOR_TYPE_MLP
  885. || model.proj_type == PROJECTOR_TYPE_MLP_NORM
  886. || model.proj_type == PROJECTOR_TYPE_LDP
  887. || model.proj_type == PROJECTOR_TYPE_LDPV2;
  888. {
  889. bool use_gelu = false;
  890. bool use_silu = false;
  891. get_bool(KEY_USE_GELU, use_gelu, false);
  892. get_bool(KEY_USE_SILU, use_silu, false);
  893. if (use_gelu && use_silu) {
  894. throw std::runtime_error(string_format("%s: both use_gelu and use_silu are set to true\n", __func__));
  895. }
  896. if (use_gelu) {
  897. hparams.ffn_op = FFN_GELU;
  898. log_ffn_op = "gelu";
  899. } else if (use_silu) {
  900. hparams.ffn_op = FFN_SILU;
  901. log_ffn_op = "silu";
  902. } else {
  903. hparams.ffn_op = FFN_GELU_QUICK;
  904. log_ffn_op = "gelu_quick";
  905. }
  906. }
  907. {
  908. std::string mm_patch_merge_type;
  909. get_string(KEY_MM_PATCH_MERGE_TYPE, mm_patch_merge_type, false);
  910. if (mm_patch_merge_type == "spatial_unpad") {
  911. hparams.mm_patch_merge_type = PATCH_MERGE_SPATIAL_UNPAD;
  912. }
  913. }
  914. if (is_vision) {
  915. int idx_mean = gguf_find_key(ctx_gguf.get(), KEY_IMAGE_MEAN);
  916. int idx_std = gguf_find_key(ctx_gguf.get(), KEY_IMAGE_STD);
  917. GGML_ASSERT(idx_mean >= 0 && "image_mean not found");
  918. GGML_ASSERT(idx_std >= 0 && "image_std not found");
  919. const float * mean_data = (const float *) gguf_get_arr_data(ctx_gguf.get(), idx_mean);
  920. const float * std_data = (const float *) gguf_get_arr_data(ctx_gguf.get(), idx_std);
  921. for (int i = 0; i < 3; ++i) {
  922. hparams.image_mean[i] = mean_data[i];
  923. hparams.image_std[i] = std_data[i];
  924. }
  925. }
  926. // Load the vision feature layer indices if they are explicitly provided;
  927. // if multiple vision feature layers are present, the values will be concatenated
  928. // to form the final visual features.
  929. // NOTE: gguf conversions should standardize the values of the vision feature layer to
  930. // be non-negative, since we use -1 to mark values as unset here.
  931. std::vector<int> vision_feature_layer;
  932. get_arr_int(KEY_FEATURE_LAYER, vision_feature_layer, false);
  933. // convert std::vector to std::unordered_set
  934. for (auto & layer : vision_feature_layer) {
  935. hparams.vision_feature_layer.insert(layer);
  936. }
  937. // model-specific params
  938. switch (model.proj_type) {
  939. case PROJECTOR_TYPE_MINICPMV:
  940. {
  941. if (hparams.minicpmv_version == 0) {
  942. hparams.minicpmv_version = 2; // default to 2 if not set
  943. }
  944. } break;
  945. case PROJECTOR_TYPE_INTERNVL:
  946. {
  947. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  948. } break;
  949. case PROJECTOR_TYPE_IDEFICS3:
  950. {
  951. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  952. get_u32(KEY_PREPROC_IMAGE_SIZE, hparams.image_longest_edge, false);
  953. } break;
  954. case PROJECTOR_TYPE_LFM2:
  955. {
  956. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  957. // ref: https://huggingface.co/LiquidAI/LFM2-VL-3B/blob/main/preprocessor_config.json
  958. // config above specifies number of tokens after downsampling, while here it is before, relax lowerbound to 64
  959. hparams.set_limit_image_tokens(64, 1024);
  960. } break;
  961. case PROJECTOR_TYPE_PIXTRAL:
  962. case PROJECTOR_TYPE_LIGHTONOCR:
  963. {
  964. // ref: https://huggingface.co/mistral-community/pixtral-12b/blob/main/preprocessor_config.json
  965. // TODO: verify the image_min_tokens
  966. hparams.n_merge = 1; // the original pixtral does not use patch merging
  967. hparams.rope_theta = 10000.0f;
  968. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  969. hparams.set_limit_image_tokens(8, 1024);
  970. hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
  971. } break;
  972. case PROJECTOR_TYPE_KIMIVL:
  973. {
  974. hparams.rope_theta = 10000.0f;
  975. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  976. // TODO: check kimivl preprocessor for exact values
  977. hparams.set_limit_image_tokens(8, 1024);
  978. hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
  979. } break;
  980. case PROJECTOR_TYPE_GEMMA3:
  981. {
  982. // default value (used by all model sizes in gemma 3 family)
  983. // number of patches for each **side** is reduced by a factor of 4
  984. hparams.n_merge = 4;
  985. // test model (tinygemma3) has a different value, we optionally read it
  986. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  987. } break;
  988. case PROJECTOR_TYPE_QWEN2VL:
  989. case PROJECTOR_TYPE_QWEN25VL:
  990. case PROJECTOR_TYPE_QWEN3VL:
  991. {
  992. hparams.n_merge = 2; // default value for Qwen 2 and 2.5
  993. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  994. get_u32(KEY_WIN_ATTN_PATTERN, hparams.n_wa_pattern, model.proj_type == PROJECTOR_TYPE_QWEN25VL); // only 2.5 requires it
  995. // ref: https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct/blob/main/preprocessor_config.json
  996. hparams.set_limit_image_tokens(8, 4096);
  997. hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
  998. const int warn_min_pixels = 1024 * hparams.n_merge * hparams.n_merge * hparams.patch_size * hparams.patch_size;
  999. if (hparams.image_min_pixels < warn_min_pixels) {
  1000. LOG_WRN("%s: Qwen-VL models require at minimum 1024 image tokens to function correctly on grounding tasks\n", __func__);
  1001. LOG_WRN("%s: if you encounter problems with accuracy, try adding --image-min-tokens 1024\n", __func__);
  1002. LOG_WRN("%s: more info: https://github.com/ggml-org/llama.cpp/issues/16842\n\n", __func__);
  1003. }
  1004. } break;
  1005. case PROJECTOR_TYPE_YOUTUVL:
  1006. {
  1007. hparams.n_merge = 2;
  1008. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  1009. get_u32(KEY_ATTN_WINDOW_SIZE, hparams.attn_window_size, true);
  1010. std::vector<int> wa_layer_indexes_vec;
  1011. get_arr_int(KEY_WIN_ATTN_LAYER_INDEXES, wa_layer_indexes_vec, true);
  1012. for (auto & layer : wa_layer_indexes_vec) {
  1013. hparams.wa_layer_indexes.insert(layer);
  1014. }
  1015. // support max_height * max_width = 8000 * 8000. 8000/16/2 = 250 image tokens
  1016. hparams.set_limit_image_tokens(1, 62500);
  1017. hparams.set_warmup_n_tokens(16*16); // avoid OOM on warmup
  1018. } break;
  1019. case PROJECTOR_TYPE_GLM4V:
  1020. {
  1021. hparams.rope_theta = 10000.0f;
  1022. hparams.n_merge = 2; // default value for GLM4-V
  1023. get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
  1024. hparams.set_limit_image_tokens(8, 4096);
  1025. hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
  1026. } break;
  1027. case PROJECTOR_TYPE_LLAMA4:
  1028. {
  1029. hparams.rope_theta = 10000.0f;
  1030. get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
  1031. set_llava_uhd_res_candidates(model, 3);
  1032. } break;
  1033. case PROJECTOR_TYPE_ULTRAVOX:
  1034. case PROJECTOR_TYPE_QWEN2A:
  1035. case PROJECTOR_TYPE_GLMA:
  1036. case PROJECTOR_TYPE_VOXTRAL:
  1037. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  1038. {
  1039. bool require_stack = model.proj_type == PROJECTOR_TYPE_ULTRAVOX ||
  1040. model.proj_type == PROJECTOR_TYPE_VOXTRAL ||
  1041. model.proj_type == PROJECTOR_TYPE_GLMA;
  1042. get_u32(KEY_A_PROJ_STACK_FACTOR, hparams.proj_stack_factor, require_stack);
  1043. hparams.ffn_op = FFN_GELU_ERF;
  1044. log_ffn_op = "gelu_erf"; // temporary solution for logging
  1045. // audio preprocessing params
  1046. hparams.audio_chunk_len = 30; // in seconds
  1047. hparams.audio_sample_rate = 16000;
  1048. hparams.audio_n_fft = 400;
  1049. hparams.audio_window_len = 400;
  1050. hparams.audio_hop_len = 160;
  1051. } break;
  1052. case PROJECTOR_TYPE_LFM2A:
  1053. {
  1054. // audio preprocessing params
  1055. hparams.audio_chunk_len = 1; // in seconds
  1056. hparams.audio_sample_rate = 16000;
  1057. hparams.audio_n_fft = 512;
  1058. hparams.audio_window_len = 400;
  1059. hparams.audio_hop_len = 160;
  1060. } break;
  1061. default:
  1062. break;
  1063. }
  1064. // sanity check
  1065. {
  1066. if (hparams.image_max_pixels < hparams.image_min_pixels) {
  1067. throw std::runtime_error(string_format("%s: image_max_pixels (%d) is less than image_min_pixels (%d)\n", __func__, hparams.image_max_pixels, hparams.image_min_pixels));
  1068. }
  1069. }
  1070. LOG_INF("%s: projector: %s\n", __func__, proj_type.c_str());
  1071. LOG_INF("%s: n_embd: %d\n", __func__, hparams.n_embd);
  1072. LOG_INF("%s: n_head: %d\n", __func__, hparams.n_head);
  1073. LOG_INF("%s: n_ff: %d\n", __func__, hparams.n_ff);
  1074. LOG_INF("%s: n_layer: %d\n", __func__, hparams.n_layer);
  1075. LOG_INF("%s: ffn_op: %s\n", __func__, log_ffn_op.c_str());
  1076. LOG_INF("%s: projection_dim: %d\n", __func__, hparams.projection_dim);
  1077. if (is_vision) {
  1078. LOG_INF("\n--- vision hparams ---\n");
  1079. LOG_INF("%s: image_size: %d\n", __func__, hparams.image_size);
  1080. LOG_INF("%s: patch_size: %d\n", __func__, hparams.patch_size);
  1081. LOG_INF("%s: has_llava_proj: %d\n", __func__, hparams.has_llava_projector);
  1082. LOG_INF("%s: minicpmv_version: %d\n", __func__, hparams.minicpmv_version);
  1083. LOG_INF("%s: n_merge: %d\n", __func__, hparams.n_merge);
  1084. LOG_INF("%s: n_wa_pattern: %d\n", __func__, hparams.n_wa_pattern);
  1085. if (!hparams.wa_layer_indexes.empty()) {
  1086. LOG_INF("%s: wa_layer_indexes: ", __func__);
  1087. for (auto & layer : hparams.wa_layer_indexes) {
  1088. LOG_INF("%d ", layer);
  1089. }
  1090. LOG_INF("\n");
  1091. }
  1092. if (hparams.image_min_pixels > 0) {
  1093. LOG_INF("%s: image_min_pixels: %d%s\n", __func__, hparams.image_min_pixels, hparams.custom_image_min_tokens > 0 ? " (custom value)" : "");
  1094. }
  1095. if (hparams.image_max_pixels > 0) {
  1096. LOG_INF("%s: image_max_pixels: %d%s\n", __func__, hparams.image_max_pixels, hparams.custom_image_max_tokens > 0 ? " (custom value)" : "");
  1097. }
  1098. } else if (is_audio) {
  1099. LOG_INF("\n--- audio hparams ---\n");
  1100. LOG_INF("%s: n_mel_bins: %d\n", __func__, hparams.n_mel_bins);
  1101. LOG_INF("%s: proj_stack_factor: %d\n", __func__, hparams.proj_stack_factor);
  1102. LOG_INF("%s: audio_chunk_len: %d\n", __func__, hparams.audio_chunk_len);
  1103. LOG_INF("%s: audio_sample_rate: %d\n", __func__, hparams.audio_sample_rate);
  1104. LOG_INF("%s: audio_n_fft: %d\n", __func__, hparams.audio_n_fft);
  1105. LOG_INF("%s: audio_window_len: %d\n", __func__, hparams.audio_window_len);
  1106. LOG_INF("%s: audio_hop_len: %d\n", __func__, hparams.audio_hop_len);
  1107. }
  1108. LOG_INF("\n");
  1109. LOG_INF("%s: model size: %.2f MiB\n", __func__, model_size / 1024.0 / 1024.0);
  1110. LOG_INF("%s: metadata size: %.2f MiB\n", __func__, ggml_get_mem_size(ctx_meta.get()) / 1024.0 / 1024.0);
  1111. }
  1112. }
  1113. void load_tensors(clip_ctx & ctx_clip) {
  1114. auto & model = ctx_clip.model;
  1115. auto & hparams = model.hparams;
  1116. std::map<std::string, size_t> tensor_offset;
  1117. std::vector<ggml_tensor *> tensors_to_load;
  1118. // TODO @ngxson : support both audio and video in the future
  1119. const char * prefix = model.modality == CLIP_MODALITY_AUDIO ? "a" : "v";
  1120. // get offsets
  1121. for (int64_t i = 0; i < gguf_get_n_tensors(ctx_gguf.get()); ++i) {
  1122. const char * name = gguf_get_tensor_name(ctx_gguf.get(), i);
  1123. tensor_offset[name] = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), i);
  1124. }
  1125. // create data context
  1126. struct ggml_init_params params = {
  1127. /*.mem_size =*/ static_cast<size_t>(gguf_get_n_tensors(ctx_gguf.get()) + 1) * ggml_tensor_overhead(),
  1128. /*.mem_buffer =*/ NULL,
  1129. /*.no_alloc =*/ true,
  1130. };
  1131. ctx_clip.ctx_data.reset(ggml_init(params));
  1132. if (!ctx_clip.ctx_data) {
  1133. throw std::runtime_error(string_format("%s: failed to init ggml context\n", __func__));
  1134. }
  1135. // helper function
  1136. auto get_tensor = [&](const std::string & name, bool required = true) {
  1137. ggml_tensor * cur = ggml_get_tensor(ctx_meta.get(), name.c_str());
  1138. if (!cur && required) {
  1139. throw std::runtime_error(string_format("%s: unable to find tensor %s\n", __func__, name.c_str()));
  1140. }
  1141. if (cur) {
  1142. tensors_to_load.push_back(cur);
  1143. // add tensors to context
  1144. ggml_tensor * data_tensor = ggml_dup_tensor(ctx_clip.ctx_data.get(), cur);
  1145. ggml_set_name(data_tensor, cur->name);
  1146. cur = data_tensor;
  1147. }
  1148. return cur;
  1149. };
  1150. model.class_embedding = get_tensor(TN_CLASS_EMBD, false);
  1151. model.pre_ln_w = get_tensor(string_format(TN_LN_PRE, prefix, "weight"), false);
  1152. model.pre_ln_b = get_tensor(string_format(TN_LN_PRE, prefix, "bias"), false);
  1153. model.post_ln_w = get_tensor(string_format(TN_LN_POST, prefix, "weight"), false);
  1154. model.post_ln_b = get_tensor(string_format(TN_LN_POST, prefix, "bias"), false);
  1155. model.patch_bias = get_tensor(TN_PATCH_BIAS, false);
  1156. model.patch_embeddings_0 = get_tensor(TN_PATCH_EMBD, false);
  1157. model.patch_embeddings_1 = get_tensor(TN_PATCH_EMBD_1, false);
  1158. model.norm_embd_w = get_tensor(string_format(TN_NORM_EMBD, "weight"), false);
  1159. model.norm_embd_b = get_tensor(string_format(TN_NORM_EMBD, "bias"), false);
  1160. model.position_embeddings = get_tensor(string_format(TN_POS_EMBD, prefix), false);
  1161. // layers
  1162. model.layers.resize(hparams.n_layer);
  1163. for (int il = 0; il < hparams.n_layer; ++il) {
  1164. auto & layer = model.layers[il];
  1165. layer.k_w = get_tensor(string_format(TN_ATTN_K, prefix, il, "weight"), false);
  1166. layer.q_w = get_tensor(string_format(TN_ATTN_Q, prefix, il, "weight"), false);
  1167. layer.v_w = get_tensor(string_format(TN_ATTN_V, prefix, il, "weight"), false);
  1168. layer.o_w = get_tensor(string_format(TN_ATTN_OUTPUT, prefix, il, "weight"));
  1169. layer.qkv_w = get_tensor(string_format(TN_ATTN_QKV, prefix, il, "weight"), false);
  1170. layer.k_norm = get_tensor(string_format(TN_ATTN_K_NORM, prefix, il, "weight"), false);
  1171. layer.q_norm = get_tensor(string_format(TN_ATTN_Q_NORM, prefix, il, "weight"), false);
  1172. layer.ln_1_w = get_tensor(string_format(TN_LN_1, prefix, il, "weight"), false);
  1173. layer.ln_2_w = get_tensor(string_format(TN_LN_2, prefix, il, "weight"), false);
  1174. layer.ls_1_w = get_tensor(string_format(TN_LS_1, prefix, il, "weight"), false); // no bias
  1175. layer.ls_2_w = get_tensor(string_format(TN_LS_2, prefix, il, "weight"), false); // no bias
  1176. layer.k_b = get_tensor(string_format(TN_ATTN_K, prefix, il, "bias"), false);
  1177. layer.q_b = get_tensor(string_format(TN_ATTN_Q, prefix, il, "bias"), false);
  1178. layer.v_b = get_tensor(string_format(TN_ATTN_V, prefix, il, "bias"), false);
  1179. layer.o_b = get_tensor(string_format(TN_ATTN_OUTPUT, prefix, il, "bias"), false);
  1180. layer.qkv_b = get_tensor(string_format(TN_ATTN_QKV, prefix, il, "bias"), false);
  1181. layer.ln_1_b = get_tensor(string_format(TN_LN_1, prefix, il, "bias"), false);
  1182. layer.ln_2_b = get_tensor(string_format(TN_LN_2, prefix, il, "bias"), false);
  1183. // ffn
  1184. layer.ff_up_w = get_tensor(string_format(TN_FFN_UP, prefix, il, "weight"));
  1185. layer.ff_up_b = get_tensor(string_format(TN_FFN_UP, prefix, il, "bias"), false);
  1186. layer.ff_gate_w = get_tensor(string_format(TN_FFN_GATE, prefix, il, "weight"), false);
  1187. layer.ff_gate_b = get_tensor(string_format(TN_FFN_GATE, prefix, il, "bias"), false);
  1188. layer.ff_down_w = get_tensor(string_format(TN_FFN_DOWN, prefix, il, "weight"));
  1189. layer.ff_down_b = get_tensor(string_format(TN_FFN_DOWN, prefix, il, "bias"), false);
  1190. // qwen3vl deepstack layer
  1191. layer.deepstack_norm_w = get_tensor(string_format(TN_DEEPSTACK_NORM, il, "weight"), false);
  1192. layer.deepstack_norm_b = get_tensor(string_format(TN_DEEPSTACK_NORM, il, "bias"), false);
  1193. layer.deepstack_fc1_w = get_tensor(string_format(TN_DEEPSTACK_FC1, il, "weight"), false);
  1194. layer.deepstack_fc1_b = get_tensor(string_format(TN_DEEPSTACK_FC1, il, "bias"), false);
  1195. layer.deepstack_fc2_w = get_tensor(string_format(TN_DEEPSTACK_FC2, il, "weight"), false);
  1196. layer.deepstack_fc2_b = get_tensor(string_format(TN_DEEPSTACK_FC2, il, "bias"), false);
  1197. if (layer.has_deepstack()) {
  1198. model.n_deepstack_layers++;
  1199. }
  1200. // some models already exported with legacy (incorrect) naming which is quite messy, let's fix it here
  1201. // note: Qwen model converted from the old surgery script has n_ff = 0, so we cannot use n_ff to check!
  1202. bool is_ffn_swapped = (
  1203. // only old models need this fix
  1204. model.proj_type == PROJECTOR_TYPE_MLP
  1205. || model.proj_type == PROJECTOR_TYPE_MLP_NORM
  1206. || model.proj_type == PROJECTOR_TYPE_LDP
  1207. || model.proj_type == PROJECTOR_TYPE_LDPV2
  1208. || model.proj_type == PROJECTOR_TYPE_QWEN2VL
  1209. || model.proj_type == PROJECTOR_TYPE_QWEN25VL
  1210. || model.proj_type == PROJECTOR_TYPE_GLM_EDGE
  1211. || model.proj_type == PROJECTOR_TYPE_GEMMA3
  1212. || model.proj_type == PROJECTOR_TYPE_IDEFICS3
  1213. || model.proj_type == PROJECTOR_TYPE_MINICPMV
  1214. ) && layer.ff_up_w && layer.ff_down_w && layer.ff_down_w->ne[0] == hparams.n_embd;
  1215. if (is_ffn_swapped) {
  1216. // swap up and down weights
  1217. ggml_tensor * tmp = layer.ff_up_w;
  1218. layer.ff_up_w = layer.ff_down_w;
  1219. layer.ff_down_w = tmp;
  1220. // swap up and down biases
  1221. tmp = layer.ff_up_b;
  1222. layer.ff_up_b = layer.ff_down_b;
  1223. layer.ff_down_b = tmp;
  1224. if (il == 0) {
  1225. LOG_WRN("%s: ffn up/down are swapped\n", __func__);
  1226. }
  1227. }
  1228. }
  1229. switch (model.proj_type) {
  1230. case PROJECTOR_TYPE_MLP:
  1231. case PROJECTOR_TYPE_MLP_NORM:
  1232. {
  1233. // LLaVA projection
  1234. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"), false);
  1235. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"), false);
  1236. // Yi-type llava
  1237. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"), false);
  1238. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1239. // missing in Yi-type llava
  1240. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"), false);
  1241. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1242. // Yi-type llava
  1243. model.mm_3_w = get_tensor(string_format(TN_LLAVA_PROJ, 3, "weight"), false);
  1244. model.mm_3_b = get_tensor(string_format(TN_LLAVA_PROJ, 3, "bias"), false);
  1245. model.mm_4_w = get_tensor(string_format(TN_LLAVA_PROJ, 4, "weight"), false);
  1246. model.mm_4_b = get_tensor(string_format(TN_LLAVA_PROJ, 4, "bias"), false);
  1247. if (model.mm_3_w) {
  1248. // TODO: this is a hack to support Yi-type llava
  1249. model.proj_type = PROJECTOR_TYPE_MLP_NORM;
  1250. }
  1251. model.image_newline = get_tensor(TN_IMAGE_NEWLINE, false);
  1252. } break;
  1253. case PROJECTOR_TYPE_LDP:
  1254. {
  1255. // MobileVLM projection
  1256. model.mm_model_mlp_1_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1257. model.mm_model_mlp_1_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "bias"));
  1258. model.mm_model_mlp_3_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "weight"));
  1259. model.mm_model_mlp_3_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "bias"));
  1260. model.mm_model_block_1_block_0_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "0.weight"));
  1261. model.mm_model_block_1_block_0_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.weight"));
  1262. model.mm_model_block_1_block_0_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 0, "1.bias"));
  1263. model.mm_model_block_1_block_1_fc1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.weight"));
  1264. model.mm_model_block_1_block_1_fc1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc1.bias"));
  1265. model.mm_model_block_1_block_1_fc2_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.weight"));
  1266. model.mm_model_block_1_block_1_fc2_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 1, "fc2.bias"));
  1267. model.mm_model_block_1_block_2_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "0.weight"));
  1268. model.mm_model_block_1_block_2_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.weight"));
  1269. model.mm_model_block_1_block_2_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 1, 2, "1.bias"));
  1270. model.mm_model_block_2_block_0_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "0.weight"));
  1271. model.mm_model_block_2_block_0_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.weight"));
  1272. model.mm_model_block_2_block_0_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 0, "1.bias"));
  1273. model.mm_model_block_2_block_1_fc1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.weight"));
  1274. model.mm_model_block_2_block_1_fc1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc1.bias"));
  1275. model.mm_model_block_2_block_1_fc2_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.weight"));
  1276. model.mm_model_block_2_block_1_fc2_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 1, "fc2.bias"));
  1277. model.mm_model_block_2_block_2_0_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "0.weight"));
  1278. model.mm_model_block_2_block_2_1_w = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.weight"));
  1279. model.mm_model_block_2_block_2_1_b = get_tensor(string_format(TN_MVLM_PROJ_BLOCK, 2, 2, "1.bias"));
  1280. } break;
  1281. case PROJECTOR_TYPE_LDPV2:
  1282. {
  1283. // MobilVLM_V2 projection
  1284. model.mm_model_mlp_0_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "weight"));
  1285. model.mm_model_mlp_0_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "bias"));
  1286. model.mm_model_mlp_2_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "weight"));
  1287. model.mm_model_mlp_2_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "bias"));
  1288. model.mm_model_peg_0_w = get_tensor(string_format(TN_MVLM_PROJ_PEG, 0, "weight"));
  1289. model.mm_model_peg_0_b = get_tensor(string_format(TN_MVLM_PROJ_PEG, 0, "bias"));
  1290. } break;
  1291. case PROJECTOR_TYPE_MINICPMV:
  1292. {
  1293. // model.mm_model_pos_embed = get_tensor(new_clip->ctx_data, TN_MINICPMV_POS_EMBD);
  1294. model.mm_model_pos_embed_k = get_tensor(TN_MINICPMV_POS_EMBD_K);
  1295. model.mm_model_query = get_tensor(TN_MINICPMV_QUERY);
  1296. model.mm_model_proj = get_tensor(TN_MINICPMV_PROJ);
  1297. model.mm_model_kv_proj = get_tensor(TN_MINICPMV_KV_PROJ);
  1298. model.mm_model_attn_q_w = get_tensor(string_format(TN_MINICPMV_ATTN, "q", "weight"));
  1299. model.mm_model_attn_k_w = get_tensor(string_format(TN_MINICPMV_ATTN, "k", "weight"));
  1300. model.mm_model_attn_v_w = get_tensor(string_format(TN_MINICPMV_ATTN, "v", "weight"));
  1301. model.mm_model_attn_q_b = get_tensor(string_format(TN_MINICPMV_ATTN, "q", "bias"));
  1302. model.mm_model_attn_k_b = get_tensor(string_format(TN_MINICPMV_ATTN, "k", "bias"));
  1303. model.mm_model_attn_v_b = get_tensor(string_format(TN_MINICPMV_ATTN, "v", "bias"));
  1304. model.mm_model_attn_o_w = get_tensor(string_format(TN_MINICPMV_ATTN, "out", "weight"));
  1305. model.mm_model_attn_o_b = get_tensor(string_format(TN_MINICPMV_ATTN, "out", "bias"));
  1306. model.mm_model_ln_q_w = get_tensor(string_format(TN_MINICPMV_LN, "q", "weight"));
  1307. model.mm_model_ln_q_b = get_tensor(string_format(TN_MINICPMV_LN, "q", "bias"));
  1308. model.mm_model_ln_kv_w = get_tensor(string_format(TN_MINICPMV_LN, "kv", "weight"));
  1309. model.mm_model_ln_kv_b = get_tensor(string_format(TN_MINICPMV_LN, "kv", "bias"));
  1310. model.mm_model_ln_post_w = get_tensor(string_format(TN_MINICPMV_LN, "post", "weight"));
  1311. model.mm_model_ln_post_b = get_tensor(string_format(TN_MINICPMV_LN, "post", "bias"));
  1312. } break;
  1313. case PROJECTOR_TYPE_GLM_EDGE:
  1314. {
  1315. model.mm_model_adapter_conv_w = get_tensor(string_format(TN_GLM_ADAPER_CONV, "weight"));
  1316. model.mm_model_adapter_conv_b = get_tensor(string_format(TN_GLM_ADAPER_CONV, "bias"));
  1317. model.mm_model_mlp_0_w = get_tensor(string_format(TN_GLM_ADAPTER_LINEAR, "weight"));
  1318. model.mm_model_ln_q_w = get_tensor(string_format(TN_GLM_ADAPTER_NORM_1, "weight"));
  1319. model.mm_model_ln_q_b = get_tensor(string_format(TN_GLM_ADAPTER_NORM_1, "bias"));
  1320. model.mm_model_mlp_1_w = get_tensor(string_format(TN_GLM_ADAPTER_D_H_2_4H, "weight"));
  1321. model.mm_model_mlp_2_w = get_tensor(string_format(TN_GLM_ADAPTER_GATE, "weight"));
  1322. model.mm_model_mlp_3_w = get_tensor(string_format(TN_GLM_ADAPTER_D_4H_2_H, "weight"));
  1323. model.mm_boi = get_tensor(string_format(TN_TOK_GLM_BOI, "weight"));
  1324. model.mm_eoi = get_tensor(string_format(TN_TOK_GLM_EOI, "weight"));
  1325. } break;
  1326. case PROJECTOR_TYPE_QWEN2VL:
  1327. case PROJECTOR_TYPE_QWEN25VL:
  1328. {
  1329. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"));
  1330. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1331. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1332. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1333. } break;
  1334. case PROJECTOR_TYPE_QWEN3VL:
  1335. {
  1336. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"));
  1337. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1338. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1339. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1340. } break;
  1341. case PROJECTOR_TYPE_YOUTUVL:
  1342. {
  1343. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM); // merger.ln_q (RMS norm)
  1344. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight")); // merger.mlp.0
  1345. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1346. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight")); // merger.mlp.2
  1347. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1348. } break;
  1349. case PROJECTOR_TYPE_GLM4V:
  1350. {
  1351. model.projection = get_tensor(TN_MM_PROJECTOR);
  1352. model.mm_ffn_up_w = get_tensor(string_format(TN_MM_UP, "weight"));
  1353. model.mm_ffn_up_b = get_tensor(string_format(TN_MM_UP, "bias"), false);
  1354. model.mm_ffn_gate_w = get_tensor(string_format(TN_MM_GATE, "weight"));
  1355. model.mm_ffn_gate_b = get_tensor(string_format(TN_MM_GATE, "bias"), false);
  1356. model.mm_ffn_down_w = get_tensor(string_format(TN_MM_DOWN, "weight"));
  1357. model.mm_ffn_down_b = get_tensor(string_format(TN_MM_DOWN, "bias"), false);
  1358. model.mm_post_norm_w = get_tensor(string_format(TN_MM_POST_NORM, "weight"));
  1359. model.mm_post_norm_b = get_tensor(string_format(TN_MM_POST_NORM, "bias"), false);
  1360. model.mm_patch_merger_w = get_tensor(string_format(TN_MM_PATCH_MERGER, "weight"));
  1361. model.mm_patch_merger_b = get_tensor(string_format(TN_MM_PATCH_MERGER, "bias"));
  1362. } break;
  1363. case PROJECTOR_TYPE_GEMMA3:
  1364. {
  1365. model.mm_input_proj_w = get_tensor(TN_MM_INP_PROJ);
  1366. model.mm_soft_emb_norm_w = get_tensor(TN_MM_SOFT_EMB_N);
  1367. } break;
  1368. case PROJECTOR_TYPE_IDEFICS3:
  1369. {
  1370. model.projection = get_tensor(TN_MM_PROJECTOR);
  1371. } break;
  1372. case PROJECTOR_TYPE_LFM2:
  1373. case PROJECTOR_TYPE_KIMIVL:
  1374. {
  1375. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM);
  1376. model.mm_input_norm_b = get_tensor(TN_MM_INP_NORM_B);
  1377. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1378. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"));
  1379. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1380. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"));
  1381. } break;
  1382. case PROJECTOR_TYPE_PIXTRAL:
  1383. {
  1384. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1385. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1386. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1387. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1388. // [IMG_BREAK] token embedding
  1389. model.token_embd_img_break = get_tensor(TN_TOK_IMG_BREAK);
  1390. // for mistral small 3.1
  1391. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM, false);
  1392. model.mm_patch_merger_w = get_tensor(string_format(TN_MM_PATCH_MERGER, "weight"), false);
  1393. } break;
  1394. case PROJECTOR_TYPE_LIGHTONOCR:
  1395. {
  1396. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1397. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"), false);
  1398. model.mm_2_w = get_tensor(string_format(TN_LLAVA_PROJ, 2, "weight"));
  1399. model.mm_2_b = get_tensor(string_format(TN_LLAVA_PROJ, 2, "bias"), false);
  1400. model.mm_input_norm_w = get_tensor(TN_MM_INP_NORM, false);
  1401. model.mm_patch_merger_w = get_tensor(string_format(TN_MM_PATCH_MERGER, "weight"), false);
  1402. } break;
  1403. case PROJECTOR_TYPE_ULTRAVOX:
  1404. {
  1405. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1406. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1407. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1408. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1409. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1410. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1411. model.mm_norm_pre_w = get_tensor(string_format(TN_MM_NORM_PRE, "weight"));
  1412. model.mm_norm_mid_w = get_tensor(string_format(TN_MM_NORM_MID, "weight"));
  1413. } break;
  1414. case PROJECTOR_TYPE_QWEN2A:
  1415. {
  1416. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1417. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1418. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1419. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1420. model.mm_fc_w = get_tensor(string_format(TN_MM_AUDIO_FC, "weight"));
  1421. model.mm_fc_b = get_tensor(string_format(TN_MM_AUDIO_FC, "bias"));
  1422. } break;
  1423. case PROJECTOR_TYPE_VOXTRAL:
  1424. {
  1425. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1426. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1427. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1428. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1429. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1430. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1431. } break;
  1432. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  1433. {
  1434. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1435. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1436. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1437. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1438. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1439. model.mm_1_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "bias"));
  1440. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1441. model.mm_2_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "bias"));
  1442. } break;
  1443. case PROJECTOR_TYPE_INTERNVL:
  1444. {
  1445. model.mm_0_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "weight"));
  1446. model.mm_0_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 0, "bias"));
  1447. model.mm_1_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1448. model.mm_1_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "bias"));
  1449. model.mm_3_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "weight"));
  1450. model.mm_3_b = get_tensor(string_format(TN_MVLM_PROJ_MLP, 3, "bias"));
  1451. } break;
  1452. case PROJECTOR_TYPE_GLMA:
  1453. {
  1454. model.conv1d_1_w = get_tensor(string_format(TN_CONV1D, 1, "weight"));
  1455. model.conv1d_1_b = get_tensor(string_format(TN_CONV1D, 1, "bias"));
  1456. model.conv1d_2_w = get_tensor(string_format(TN_CONV1D, 2, "weight"));
  1457. model.conv1d_2_b = get_tensor(string_format(TN_CONV1D, 2, "bias"));
  1458. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1459. model.mm_1_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "bias"));
  1460. model.mm_2_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "weight"));
  1461. model.mm_2_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 2, "bias"));
  1462. model.mm_norm_pre_w = get_tensor(string_format(TN_MM_NORM_PRE, "weight"));
  1463. model.mm_norm_pre_b = get_tensor(string_format(TN_MM_NORM_PRE, "bias"));
  1464. model.mm_boi = get_tensor(string_format(TN_TOK_BOI, "weight"));
  1465. model.mm_eoi = get_tensor(string_format(TN_TOK_EOI, "weight"));
  1466. } break;
  1467. case PROJECTOR_TYPE_LLAMA4:
  1468. {
  1469. model.mm_model_proj = get_tensor(TN_MM_PROJECTOR);
  1470. model.mm_model_mlp_1_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 1, "weight"));
  1471. model.mm_model_mlp_2_w = get_tensor(string_format(TN_MVLM_PROJ_MLP, 2, "weight"));
  1472. } break;
  1473. case PROJECTOR_TYPE_COGVLM:
  1474. {
  1475. model.mm_model_proj = get_tensor(TN_MM_PROJECTOR);
  1476. model.mm_post_fc_norm_w = get_tensor(string_format(TN_MM_POST_FC_NORM, "weight"));
  1477. model.mm_post_fc_norm_b = get_tensor(string_format(TN_MM_POST_FC_NORM, "bias"));
  1478. model.mm_h_to_4h_w = get_tensor(string_format(TN_MM_H_TO_4H, "weight"));
  1479. model.mm_gate_w = get_tensor(string_format(TN_MM_GATE, "weight"));
  1480. model.mm_4h_to_h_w = get_tensor(string_format(TN_MM_4H_TO_H, "weight"));
  1481. model.mm_boi = get_tensor(TN_TOK_BOI);
  1482. model.mm_eoi = get_tensor(TN_TOK_EOI);
  1483. } break;
  1484. case PROJECTOR_TYPE_JANUS_PRO:
  1485. {
  1486. model.mm_0_w = get_tensor(string_format(TN_LLAVA_PROJ, 0, "weight"));
  1487. model.mm_0_b = get_tensor(string_format(TN_LLAVA_PROJ, 0, "bias"));
  1488. model.mm_1_w = get_tensor(string_format(TN_LLAVA_PROJ, 1, "weight"));
  1489. model.mm_1_b = get_tensor(string_format(TN_LLAVA_PROJ, 1, "bias"));
  1490. } break;
  1491. case PROJECTOR_TYPE_LFM2A:
  1492. {
  1493. for (int i : {0, 2, 3, 5, 6}) {
  1494. model.pre_encode_conv_X_w[i] = get_tensor(string_format(TN_CONV1D, i, "weight"));
  1495. model.pre_encode_conv_X_b[i] = get_tensor(string_format(TN_CONV1D, i, "bias"));
  1496. }
  1497. model.pre_encode_out_w = get_tensor(string_format(TN_PRE_ENCODE_OUT, "weight"));
  1498. model.pre_encode_out_b = get_tensor(string_format(TN_PRE_ENCODE_OUT, "bias"));
  1499. model.mm_0_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 0, "weight"));
  1500. model.mm_0_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 0, "bias"));
  1501. model.mm_1_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "weight"));
  1502. model.mm_1_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 1, "bias"));
  1503. model.mm_3_w = get_tensor(string_format(TN_MM_AUDIO_MLP, 3, "weight"));
  1504. model.mm_3_b = get_tensor(string_format(TN_MM_AUDIO_MLP, 3, "bias"));
  1505. for (int il = 0; il < hparams.n_layer; ++il) {
  1506. auto & layer = model.layers[il];
  1507. layer.ff_norm_w = get_tensor(string_format(TN_FFN_NORM, prefix, il, "weight"));
  1508. layer.ff_norm_b = get_tensor(string_format(TN_FFN_NORM, prefix, il, "bias"));
  1509. layer.ff_norm_1_w = get_tensor(string_format(TN_FFN_NORM_1, prefix, il, "weight"));
  1510. layer.ff_norm_1_b = get_tensor(string_format(TN_FFN_NORM_1, prefix, il, "bias"));
  1511. layer.ff_up_1_w = get_tensor(string_format(TN_FFN_UP_1, prefix, il, "weight"));
  1512. layer.ff_up_1_b = get_tensor(string_format(TN_FFN_UP_1, prefix, il, "bias"));
  1513. layer.ff_down_1_w = get_tensor(string_format(TN_FFN_DOWN_1, prefix, il, "weight"));
  1514. layer.ff_down_1_b = get_tensor(string_format(TN_FFN_DOWN_1, prefix, il, "bias"));
  1515. layer.pos_bias_u = get_tensor(string_format(TN_POS_BIAS_U, prefix, il));
  1516. layer.pos_bias_v = get_tensor(string_format(TN_POS_BIAS_V, prefix, il));
  1517. layer.norm_conv_w = get_tensor(string_format(TN_NORM_CONV, prefix, il, "weight"));
  1518. layer.norm_conv_b = get_tensor(string_format(TN_NORM_CONV, prefix, il, "bias"));
  1519. layer.linear_pos_w = get_tensor(string_format(TN_LINEAR_POS, prefix, il, "weight"));
  1520. layer.conv_norm_w = get_tensor(string_format(TN_CONV_NORM, prefix, il, "weight"));
  1521. layer.conv_norm_b = get_tensor(string_format(TN_CONV_NORM, prefix, il, "bias"));
  1522. layer.conv_dw_w = get_tensor(string_format(TN_CONV_DW, prefix, il, "weight"));
  1523. layer.conv_dw_b = get_tensor(string_format(TN_CONV_DW, prefix, il, "bias"));
  1524. layer.conv_pw1_w = get_tensor(string_format(TN_CONV_PW1, prefix, il, "weight"));
  1525. layer.conv_pw1_b = get_tensor(string_format(TN_CONV_PW1, prefix, il, "bias"));
  1526. layer.conv_pw2_w = get_tensor(string_format(TN_CONV_PW2, prefix, il, "weight"));
  1527. layer.conv_pw2_b = get_tensor(string_format(TN_CONV_PW2, prefix, il, "bias"));
  1528. }
  1529. } break;
  1530. default:
  1531. GGML_ASSERT(false && "unknown projector type");
  1532. }
  1533. // load data
  1534. {
  1535. std::vector<uint8_t> read_buf;
  1536. auto fin = std::ifstream(fname, std::ios::binary);
  1537. if (!fin) {
  1538. throw std::runtime_error(string_format("%s: failed to open %s\n", __func__, fname.c_str()));
  1539. }
  1540. // alloc memory and offload data
  1541. ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(ctx_clip.backend);
  1542. ctx_clip.buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_clip.ctx_data.get(), buft));
  1543. ggml_backend_buffer_set_usage(ctx_clip.buf.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  1544. for (auto & t : tensors_to_load) {
  1545. ggml_tensor * cur = ggml_get_tensor(ctx_clip.ctx_data.get(), t->name);
  1546. const size_t offset = tensor_offset[t->name];
  1547. fin.seekg(offset, std::ios::beg);
  1548. if (!fin) {
  1549. throw std::runtime_error(string_format("%s: failed to seek for tensor %s\n", __func__, t->name));
  1550. }
  1551. size_t num_bytes = ggml_nbytes(cur);
  1552. if (ggml_backend_buft_is_host(buft)) {
  1553. // for the CPU and Metal backend, we can read directly into the tensor
  1554. fin.read(reinterpret_cast<char *>(cur->data), num_bytes);
  1555. } else {
  1556. // read into a temporary buffer first, then copy to device memory
  1557. read_buf.resize(num_bytes);
  1558. fin.read(reinterpret_cast<char *>(read_buf.data()), num_bytes);
  1559. ggml_backend_tensor_set(cur, read_buf.data(), 0, num_bytes);
  1560. }
  1561. }
  1562. fin.close();
  1563. LOG_DBG("%s: loaded %zu tensors from %s\n", __func__, tensors_to_load.size(), fname.c_str());
  1564. }
  1565. }
  1566. struct support_info_op {
  1567. ggml_tensor * op;
  1568. // true if the op runs on the accelerated ctx_clip.backend
  1569. bool is_accel = true;
  1570. };
  1571. struct support_info_graph {
  1572. // whether the clip_ctx.backend supports flash attention
  1573. bool fattn = true;
  1574. ggml_tensor * fattn_op = nullptr; // for debugging
  1575. std::vector<support_info_op> ops;
  1576. };
  1577. static void warmup(clip_ctx & ctx_clip) {
  1578. // create a fake batch
  1579. const auto & hparams = ctx_clip.model.hparams;
  1580. clip_image_f32_batch batch;
  1581. clip_image_f32_ptr img(clip_image_f32_init());
  1582. if (ctx_clip.model.modality == CLIP_MODALITY_VISION) {
  1583. img->nx = hparams.warmup_image_size;
  1584. img->ny = hparams.warmup_image_size;
  1585. LOG_INF("%s: warmup with image size = %d x %d\n", __func__, img->nx, img->ny);
  1586. } else {
  1587. img->nx = hparams.warmup_audio_size;
  1588. img->ny = hparams.n_mel_bins;
  1589. LOG_INF("%s: warmup with audio size = %d\n", __func__, img->nx);
  1590. }
  1591. batch.entries.push_back(std::move(img));
  1592. warmup(ctx_clip, batch);
  1593. }
  1594. static void warmup(clip_ctx & ctx_clip, const clip_image_f32_batch & batch) {
  1595. support_info_graph info;
  1596. if (ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_AUTO) {
  1597. // try to enable flash attention to see if it's supported
  1598. ctx_clip.flash_attn_type = CLIP_FLASH_ATTN_TYPE_ENABLED;
  1599. info = alloc_compute_meta(ctx_clip, batch);
  1600. if (!info.fattn && info.fattn_op) {
  1601. auto op = info.fattn_op;
  1602. LOG_WRN("%s: *****************************************************************\n", __func__);
  1603. LOG_WRN("%s: WARNING: flash attention not supported by %s, memory usage will increase\n", __func__, ggml_backend_name(ctx_clip.backend));
  1604. LOG_WRN("%s: op params: \n", __func__);
  1605. static auto print_shape = [](const char * fn, const char * name, ggml_tensor * t) {
  1606. LOG_WRN("%s: %s: type = %s, ne = [%d %d %d %d], nb = [%d %d %d %d]\n", fn,
  1607. name, ggml_type_name(t->type),
  1608. t->ne[0], t->ne[1], t->ne[2], t->ne[3],
  1609. t->nb[0], t->nb[1], t->nb[2], t->nb[3]);
  1610. };
  1611. print_shape(__func__, " dst", op);
  1612. print_shape(__func__, "src0", op->src[0]);
  1613. print_shape(__func__, "src1", op->src[1]);
  1614. print_shape(__func__, "src2", op->src[2]);
  1615. LOG_WRN("%s: please report this on github as an issue\n", __func__);
  1616. LOG_WRN("%s: *****************************************************************\n", __func__);
  1617. ctx_clip.flash_attn_type = CLIP_FLASH_ATTN_TYPE_DISABLED;
  1618. alloc_compute_meta(ctx_clip, batch);
  1619. }
  1620. } else {
  1621. info = alloc_compute_meta(ctx_clip, batch);
  1622. if (!info.fattn && ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) {
  1623. LOG_WRN("%s: flash attention is not supported by the current backend; falling back to CPU (performance will be degraded)\n", __func__);
  1624. }
  1625. }
  1626. ctx_clip.is_allocated = true; // mark buffers as allocated
  1627. LOG_INF("%s: flash attention is %s\n", __func__,
  1628. (ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) ? "enabled" : "disabled");
  1629. // print ops that are not supported by the GPU backend (if there is one)
  1630. if (ctx_clip.backend && ctx_clip.backend != ctx_clip.backend_cpu) {
  1631. std::vector<support_info_op> unsupported_ops;
  1632. for (const auto & op : info.ops) {
  1633. if (!op.is_accel) {
  1634. unsupported_ops.push_back(op);
  1635. }
  1636. }
  1637. if (!unsupported_ops.empty()) {
  1638. LOG_WRN("%s: *****************************************************************\n", __func__);
  1639. LOG_WRN("%s: WARNING: the CLIP graph uses unsupported operators by the backend\n", __func__);
  1640. LOG_WRN("%s: the performance will be suboptimal \n", __func__);
  1641. LOG_WRN("%s: list of unsupported ops (backend=%s):\n", __func__, ggml_backend_name(ctx_clip.backend));
  1642. for (const auto & op : unsupported_ops) {
  1643. LOG_WRN("%s: %16s: type = %s, ne = [%d %d %d %d]\n", __func__,
  1644. ggml_op_name(op.op->op),
  1645. ggml_type_name(op.op->type),
  1646. op.op->ne[0], op.op->ne[1], op.op->ne[2], op.op->ne[3]);
  1647. }
  1648. LOG_WRN("%s: flash attention is %s\n", __func__,
  1649. (ctx_clip.flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) ? "enabled" : "disabled");
  1650. LOG_WRN("%s: please report this on github as an issue\n", __func__);
  1651. LOG_WRN("%s: ref: https://github.com/ggml-org/llama.cpp/pull/16837#issuecomment-3461676118\n", __func__);
  1652. LOG_WRN("%s: *****************************************************************\n", __func__);
  1653. }
  1654. }
  1655. }
  1656. static support_info_graph alloc_compute_meta(clip_ctx & ctx_clip, const clip_image_f32_batch & batch) {
  1657. ctx_clip.buf_compute_meta.resize(ctx_clip.max_nodes * ggml_tensor_overhead() + ggml_graph_overhead());
  1658. ggml_cgraph * gf = clip_image_build_graph(&ctx_clip, batch);
  1659. ggml_backend_sched_reserve(ctx_clip.sched.get(), gf);
  1660. for (size_t i = 0; i < ctx_clip.backend_ptrs.size(); ++i) {
  1661. ggml_backend_t backend = ctx_clip.backend_ptrs[i];
  1662. ggml_backend_buffer_type_t buft = ctx_clip.backend_buft[i];
  1663. size_t size = ggml_backend_sched_get_buffer_size(ctx_clip.sched.get(), backend);
  1664. if (size > 1) {
  1665. LOG_INF("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  1666. ggml_backend_buft_name(buft),
  1667. size / 1024.0 / 1024.0);
  1668. }
  1669. }
  1670. const int n_splits = ggml_backend_sched_get_n_splits(ctx_clip.sched.get());
  1671. const int n_nodes = ggml_graph_n_nodes(gf);
  1672. LOG_INF("%s: graph splits = %d, nodes = %d\n", __func__, n_splits, n_nodes);
  1673. support_info_graph res {
  1674. /*.fattn = */ true,
  1675. /*.fattn_op = */ nullptr,
  1676. /*.ops = */ {},
  1677. };
  1678. // check op support
  1679. for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
  1680. ggml_tensor * node = ggml_graph_node(gf, i);
  1681. res.ops.push_back({node, true});
  1682. if (!ggml_backend_supports_op(ctx_clip.backend, node)) {
  1683. res.ops.back().is_accel = false;
  1684. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1685. res.fattn = false;
  1686. res.fattn_op = node;
  1687. }
  1688. }
  1689. }
  1690. return res;
  1691. }
  1692. void get_bool(const std::string & key, bool & output, bool required = true) const {
  1693. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1694. if (i < 0) {
  1695. if (required) {
  1696. throw std::runtime_error("Key not found: " + key);
  1697. }
  1698. return;
  1699. }
  1700. output = gguf_get_val_bool(ctx_gguf.get(), i);
  1701. }
  1702. void get_i32(const std::string & key, int & output, bool required = true) const {
  1703. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1704. if (i < 0) {
  1705. if (required) {
  1706. throw std::runtime_error("Key not found: " + key);
  1707. }
  1708. return;
  1709. }
  1710. output = gguf_get_val_i32(ctx_gguf.get(), i);
  1711. }
  1712. void get_u32(const std::string & key, int & output, bool required = true) const {
  1713. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1714. if (i < 0) {
  1715. if (required) {
  1716. throw std::runtime_error("Key not found: " + key);
  1717. }
  1718. return;
  1719. }
  1720. output = gguf_get_val_u32(ctx_gguf.get(), i);
  1721. }
  1722. void get_f32(const std::string & key, float & output, bool required = true) const {
  1723. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1724. if (i < 0) {
  1725. if (required) {
  1726. throw std::runtime_error("Key not found: " + key);
  1727. }
  1728. return;
  1729. }
  1730. output = gguf_get_val_f32(ctx_gguf.get(), i);
  1731. }
  1732. void get_string(const std::string & key, std::string & output, bool required = true) const {
  1733. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1734. if (i < 0) {
  1735. if (required) {
  1736. throw std::runtime_error("Key not found: " + key);
  1737. }
  1738. return;
  1739. }
  1740. output = std::string(gguf_get_val_str(ctx_gguf.get(), i));
  1741. }
  1742. void get_arr_int(const std::string & key, std::vector<int> & output, bool required = true) const {
  1743. const int i = gguf_find_key(ctx_gguf.get(), key.c_str());
  1744. if (i < 0) {
  1745. if (required) {
  1746. throw std::runtime_error("Key not found: " + key);
  1747. }
  1748. return;
  1749. }
  1750. int n = gguf_get_arr_n(ctx_gguf.get(), i);
  1751. output.resize(n);
  1752. const int32_t * values = (const int32_t *)gguf_get_arr_data(ctx_gguf.get(), i);
  1753. for (int i = 0; i < n; ++i) {
  1754. output[i] = values[i];
  1755. }
  1756. }
  1757. static void set_llava_uhd_res_candidates(clip_model & model, const int max_patches_per_side) {
  1758. auto & hparams = model.hparams;
  1759. for (int x = 1; x <= max_patches_per_side; x++) {
  1760. for (int y = 1; y <= max_patches_per_side; y++) {
  1761. if (x == 1 && y == 1) {
  1762. continue; // skip the first point
  1763. }
  1764. hparams.image_res_candidates.push_back(clip_image_size{
  1765. x*hparams.image_size,
  1766. y*hparams.image_size,
  1767. });
  1768. }
  1769. }
  1770. }
  1771. };
  1772. struct clip_init_result clip_init(const char * fname, struct clip_context_params ctx_params) {
  1773. clip_ctx * ctx_vision = nullptr;
  1774. clip_ctx * ctx_audio = nullptr;
  1775. try {
  1776. clip_model_loader loader(fname);
  1777. if (loader.has_vision) {
  1778. ctx_vision = new clip_ctx(ctx_params);
  1779. loader.load_hparams(ctx_vision->model, CLIP_MODALITY_VISION);
  1780. loader.load_tensors(*ctx_vision);
  1781. if (ctx_params.warmup) {
  1782. loader.warmup(*ctx_vision);
  1783. }
  1784. // clip_debug_encode(ctx_vision, 24*14, 24*14, 0.5f);
  1785. }
  1786. if (loader.has_audio) {
  1787. ctx_audio = new clip_ctx(ctx_params);
  1788. loader.load_hparams(ctx_audio->model, CLIP_MODALITY_AUDIO);
  1789. loader.load_tensors(*ctx_audio);
  1790. if (ctx_params.warmup) {
  1791. loader.warmup(*ctx_audio);
  1792. }
  1793. }
  1794. } catch (const std::exception & e) {
  1795. LOG_ERR("%s: failed to load model '%s': %s\n", __func__, fname, e.what());
  1796. delete ctx_vision;
  1797. delete ctx_audio;
  1798. return {nullptr, nullptr};
  1799. }
  1800. return {ctx_vision, ctx_audio};
  1801. }
  1802. struct clip_image_size * clip_image_size_init() {
  1803. struct clip_image_size * load_image_size = new struct clip_image_size();
  1804. load_image_size->width = 448;
  1805. load_image_size->height = 448;
  1806. return load_image_size;
  1807. }
  1808. struct clip_image_u8 * clip_image_u8_init() {
  1809. return new clip_image_u8();
  1810. }
  1811. struct clip_image_f32 * clip_image_f32_init() {
  1812. return new clip_image_f32();
  1813. }
  1814. struct clip_image_f32_batch * clip_image_f32_batch_init() {
  1815. return new clip_image_f32_batch();
  1816. }
  1817. unsigned char * clip_image_u8_get_data(struct clip_image_u8 * img, uint32_t * nx, uint32_t * ny) {
  1818. if (nx) *nx = img->nx;
  1819. if (ny) *ny = img->ny;
  1820. return img->buf.data();
  1821. }
  1822. void clip_image_size_free(struct clip_image_size * load_image_size) {
  1823. if (load_image_size == nullptr) {
  1824. return;
  1825. }
  1826. delete load_image_size;
  1827. }
  1828. void clip_image_u8_free(struct clip_image_u8 * img) { delete img; }
  1829. void clip_image_f32_free(struct clip_image_f32 * img) { delete img; }
  1830. void clip_image_u8_batch_free(struct clip_image_u8_batch * batch) { delete batch; }
  1831. void clip_image_f32_batch_free(struct clip_image_f32_batch * batch) { delete batch; }
  1832. size_t clip_image_f32_batch_n_images(const struct clip_image_f32_batch * batch) {
  1833. return batch->entries.size();
  1834. }
  1835. size_t clip_image_f32_batch_nx(const struct clip_image_f32_batch * batch, int idx) {
  1836. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1837. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1838. return 0;
  1839. }
  1840. return batch->entries[idx]->nx;
  1841. }
  1842. size_t clip_image_f32_batch_ny(const struct clip_image_f32_batch * batch, int idx) {
  1843. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1844. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1845. return 0;
  1846. }
  1847. return batch->entries[idx]->ny;
  1848. }
  1849. clip_image_f32 * clip_image_f32_get_img(const struct clip_image_f32_batch * batch, int idx) {
  1850. if (idx < 0 || idx >= (int)batch->entries.size()) {
  1851. LOG_ERR("%s: invalid index %d\n", __func__, idx);
  1852. return nullptr;
  1853. }
  1854. return batch->entries[idx].get();
  1855. }
  1856. void clip_build_img_from_pixels(const unsigned char * rgb_pixels, int nx, int ny, clip_image_u8 * img) {
  1857. img->nx = nx;
  1858. img->ny = ny;
  1859. img->buf.resize(3 * nx * ny);
  1860. memcpy(img->buf.data(), rgb_pixels, img->buf.size());
  1861. }
  1862. // Normalize image to float32 - careful with pytorch .to(model.device, dtype=torch.float16) - this sometimes reduces precision (32>16>32), sometimes not
  1863. static void normalize_image_u8_to_f32(const clip_image_u8 & src, clip_image_f32 & dst, const float mean[3], const float std[3]) {
  1864. dst.nx = src.nx;
  1865. dst.ny = src.ny;
  1866. dst.buf.resize(src.buf.size());
  1867. // TODO @ngxson : seems like this could be done more efficiently on cgraph
  1868. for (size_t i = 0; i < src.buf.size(); ++i) {
  1869. int c = i % 3; // rgb
  1870. dst.buf[i] = (static_cast<float>(src.buf[i]) / 255.0f - mean[c]) / std[c];
  1871. }
  1872. }
  1873. // set of tools to manupulate images
  1874. // in the future, we can have HW acceleration by allowing this struct to access 3rd party lib like imagick or opencv
  1875. struct img_tool {
  1876. enum resize_algo {
  1877. RESIZE_ALGO_BILINEAR,
  1878. RESIZE_ALGO_BICUBIC,
  1879. // RESIZE_ALGO_LANCZOS, // TODO
  1880. };
  1881. static void resize(
  1882. const clip_image_u8 & src,
  1883. clip_image_u8 & dst,
  1884. const clip_image_size & target_resolution,
  1885. resize_algo algo,
  1886. bool add_padding = true, // TODO: define the behavior for add_padding = false
  1887. std::array<uint8_t, 3> pad_color = {0, 0, 0}) {
  1888. dst.nx = target_resolution.width;
  1889. dst.ny = target_resolution.height;
  1890. dst.buf.resize(3 * dst.nx * dst.ny);
  1891. if (dst.nx == src.nx && dst.ny == src.ny) {
  1892. // no resize needed, simple copy
  1893. dst.buf = src.buf;
  1894. return;
  1895. }
  1896. if (!add_padding) {
  1897. // direct resize
  1898. switch (algo) {
  1899. case RESIZE_ALGO_BILINEAR:
  1900. resize_bilinear(src, dst, target_resolution.width, target_resolution.height);
  1901. break;
  1902. case RESIZE_ALGO_BICUBIC:
  1903. resize_bicubic(src, dst, target_resolution.width, target_resolution.height);
  1904. break;
  1905. default:
  1906. throw std::runtime_error("Unsupported resize algorithm");
  1907. }
  1908. } else {
  1909. // resize with padding
  1910. clip_image_u8 resized_image;
  1911. float scale_w = static_cast<float>(target_resolution.width) / src.nx;
  1912. float scale_h = static_cast<float>(target_resolution.height) / src.ny;
  1913. float scale = std::min(scale_w, scale_h);
  1914. int new_width = std::min(static_cast<int>(std::ceil(src.nx * scale)), target_resolution.width);
  1915. int new_height = std::min(static_cast<int>(std::ceil(src.ny * scale)), target_resolution.height);
  1916. switch (algo) {
  1917. case RESIZE_ALGO_BILINEAR:
  1918. resize_bilinear(src, resized_image, new_width, new_height);
  1919. break;
  1920. case RESIZE_ALGO_BICUBIC:
  1921. resize_bicubic(src, resized_image, new_width, new_height);
  1922. break;
  1923. default:
  1924. throw std::runtime_error("Unsupported resize algorithm");
  1925. }
  1926. // fill dst with pad_color
  1927. fill(dst, pad_color);
  1928. int offset_x = (target_resolution.width - new_width) / 2;
  1929. int offset_y = (target_resolution.height - new_height) / 2;
  1930. composite(dst, resized_image, offset_x, offset_y);
  1931. }
  1932. }
  1933. static void crop(const clip_image_u8 & image, clip_image_u8 & dst, int x, int y, int w, int h) {
  1934. dst.nx = w;
  1935. dst.ny = h;
  1936. dst.buf.resize(3 * w * h);
  1937. for (int i = 0; i < h; ++i) {
  1938. for (int j = 0; j < w; ++j) {
  1939. int src_idx = 3 * ((y + i)*image.nx + (x + j));
  1940. int dst_idx = 3 * (i*w + j);
  1941. dst.buf[dst_idx] = image.buf[src_idx];
  1942. dst.buf[dst_idx + 1] = image.buf[src_idx + 1];
  1943. dst.buf[dst_idx + 2] = image.buf[src_idx + 2];
  1944. }
  1945. }
  1946. }
  1947. // calculate the size of the **resized** image, while preserving the aspect ratio
  1948. // the calculated size will be aligned to the nearest multiple of align_size
  1949. // if H or W size is larger than longest_edge, it will be resized to longest_edge
  1950. static clip_image_size calc_size_preserved_ratio(const clip_image_size & inp_size, const int align_size, const int longest_edge) {
  1951. GGML_ASSERT(align_size > 0);
  1952. if (inp_size.width <= 0 || inp_size.height <= 0 || longest_edge <= 0) {
  1953. return {0, 0};
  1954. }
  1955. float scale = std::min(static_cast<float>(longest_edge) / inp_size.width,
  1956. static_cast<float>(longest_edge) / inp_size.height);
  1957. float target_width_f = static_cast<float>(inp_size.width) * scale;
  1958. float target_height_f = static_cast<float>(inp_size.height) * scale;
  1959. auto ceil_by_factor = [f = align_size](float x) { return static_cast<int>(std::ceil(x / static_cast<float>(f))) * f; };
  1960. int aligned_width = ceil_by_factor(target_width_f);
  1961. int aligned_height = ceil_by_factor(target_height_f);
  1962. return {aligned_width, aligned_height};
  1963. }
  1964. // calculate the size of the **resized** image, while preserving the aspect ratio
  1965. // the calculated size will have min_pixels <= W*H <= max_pixels
  1966. // this is referred as "smart_resize" in transformers code
  1967. static clip_image_size calc_size_preserved_ratio(const clip_image_size & inp_size, const int align_size, const int min_pixels, const int max_pixels) {
  1968. GGML_ASSERT(align_size > 0);
  1969. const int width = inp_size.width;
  1970. const int height = inp_size.height;
  1971. auto round_by_factor = [f = align_size](float x) { return static_cast<int>(std::round(x / static_cast<float>(f))) * f; };
  1972. auto ceil_by_factor = [f = align_size](float x) { return static_cast<int>(std::ceil(x / static_cast<float>(f))) * f; };
  1973. auto floor_by_factor = [f = align_size](float x) { return static_cast<int>(std::floor(x / static_cast<float>(f))) * f; };
  1974. // always align up first
  1975. int h_bar = std::max(align_size, round_by_factor(height));
  1976. int w_bar = std::max(align_size, round_by_factor(width));
  1977. if (h_bar * w_bar > max_pixels) {
  1978. const auto beta = std::sqrt(static_cast<float>(height * width) / max_pixels);
  1979. h_bar = std::max(align_size, floor_by_factor(height / beta));
  1980. w_bar = std::max(align_size, floor_by_factor(width / beta));
  1981. } else if (h_bar * w_bar < min_pixels) {
  1982. const auto beta = std::sqrt(static_cast<float>(min_pixels) / (height * width));
  1983. h_bar = ceil_by_factor(height * beta);
  1984. w_bar = ceil_by_factor(width * beta);
  1985. }
  1986. return {w_bar, h_bar};
  1987. }
  1988. // draw src image into dst image at offset (offset_x, offset_y)
  1989. static void composite(clip_image_u8 & dst, const clip_image_u8 & src, int offset_x, int offset_y) {
  1990. for (int y = 0; y < src.ny; ++y) {
  1991. for (int x = 0; x < src.nx; ++x) {
  1992. int dx = x + offset_x;
  1993. int dy = y + offset_y;
  1994. // skip pixels that would be out of bounds in the destination
  1995. if (dx < 0 || dy < 0 || dx >= dst.nx || dy >= dst.ny) {
  1996. continue;
  1997. }
  1998. size_t dst_idx = 3 * (static_cast<size_t>(dy) * dst.nx + static_cast<size_t>(dx));
  1999. size_t src_idx = 3 * (static_cast<size_t>(y) * src.nx + static_cast<size_t>(x));
  2000. dst.buf[dst_idx + 0] = src.buf[src_idx + 0];
  2001. dst.buf[dst_idx + 1] = src.buf[src_idx + 1];
  2002. dst.buf[dst_idx + 2] = src.buf[src_idx + 2];
  2003. }
  2004. }
  2005. }
  2006. // fill the image with a solid color
  2007. static void fill(clip_image_u8 & img, const std::array<uint8_t, 3> & color) {
  2008. for (size_t i = 0; i < img.buf.size(); i += 3) {
  2009. img.buf[i] = color[0];
  2010. img.buf[i + 1] = color[1];
  2011. img.buf[i + 2] = color[2];
  2012. }
  2013. }
  2014. private:
  2015. // Bilinear resize function
  2016. static void resize_bilinear(const clip_image_u8 & src, clip_image_u8 & dst, int target_width, int target_height) {
  2017. dst.nx = target_width;
  2018. dst.ny = target_height;
  2019. dst.buf.resize(3 * target_width * target_height);
  2020. float x_ratio = static_cast<float>(src.nx - 1) / target_width;
  2021. float y_ratio = static_cast<float>(src.ny - 1) / target_height;
  2022. for (int y = 0; y < target_height; y++) {
  2023. for (int x = 0; x < target_width; x++) {
  2024. float px = x_ratio * x;
  2025. float py = y_ratio * y;
  2026. int x_floor = static_cast<int>(px);
  2027. int y_floor = static_cast<int>(py);
  2028. float x_lerp = px - x_floor;
  2029. float y_lerp = py - y_floor;
  2030. for (int c = 0; c < 3; c++) {
  2031. float top = lerp(
  2032. static_cast<float>(src.buf[3 * (y_floor * src.nx + x_floor) + c]),
  2033. static_cast<float>(src.buf[3 * (y_floor * src.nx + (x_floor + 1)) + c]),
  2034. x_lerp
  2035. );
  2036. float bottom = lerp(
  2037. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + x_floor) + c]),
  2038. static_cast<float>(src.buf[3 * ((y_floor + 1) * src.nx + (x_floor + 1)) + c]),
  2039. x_lerp
  2040. );
  2041. dst.buf[3 * (y * target_width + x) + c] = static_cast<uint8_t>(lerp(top, bottom, y_lerp));
  2042. }
  2043. }
  2044. }
  2045. }
  2046. // Bicubic resize function
  2047. // part of image will be cropped if the aspect ratio is different
  2048. static bool resize_bicubic(const clip_image_u8 & img, clip_image_u8 & dst, int target_width, int target_height) {
  2049. const int nx = img.nx;
  2050. const int ny = img.ny;
  2051. dst.nx = target_width;
  2052. dst.ny = target_height;
  2053. dst.buf.resize(3 * target_width * target_height);
  2054. float Cc;
  2055. float C[5] = {};
  2056. float d0, d2, d3, a0, a1, a2, a3;
  2057. int i, j, k, jj;
  2058. int x, y;
  2059. float dx, dy;
  2060. float tx, ty;
  2061. tx = (float)nx / (float)target_width;
  2062. ty = (float)ny / (float)target_height;
  2063. // Bicubic interpolation; adapted from ViT.cpp, inspired from :
  2064. // -> https://github.com/yglukhov/bicubic-interpolation-image-processing/blob/master/libimage.c#L36
  2065. // -> https://en.wikipedia.org/wiki/Bicubic_interpolation
  2066. for (i = 0; i < target_height; i++) {
  2067. for (j = 0; j < target_width; j++) {
  2068. x = (int)(tx * j);
  2069. y = (int)(ty * i);
  2070. dx = tx * j - x;
  2071. dy = ty * i - y;
  2072. for (k = 0; k < 3; k++) {
  2073. for (jj = 0; jj <= 3; jj++) {
  2074. d0 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x - 1, 0, nx - 1)) * 3 + k] - img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  2075. d2 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x + 1, 0, nx - 1)) * 3 + k] - img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  2076. d3 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x + 2, 0, nx - 1)) * 3 + k] - img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  2077. a0 = img.buf[(clip(y - 1 + jj, 0, ny - 1) * nx + clip(x, 0, nx - 1)) * 3 + k];
  2078. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  2079. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  2080. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  2081. C[jj] = a0 + a1 * dx + a2 * dx * dx + a3 * dx * dx * dx;
  2082. d0 = C[0] - C[1];
  2083. d2 = C[2] - C[1];
  2084. d3 = C[3] - C[1];
  2085. a0 = C[1];
  2086. a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
  2087. a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
  2088. a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
  2089. Cc = a0 + a1 * dy + a2 * dy * dy + a3 * dy * dy * dy;
  2090. const uint8_t Cc2 = std::min(std::max(std::round(Cc), 0.0f), 255.0f);
  2091. dst.buf[(i * target_width + j) * 3 + k] = float(Cc2);
  2092. }
  2093. }
  2094. }
  2095. }
  2096. return true;
  2097. }
  2098. static inline int clip(int x, int lower, int upper) {
  2099. return std::max(lower, std::min(x, upper));
  2100. }
  2101. // Linear interpolation between two points
  2102. static inline float lerp(float s, float e, float t) {
  2103. return s + (e - s) * t;
  2104. }
  2105. };
  2106. /**
  2107. * implementation of LLaVA-UHD:
  2108. * - https://arxiv.org/pdf/2403.11703
  2109. * - https://github.com/thunlp/LLaVA-UHD
  2110. * - https://github.com/thunlp/LLaVA-UHD/blob/302301bc2175f7e717fb8548516188e89f649753/llava_uhd/train/llava-uhd/slice_logic.py#L118
  2111. *
  2112. * overview:
  2113. * - an image always have a single overview (downscaled image)
  2114. * - an image can have 0 or multiple slices, depending on the image size
  2115. * - each slice can then be considered as a separate image
  2116. *
  2117. * for example:
  2118. *
  2119. * [overview] --> [slice 1] --> [slice 2]
  2120. * | |
  2121. * +--> [slice 3] --> [slice 4]
  2122. */
  2123. struct llava_uhd {
  2124. struct slice_coordinates {
  2125. int x;
  2126. int y;
  2127. clip_image_size size;
  2128. };
  2129. struct slice_instructions {
  2130. clip_image_size overview_size; // size of downscaled image
  2131. clip_image_size refined_size; // size of image right before slicing (must be multiple of slice size)
  2132. clip_image_size grid_size; // grid_size.width * grid_size.height = number of slices
  2133. std::vector<slice_coordinates> slices;
  2134. img_tool::resize_algo interpolation_overview = img_tool::RESIZE_ALGO_BILINEAR;
  2135. bool padding_overview = false; // if true, refine image will be padded to the grid size (e.g. llava-1.6)
  2136. std::array<uint8_t, 3> pad_color_overview = {0, 0, 0};
  2137. img_tool::resize_algo interpolation_refined = img_tool::RESIZE_ALGO_BICUBIC;
  2138. bool padding_refined = false; // if true, refine image will be padded to the grid size (e.g. llava-1.6)
  2139. std::array<uint8_t, 3> pad_color_refined = {0, 0, 0};
  2140. };
  2141. static slice_instructions get_slice_instructions(struct clip_ctx * ctx, const clip_image_size & original_size) {
  2142. slice_instructions res;
  2143. const int patch_size = clip_get_patch_size(ctx);
  2144. const int slice_size = clip_get_image_size(ctx);
  2145. const int original_width = original_size.width;
  2146. const int original_height = original_size.height;
  2147. const bool has_slices = original_size.width > slice_size || original_size.height > slice_size;
  2148. const bool has_pinpoints = !ctx->model.hparams.image_res_candidates.empty();
  2149. if (!has_slices) {
  2150. // skip slicing logic
  2151. res.overview_size = clip_image_size{slice_size, slice_size};
  2152. res.refined_size = clip_image_size{0, 0};
  2153. res.grid_size = clip_image_size{0, 0};
  2154. return res;
  2155. }
  2156. if (has_pinpoints) {
  2157. // has pinpoints, use them to calculate the grid size (e.g. llava-1.6)
  2158. auto refine_size = llava_uhd::select_best_resolution(
  2159. original_size,
  2160. ctx->model.hparams.image_res_candidates);
  2161. res.overview_size = clip_image_size{slice_size, slice_size};
  2162. res.refined_size = refine_size;
  2163. res.grid_size = clip_image_size{0, 0};
  2164. res.padding_refined = true;
  2165. res.interpolation_refined = img_tool::RESIZE_ALGO_BILINEAR; // preserve old behavior when padding
  2166. LOG_DBG("%s: using pinpoints for slicing\n", __func__);
  2167. LOG_DBG("%s: original size: %d x %d, overview size: %d x %d, refined size: %d x %d\n",
  2168. __func__, original_width, original_height,
  2169. res.overview_size.width, res.overview_size.height,
  2170. res.refined_size.width, res.refined_size.height);
  2171. for (int y = 0; y < refine_size.height; y += slice_size) {
  2172. for (int x = 0; x < refine_size.width; x += slice_size) {
  2173. slice_coordinates slice;
  2174. slice.x = x;
  2175. slice.y = y;
  2176. slice.size.width = std::min(slice_size, refine_size.width - x);
  2177. slice.size.height = std::min(slice_size, refine_size.height - y);
  2178. res.slices.push_back(slice);
  2179. LOG_DBG("%s: slice %d: x=%d, y=%d, size=%dx%d\n",
  2180. __func__, (int)res.slices.size() - 1,
  2181. slice.x, slice.y, slice.size.width, slice.size.height);
  2182. }
  2183. }
  2184. res.grid_size.height = refine_size.height / slice_size;
  2185. res.grid_size.width = refine_size.width / slice_size;
  2186. LOG_DBG("%s: grid size: %d x %d\n", __func__, res.grid_size.width, res.grid_size.height);
  2187. return res;
  2188. }
  2189. // no pinpoints, dynamically calculate the grid size (e.g. minicpmv)
  2190. auto best_size = get_best_resize(original_size, slice_size, patch_size, !has_slices);
  2191. res.overview_size = best_size;
  2192. {
  2193. const int max_slice_nums = 9; // TODO: this is only used by minicpmv, maybe remove it
  2194. const float log_ratio = log((float)original_width / original_height);
  2195. const float ratio = (float)original_width * original_height / (slice_size * slice_size);
  2196. const int multiple = fmin(ceil(ratio), max_slice_nums);
  2197. auto best_grid = get_best_grid(max_slice_nums, multiple, log_ratio);
  2198. auto refine_size = get_refine_size(original_size, best_grid, slice_size, patch_size, true);
  2199. res.grid_size = best_grid;
  2200. res.refined_size = refine_size;
  2201. LOG_DBG("%s: original size: %d x %d, overview size: %d x %d, refined size: %d x %d, grid size: %d x %d\n",
  2202. __func__, original_width, original_height,
  2203. res.overview_size.width, res.overview_size.height,
  2204. res.refined_size.width, res.refined_size.height,
  2205. res.grid_size.width, res.grid_size.height);
  2206. int width = refine_size.width;
  2207. int height = refine_size.height;
  2208. int grid_x = int(width / best_grid.width);
  2209. int grid_y = int(height / best_grid.height);
  2210. for (int patches_y = 0, ic = 0;
  2211. patches_y < refine_size.height && ic < best_grid.height;
  2212. patches_y += grid_y, ic += 1) {
  2213. for (int patches_x = 0, jc = 0;
  2214. patches_x < refine_size.width && jc < best_grid.width;
  2215. patches_x += grid_x, jc += 1) {
  2216. slice_coordinates slice;
  2217. slice.x = patches_x;
  2218. slice.y = patches_y;
  2219. slice.size.width = grid_x;
  2220. slice.size.height = grid_y;
  2221. res.slices.push_back(slice);
  2222. LOG_DBG("%s: slice %d: x=%d, y=%d, size=%dx%d\n",
  2223. __func__, (int)res.slices.size() - 1,
  2224. slice.x, slice.y, slice.size.width, slice.size.height);
  2225. }
  2226. }
  2227. }
  2228. return res;
  2229. }
  2230. static std::vector<clip_image_u8_ptr> slice_image(const clip_image_u8 * img, const slice_instructions & inst) {
  2231. std::vector<clip_image_u8_ptr> output;
  2232. // resize to overview size
  2233. clip_image_u8_ptr resized_img(clip_image_u8_init());
  2234. img_tool::resize(*img, *resized_img, inst.overview_size, inst.interpolation_overview,
  2235. inst.padding_overview, inst.pad_color_overview);
  2236. output.push_back(std::move(resized_img));
  2237. if (inst.slices.empty()) {
  2238. // no slices, just return the resized image
  2239. return output;
  2240. }
  2241. // resize to refined size
  2242. clip_image_u8_ptr refined_img(clip_image_u8_init());
  2243. img_tool::resize(*img, *refined_img, inst.refined_size, inst.interpolation_refined,
  2244. inst.padding_refined, inst.pad_color_refined);
  2245. // create slices
  2246. for (const auto & slice : inst.slices) {
  2247. int x = slice.x;
  2248. int y = slice.y;
  2249. int w = slice.size.width;
  2250. int h = slice.size.height;
  2251. clip_image_u8_ptr img_slice(clip_image_u8_init());
  2252. img_tool::crop(*refined_img, *img_slice, x, y, w, h);
  2253. output.push_back(std::move(img_slice));
  2254. }
  2255. return output;
  2256. }
  2257. private:
  2258. static clip_image_size get_best_resize(const clip_image_size & original_size, int scale_resolution, int patch_size, bool allow_upscale = false) {
  2259. int width = original_size.width;
  2260. int height = original_size.height;
  2261. if ((width * height > scale_resolution * scale_resolution) || allow_upscale) {
  2262. float r = static_cast<float>(width) / height;
  2263. height = static_cast<int>(scale_resolution / std::sqrt(r));
  2264. width = static_cast<int>(height * r);
  2265. }
  2266. clip_image_size res;
  2267. res.width = ensure_divide(width, patch_size);
  2268. res.height = ensure_divide(height, patch_size);
  2269. return res;
  2270. }
  2271. static clip_image_size resize_maintain_aspect_ratio(const clip_image_size & orig, const clip_image_size & target_max) {
  2272. float scale_width = static_cast<float>(target_max.width) / orig.width;
  2273. float scale_height = static_cast<float>(target_max.height) / orig.height;
  2274. float scale = std::min(scale_width, scale_height);
  2275. return clip_image_size{
  2276. static_cast<int>(orig.width * scale),
  2277. static_cast<int>(orig.height * scale),
  2278. };
  2279. }
  2280. /**
  2281. * Selects the best resolution from a list of possible resolutions based on the original size.
  2282. *
  2283. * For example, when given a list of resolutions:
  2284. * - 100x100
  2285. * - 200x100
  2286. * - 100x200
  2287. * - 200x200
  2288. *
  2289. * And an input image of size 111x200, then 100x200 is the best fit (least wasted resolution).
  2290. *
  2291. * @param original_size The original size of the image
  2292. * @param possible_resolutions A list of possible resolutions
  2293. * @return The best fit resolution
  2294. */
  2295. static clip_image_size select_best_resolution(const clip_image_size & original_size, const std::vector<clip_image_size> & possible_resolutions) {
  2296. clip_image_size best_fit;
  2297. int min_wasted_area = std::numeric_limits<int>::max();
  2298. int max_effective_resolution = 0;
  2299. for (const clip_image_size & candidate : possible_resolutions) {
  2300. auto target_size = resize_maintain_aspect_ratio(original_size, candidate);
  2301. int effective_resolution = std::min(
  2302. target_size.width * target_size.height,
  2303. original_size.width * original_size.height);
  2304. int wasted_area = (candidate.width * candidate.height) - effective_resolution;
  2305. if (effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_area < min_wasted_area)) {
  2306. max_effective_resolution = effective_resolution;
  2307. min_wasted_area = wasted_area;
  2308. best_fit = candidate;
  2309. }
  2310. LOG_DBG("%s: candidate: %d x %d, target: %d x %d, wasted: %d, effective: %d\n", __func__, candidate.width, candidate.height, target_size.width, target_size.height, wasted_area, effective_resolution);
  2311. }
  2312. return best_fit;
  2313. }
  2314. static int ensure_divide(int length, int patch_size) {
  2315. return std::max(static_cast<int>(std::round(static_cast<float>(length) / patch_size) * patch_size), patch_size);
  2316. }
  2317. static clip_image_size get_refine_size(const clip_image_size & original_size, const clip_image_size & grid, int scale_resolution, int patch_size, bool allow_upscale = false) {
  2318. int width = original_size.width;
  2319. int height = original_size.height;
  2320. int grid_x = grid.width;
  2321. int grid_y = grid.height;
  2322. int refine_width = ensure_divide(width, grid_x);
  2323. int refine_height = ensure_divide(height, grid_y);
  2324. clip_image_size grid_size;
  2325. grid_size.width = refine_width / grid_x;
  2326. grid_size.height = refine_height / grid_y;
  2327. auto best_grid_size = get_best_resize(grid_size, scale_resolution, patch_size, allow_upscale);
  2328. int best_grid_width = best_grid_size.width;
  2329. int best_grid_height = best_grid_size.height;
  2330. clip_image_size refine_size;
  2331. refine_size.width = best_grid_width * grid_x;
  2332. refine_size.height = best_grid_height * grid_y;
  2333. return refine_size;
  2334. }
  2335. static clip_image_size get_best_grid(const int max_slice_nums, const int multiple, const float log_ratio) {
  2336. std::vector<int> candidate_split_grids_nums;
  2337. for (int i : {multiple - 1, multiple, multiple + 1}) {
  2338. if (i == 1 || i > max_slice_nums) {
  2339. continue;
  2340. }
  2341. candidate_split_grids_nums.push_back(i);
  2342. }
  2343. std::vector<clip_image_size> candidate_grids;
  2344. for (int split_grids_nums : candidate_split_grids_nums) {
  2345. int m = 1;
  2346. while (m <= split_grids_nums) {
  2347. if (split_grids_nums % m == 0) {
  2348. candidate_grids.push_back(clip_image_size{m, split_grids_nums / m});
  2349. }
  2350. ++m;
  2351. }
  2352. }
  2353. clip_image_size best_grid{1, 1};
  2354. float min_error = std::numeric_limits<float>::infinity();
  2355. for (const auto& grid : candidate_grids) {
  2356. float error = std::abs(log_ratio - std::log(1.0 * grid.width / grid.height));
  2357. if (error < min_error) {
  2358. best_grid = grid;
  2359. min_error = error;
  2360. }
  2361. }
  2362. return best_grid;
  2363. }
  2364. };
  2365. // returns the normalized float tensor for llava-1.5, for spatial_unpad with anyres processing for llava-1.6 it returns the normalized image patch tensors as a vector
  2366. // res_imgs memory is being allocated here, previous allocations will be freed if found
  2367. bool clip_image_preprocess(struct clip_ctx * ctx, const clip_image_u8 * img, struct clip_image_f32_batch * res_imgs) {
  2368. clip_image_size original_size{img->nx, img->ny};
  2369. auto & params = ctx->model.hparams;
  2370. switch (ctx->proj_type()) {
  2371. case PROJECTOR_TYPE_MINICPMV:
  2372. {
  2373. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2374. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2375. for (size_t i = 0; i < imgs.size(); ++i) {
  2376. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2377. clip_image_f32_ptr res(clip_image_f32_init());
  2378. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2379. res_imgs->entries.push_back(std::move(res));
  2380. }
  2381. res_imgs->grid_x = inst.grid_size.width;
  2382. res_imgs->grid_y = inst.grid_size.height;
  2383. } break;
  2384. case PROJECTOR_TYPE_QWEN2VL:
  2385. case PROJECTOR_TYPE_QWEN25VL:
  2386. case PROJECTOR_TYPE_QWEN3VL:
  2387. case PROJECTOR_TYPE_GLM4V:
  2388. {
  2389. GGML_ASSERT(params.image_min_pixels > 0 && params.image_max_pixels > 0);
  2390. clip_image_u8 resized;
  2391. const clip_image_size new_size = img_tool::calc_size_preserved_ratio(
  2392. original_size,
  2393. params.patch_size * 2,
  2394. params.image_min_pixels,
  2395. params.image_max_pixels);
  2396. img_tool::resize(*img, resized, new_size, img_tool::RESIZE_ALGO_BILINEAR, false);
  2397. // clip_image_save_to_bmp(resized, "preproc.bmp");
  2398. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2399. // clip_image_f32_ptr res(clip_image_f32_init());
  2400. normalize_image_u8_to_f32(resized, *img_f32, params.image_mean, params.image_std);
  2401. // res_imgs->data[0] = *res;
  2402. res_imgs->entries.push_back(std::move(img_f32));
  2403. } break;
  2404. case PROJECTOR_TYPE_YOUTUVL:
  2405. {
  2406. const int patch_size = params.patch_size; // typically 16
  2407. const int merge_size = params.n_merge; // typically 2
  2408. const int align_size = patch_size * merge_size; // 32
  2409. const int max_num_patches = params.image_max_pixels > 0 ?
  2410. params.image_max_pixels / (patch_size * patch_size) : 256;
  2411. // Linear search for optimal scale to fit within max_num_patches
  2412. float scale = 1.0f;
  2413. int target_height = original_size.height;
  2414. int target_width = original_size.width;
  2415. auto get_scaled_image_size = [align_size](float scale, int size) -> int {
  2416. float scaled_size = size * scale;
  2417. // Round up to nearest multiple of align_size
  2418. int aligned = static_cast<int>(std::ceil(scaled_size / align_size)) * align_size;
  2419. // Ensure at least one patch
  2420. return std::max(align_size, aligned);
  2421. };
  2422. // Linear search with 0.02 step size
  2423. while (scale > 0.0f) {
  2424. target_height = get_scaled_image_size(scale, original_size.height);
  2425. target_width = get_scaled_image_size(scale, original_size.width);
  2426. int num_patches_h = target_height / patch_size;
  2427. int num_patches_w = target_width / patch_size;
  2428. int num_patches = num_patches_h * num_patches_w;
  2429. if (num_patches > max_num_patches) {
  2430. scale -= 0.02f;
  2431. } else {
  2432. break;
  2433. }
  2434. }
  2435. clip_image_size new_size = {target_width, target_height};
  2436. // Resize the image
  2437. clip_image_u8 resized;
  2438. img_tool::resize(*img, resized, new_size, img_tool::RESIZE_ALGO_BILINEAR, false);
  2439. // Normalize to float32
  2440. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2441. normalize_image_u8_to_f32(resized, *img_f32, params.image_mean, params.image_std);
  2442. // Add to results
  2443. res_imgs->entries.push_back(std::move(img_f32));
  2444. } break;
  2445. case PROJECTOR_TYPE_IDEFICS3:
  2446. {
  2447. // The refined size has two steps:
  2448. // 1. Resize w/ aspect-ratio preserving such that the longer side is
  2449. // the preprocessor longest size
  2450. // 2. Resize w/out preserving aspect ratio such that both sides are
  2451. // multiples of image_size (always rounding up)
  2452. //
  2453. // CITE: https://github.com/huggingface/transformers/blob/main/src/transformers/models/idefics3/image_processing_idefics3.py#L737
  2454. const clip_image_size refined_size = img_tool::calc_size_preserved_ratio(
  2455. original_size, params.image_size, params.image_longest_edge);
  2456. // LOG_INF("%s: original size: %d x %d, refined size: %d x %d\n",
  2457. // __func__, original_size.width, original_size.height,
  2458. // refined_size.width, refined_size.height);
  2459. llava_uhd::slice_instructions instructions;
  2460. instructions.overview_size = clip_image_size{params.image_size, params.image_size};
  2461. instructions.refined_size = refined_size;
  2462. instructions.grid_size = clip_image_size{
  2463. static_cast<int>(std::ceil(static_cast<float>(refined_size.width) / params.image_size)),
  2464. static_cast<int>(std::ceil(static_cast<float>(refined_size.height) / params.image_size)),
  2465. };
  2466. for (int y = 0; y < refined_size.height; y += params.image_size) {
  2467. for (int x = 0; x < refined_size.width; x += params.image_size) {
  2468. // LOG_INF("%s: adding slice at x=%d, y=%d\n", __func__, x, y);
  2469. instructions.slices.push_back(llava_uhd::slice_coordinates{
  2470. /* x */x,
  2471. /* y */y,
  2472. /* size */clip_image_size{
  2473. std::min(params.image_size, refined_size.width - x),
  2474. std::min(params.image_size, refined_size.height - y)
  2475. }
  2476. });
  2477. }
  2478. }
  2479. auto imgs = llava_uhd::slice_image(img, instructions);
  2480. // cast and normalize to f32
  2481. for (size_t i = 0; i < imgs.size(); ++i) {
  2482. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2483. clip_image_f32_ptr res(clip_image_f32_init());
  2484. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2485. res_imgs->entries.push_back(std::move(res));
  2486. }
  2487. res_imgs->grid_x = instructions.grid_size.width;
  2488. res_imgs->grid_y = instructions.grid_size.height;
  2489. } break;
  2490. case PROJECTOR_TYPE_GLM_EDGE:
  2491. case PROJECTOR_TYPE_GEMMA3:
  2492. case PROJECTOR_TYPE_INTERNVL: // TODO @ngxson : support dynamic resolution
  2493. {
  2494. clip_image_u8 resized_image;
  2495. int sz = params.image_size;
  2496. img_tool::resize(*img, resized_image, {sz, sz}, img_tool::RESIZE_ALGO_BILINEAR);
  2497. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2498. //clip_image_save_to_bmp(resized_image, "resized.bmp");
  2499. normalize_image_u8_to_f32(resized_image, *img_f32, params.image_mean, params.image_std);
  2500. res_imgs->entries.push_back(std::move(img_f32));
  2501. } break;
  2502. case PROJECTOR_TYPE_JANUS_PRO:
  2503. {
  2504. // Janus Pro preprocessing: pad to square with gray(127), resize to 384x384
  2505. const std::array<uint8_t, 3> pad_color = {127, 127, 127};
  2506. clip_image_u8 resized_image;
  2507. int sz = params.image_size;
  2508. img_tool::resize(*img, resized_image, {sz, sz}, img_tool::RESIZE_ALGO_BILINEAR, true, pad_color);
  2509. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2510. normalize_image_u8_to_f32(resized_image, *img_f32, params.image_mean, params.image_std);
  2511. res_imgs->entries.push_back(std::move(img_f32));
  2512. } break;
  2513. case PROJECTOR_TYPE_PIXTRAL:
  2514. case PROJECTOR_TYPE_LIGHTONOCR:
  2515. {
  2516. GGML_ASSERT(params.image_min_pixels > 0 && params.image_max_pixels > 0);
  2517. clip_image_u8 resized_image;
  2518. // the original pixtral model doesn't have n_merge
  2519. const int cur_merge = params.n_merge == 0 ? 1 : params.n_merge;
  2520. const clip_image_size target_size = img_tool::calc_size_preserved_ratio(
  2521. original_size,
  2522. params.patch_size * cur_merge,
  2523. params.image_min_pixels,
  2524. params.image_max_pixels);
  2525. img_tool::resize(*img, resized_image, target_size, img_tool::RESIZE_ALGO_BILINEAR);
  2526. clip_image_f32_ptr img_f32(clip_image_f32_init());
  2527. normalize_image_u8_to_f32(resized_image, *img_f32, params.image_mean, params.image_std);
  2528. res_imgs->entries.push_back(std::move(img_f32));
  2529. } break;
  2530. case PROJECTOR_TYPE_LLAMA4:
  2531. {
  2532. GGML_ASSERT(!params.image_res_candidates.empty());
  2533. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2534. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2535. for (size_t i = 0; i < imgs.size(); ++i) {
  2536. clip_image_f32_ptr res(clip_image_f32_init());
  2537. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2538. res_imgs->entries.push_back(std::move(res));
  2539. }
  2540. res_imgs->grid_x = inst.grid_size.width;
  2541. res_imgs->grid_y = inst.grid_size.height;
  2542. } break;
  2543. case PROJECTOR_TYPE_LFM2:
  2544. case PROJECTOR_TYPE_KIMIVL:
  2545. {
  2546. GGML_ASSERT(params.image_min_pixels > 0 && params.image_max_pixels > 0);
  2547. const clip_image_size target_size = img_tool::calc_size_preserved_ratio(
  2548. original_size,
  2549. params.patch_size * params.n_merge,
  2550. params.image_min_pixels,
  2551. params.image_max_pixels);
  2552. const std::array<uint8_t, 3> pad_color = {122, 116, 104};
  2553. clip_image_u8 resized_img;
  2554. const bool pad = (ctx->proj_type() != PROJECTOR_TYPE_LFM2);
  2555. img_tool::resize(*img, resized_img, target_size, img_tool::RESIZE_ALGO_BILINEAR, pad, pad_color);
  2556. clip_image_f32_ptr res(clip_image_f32_init());
  2557. normalize_image_u8_to_f32(resized_img, *res, params.image_mean, params.image_std);
  2558. res_imgs->entries.push_back(std::move(res));
  2559. } break;
  2560. case PROJECTOR_TYPE_MLP:
  2561. case PROJECTOR_TYPE_MLP_NORM:
  2562. case PROJECTOR_TYPE_LDP:
  2563. case PROJECTOR_TYPE_LDPV2:
  2564. case PROJECTOR_TYPE_COGVLM: // TODO @ngxson : is this correct for cogvlm?
  2565. {
  2566. // TODO @ngxson : refactor the code below to avoid duplicated logic
  2567. // the logic below is to pad the shorter side to the longer side with a background color: rgb(122, 116, 104)
  2568. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  2569. clip_image_u8_ptr temp(clip_image_u8_init()); // we will keep the input image data here temporarily
  2570. // The model config actually contains all we need to decide on how to preprocess, here we automatically switch to the new llava-1.6 preprocessing
  2571. if (params.image_res_candidates.empty()) { // pad_to_square
  2572. // for llava-1.5, we resize image to a square, and pad the shorter side with a background color
  2573. // see https://github.com/haotian-liu/LLaVA/blob/e854a2bf85118c504f6f16bf5c3c7c92f8fa8c6b/llava/conversation.py#L113-L156
  2574. const int longer_side = std::max(img->nx, img->ny);
  2575. temp->nx = longer_side;
  2576. temp->ny = longer_side;
  2577. temp->buf.resize(3 * longer_side * longer_side);
  2578. // background color in RGB from LLaVA (this is the mean rgb color * 255)
  2579. const std::array<uint8_t, 3> pad_color = {122, 116, 104};
  2580. // resize the image to the target_size
  2581. img_tool::resize(*img, *temp, clip_image_size{params.image_size, params.image_size}, img_tool::RESIZE_ALGO_BILINEAR, true, pad_color);
  2582. clip_image_f32_ptr res(clip_image_f32_init());
  2583. normalize_image_u8_to_f32(*temp, *res, params.image_mean, params.image_std);
  2584. res_imgs->entries.push_back(std::move(res));
  2585. } else {
  2586. // "spatial_unpad" with "anyres" processing for llava-1.6
  2587. auto const inst = llava_uhd::get_slice_instructions(ctx, original_size);
  2588. std::vector<clip_image_u8_ptr> imgs = llava_uhd::slice_image(img, inst);
  2589. for (size_t i = 0; i < imgs.size(); ++i) {
  2590. // clip_image_save_to_bmp(*imgs[i], "slice_" + std::to_string(i) + ".bmp");
  2591. clip_image_f32_ptr res(clip_image_f32_init());
  2592. normalize_image_u8_to_f32(*imgs[i], *res, params.image_mean, params.image_std);
  2593. res_imgs->entries.push_back(std::move(res));
  2594. }
  2595. }
  2596. } break;
  2597. default:
  2598. LOG_ERR("%s: unsupported projector type %d\n", __func__, ctx->proj_type());
  2599. return false;
  2600. }
  2601. return true;
  2602. }
  2603. ggml_tensor * clip_get_newline_tensor(const struct clip_ctx * ctx) {
  2604. return ctx->model.image_newline;
  2605. }
  2606. void clip_free(clip_ctx * ctx) {
  2607. if (ctx == nullptr) {
  2608. return;
  2609. }
  2610. delete ctx;
  2611. }
  2612. // deprecated
  2613. size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
  2614. const int32_t nx = ctx->model.hparams.image_size;
  2615. const int32_t ny = ctx->model.hparams.image_size;
  2616. return clip_embd_nbytes_by_img(ctx, nx, ny);
  2617. }
  2618. size_t clip_embd_nbytes_by_img(const struct clip_ctx * ctx, int img_w, int img_h) {
  2619. clip_image_f32 img;
  2620. img.nx = img_w;
  2621. img.ny = img_h;
  2622. return clip_n_output_tokens(ctx, &img) * clip_n_mmproj_embd(ctx) * sizeof(float);
  2623. }
  2624. int32_t clip_get_image_size(const struct clip_ctx * ctx) {
  2625. return ctx->model.hparams.image_size;
  2626. }
  2627. int32_t clip_get_patch_size(const struct clip_ctx * ctx) {
  2628. return ctx->model.hparams.patch_size;
  2629. }
  2630. int32_t clip_get_hidden_size(const struct clip_ctx * ctx) {
  2631. return ctx->model.hparams.n_embd;
  2632. }
  2633. const char * clip_patch_merge_type(const struct clip_ctx * ctx) {
  2634. return ctx->model.hparams.mm_patch_merge_type == PATCH_MERGE_SPATIAL_UNPAD ? "spatial_unpad" : "flat";
  2635. }
  2636. int clip_n_output_tokens_x(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2637. const auto & params = ctx->model.hparams;
  2638. const int n_total = clip_n_output_tokens(ctx, img);
  2639. const auto & proj = ctx->proj_type();
  2640. switch (proj) {
  2641. case PROJECTOR_TYPE_QWEN2VL:
  2642. case PROJECTOR_TYPE_QWEN25VL:
  2643. case PROJECTOR_TYPE_QWEN3VL:
  2644. case PROJECTOR_TYPE_GLM4V:
  2645. case PROJECTOR_TYPE_YOUTUVL:
  2646. return (img->nx / params.patch_size) / 2;
  2647. default:
  2648. break;
  2649. }
  2650. return n_total;
  2651. }
  2652. int clip_n_output_tokens_y(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2653. const auto & params = ctx->model.hparams;
  2654. const auto & proj = ctx->proj_type();
  2655. switch (proj) {
  2656. case PROJECTOR_TYPE_QWEN2VL:
  2657. case PROJECTOR_TYPE_QWEN25VL:
  2658. case PROJECTOR_TYPE_QWEN3VL:
  2659. case PROJECTOR_TYPE_GLM4V:
  2660. case PROJECTOR_TYPE_YOUTUVL:
  2661. return (img->ny / params.patch_size) / 2;
  2662. default:
  2663. break;
  2664. }
  2665. return 1;
  2666. }
  2667. int clip_n_output_tokens(const struct clip_ctx * ctx, struct clip_image_f32 * img) {
  2668. const auto & params = ctx->model.hparams;
  2669. // for models with fixed size image, the input image is already pre-processed and resized to square
  2670. int patch_size = params.patch_size;
  2671. int n_patches = (img->nx / patch_size) * (img->ny / patch_size);
  2672. projector_type proj = ctx->proj_type();
  2673. switch (proj) {
  2674. case PROJECTOR_TYPE_MLP:
  2675. case PROJECTOR_TYPE_MLP_NORM:
  2676. case PROJECTOR_TYPE_JANUS_PRO:
  2677. {
  2678. // do nothing
  2679. } break;
  2680. case PROJECTOR_TYPE_LDP:
  2681. case PROJECTOR_TYPE_LDPV2:
  2682. case PROJECTOR_TYPE_GLM_EDGE:
  2683. {
  2684. n_patches /= 4;
  2685. if (ctx->model.mm_boi) {
  2686. n_patches += 2; // for BOI and EOI token embeddings
  2687. }
  2688. } break;
  2689. case PROJECTOR_TYPE_MINICPMV:
  2690. {
  2691. // Use actual config value if available, otherwise fall back to hardcoded values
  2692. if (params.minicpmv_query_num > 0) {
  2693. n_patches = params.minicpmv_query_num;
  2694. } else {
  2695. // Fallback to hardcoded values for legacy models
  2696. if (params.minicpmv_version == 2) {
  2697. n_patches = 96;
  2698. } else if (params.minicpmv_version == 3) {
  2699. n_patches = 64;
  2700. } else if (params.minicpmv_version == 4) {
  2701. n_patches = 64;
  2702. } else if (params.minicpmv_version == 5) {
  2703. // MiniCPM-V 4.0
  2704. n_patches = 64;
  2705. } else if (params.minicpmv_version == 6) {
  2706. // MiniCPM-V 4.5
  2707. n_patches = 64;
  2708. } else {
  2709. GGML_ABORT("Unknown minicpmv version");
  2710. }
  2711. }
  2712. } break;
  2713. case PROJECTOR_TYPE_QWEN2VL:
  2714. case PROJECTOR_TYPE_QWEN25VL:
  2715. case PROJECTOR_TYPE_QWEN3VL:
  2716. case PROJECTOR_TYPE_GLM4V:
  2717. case PROJECTOR_TYPE_YOUTUVL:
  2718. {
  2719. // dynamic size (2 conv, so double patch size)
  2720. int x_patch = img->nx / (params.patch_size * 2);
  2721. int y_patch = img->ny / (params.patch_size * 2);
  2722. n_patches = x_patch * y_patch;
  2723. } break;
  2724. case PROJECTOR_TYPE_GEMMA3:
  2725. case PROJECTOR_TYPE_IDEFICS3:
  2726. case PROJECTOR_TYPE_INTERNVL:
  2727. case PROJECTOR_TYPE_LLAMA4:
  2728. {
  2729. // both X and Y are downscaled by the scale factor
  2730. int scale_factor = ctx->model.hparams.n_merge;
  2731. n_patches /= (scale_factor * scale_factor);
  2732. } break;
  2733. case PROJECTOR_TYPE_LFM2:
  2734. case PROJECTOR_TYPE_KIMIVL:
  2735. {
  2736. // dynamic size
  2737. int out_patch_size = params.patch_size * ctx->model.hparams.n_merge;
  2738. int x_patch = CLIP_ALIGN(img->nx, out_patch_size) / out_patch_size;
  2739. int y_patch = CLIP_ALIGN(img->ny, out_patch_size) / out_patch_size;
  2740. n_patches = x_patch * y_patch;
  2741. } break;
  2742. case PROJECTOR_TYPE_PIXTRAL:
  2743. case PROJECTOR_TYPE_LIGHTONOCR:
  2744. {
  2745. // dynamic size
  2746. int n_merge = ctx->model.hparams.n_merge;
  2747. int n_patches_x = img->nx / patch_size / (n_merge > 0 ? n_merge : 1);
  2748. int n_patches_y = img->ny / patch_size / (n_merge > 0 ? n_merge : 1);
  2749. if (ctx->model.token_embd_img_break) {
  2750. n_patches = n_patches_y * n_patches_x + n_patches_y - 1; // + one [IMG_BREAK] per row, except the last row
  2751. } else {
  2752. n_patches = n_patches_y * n_patches_x;
  2753. }
  2754. } break;
  2755. case PROJECTOR_TYPE_VOXTRAL:
  2756. case PROJECTOR_TYPE_ULTRAVOX:
  2757. case PROJECTOR_TYPE_QWEN2A:
  2758. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  2759. {
  2760. n_patches = img->nx;
  2761. const int proj_stack_factor = ctx->model.hparams.proj_stack_factor;
  2762. if (ctx->model.audio_has_stack_frames()) {
  2763. GGML_ASSERT(proj_stack_factor > 0);
  2764. const int n_len = CLIP_ALIGN(n_patches, proj_stack_factor);
  2765. n_patches = n_len / proj_stack_factor;
  2766. }
  2767. // whisper downscales input token by half after conv1d
  2768. n_patches /= 2;
  2769. if (ctx->model.audio_has_avgpool()) {
  2770. // divide by 2 because of nn.AvgPool1d(2, stride=2)
  2771. n_patches /= 2;
  2772. }
  2773. } break;
  2774. case PROJECTOR_TYPE_GLMA:
  2775. {
  2776. n_patches = img->nx;
  2777. // whisper downscales input token by half after conv1d
  2778. n_patches /= 2;
  2779. // reshape by merge_factor
  2780. n_patches /= ctx->model.hparams.proj_stack_factor;
  2781. // for BOI and EOI token embeddings
  2782. n_patches += 2;
  2783. } break;
  2784. case PROJECTOR_TYPE_COGVLM:
  2785. {
  2786. n_patches += 2; // for BOI and EOI token embeddings
  2787. } break;
  2788. case PROJECTOR_TYPE_LFM2A:
  2789. {
  2790. n_patches = ((((img->nx + 1) / 2) + 1) / 2 + 1) / 2;
  2791. } break;
  2792. default:
  2793. GGML_ABORT("unsupported projector type");
  2794. }
  2795. return n_patches;
  2796. }
  2797. bool clip_image_encode(struct clip_ctx * ctx, const int n_threads, clip_image_f32 * img, float * vec) {
  2798. clip_image_f32_batch imgs;
  2799. clip_image_f32_ptr img_copy(clip_image_f32_init());
  2800. *img_copy = *img;
  2801. imgs.entries.push_back(std::move(img_copy));
  2802. return clip_image_batch_encode(ctx, n_threads, &imgs, vec);
  2803. }
  2804. bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_image_f32_batch * imgs_c_ptr, float * vec) {
  2805. const clip_image_f32_batch & imgs = *imgs_c_ptr;
  2806. int batch_size = imgs.entries.size();
  2807. // TODO @ngxson : implement batch size > 1 as a loop
  2808. // we don't need true batching support because the cgraph will gonna be big anyway
  2809. if (batch_size != 1) {
  2810. return false; // only support batch size of 1
  2811. }
  2812. // if buffers are not allocated, we need to do a warmup run to allocate them
  2813. if (!ctx->is_allocated) {
  2814. clip_model_loader::warmup(*ctx, *imgs_c_ptr);
  2815. }
  2816. // build the inference graph
  2817. ctx->debug_print_tensors.clear();
  2818. ggml_backend_sched_reset(ctx->sched.get());
  2819. ggml_cgraph * gf = clip_image_build_graph(ctx, imgs);
  2820. ggml_backend_sched_alloc_graph(ctx->sched.get(), gf);
  2821. // set inputs
  2822. const auto & model = ctx->model;
  2823. const auto & hparams = model.hparams;
  2824. const int image_size_width = imgs.entries[0]->nx;
  2825. const int image_size_height = imgs.entries[0]->ny;
  2826. const int patch_size = hparams.patch_size;
  2827. const int num_patches = ((image_size_width / patch_size) * (image_size_height / patch_size));
  2828. const int n_pos = num_patches + (model.class_embedding ? 1 : 0);
  2829. const int pos_w = image_size_width / patch_size;
  2830. const int pos_h = image_size_height / patch_size;
  2831. auto get_inp_tensor = [&gf](const char * name) {
  2832. ggml_tensor * inp = ggml_graph_get_tensor(gf, name);
  2833. if (inp == nullptr) {
  2834. GGML_ABORT("Failed to get tensor %s", name);
  2835. }
  2836. if (!(inp->flags & GGML_TENSOR_FLAG_INPUT)) {
  2837. GGML_ABORT("Tensor %s is not an input tensor", name);
  2838. }
  2839. return inp;
  2840. };
  2841. auto set_input_f32 = [&get_inp_tensor](const char * name, std::vector<float> & values) {
  2842. ggml_tensor * cur = get_inp_tensor(name);
  2843. GGML_ASSERT(cur->type == GGML_TYPE_F32);
  2844. GGML_ASSERT(ggml_nelements(cur) == (int64_t)values.size());
  2845. ggml_backend_tensor_set(cur, values.data(), 0, ggml_nbytes(cur));
  2846. };
  2847. auto set_input_i32 = [&get_inp_tensor](const char * name, std::vector<int32_t> & values) {
  2848. ggml_tensor * cur = get_inp_tensor(name);
  2849. GGML_ASSERT(cur->type == GGML_TYPE_I32);
  2850. GGML_ASSERT(ggml_nelements(cur) == (int64_t)values.size());
  2851. ggml_backend_tensor_set(cur, values.data(), 0, ggml_nbytes(cur));
  2852. };
  2853. // set input pixel values
  2854. if (!imgs.is_audio) {
  2855. size_t nelem = 0;
  2856. for (const auto & img : imgs.entries) {
  2857. nelem += img->nx * img->ny * 3;
  2858. }
  2859. std::vector<float> inp_raw(nelem);
  2860. // layout of data (note: the channel dim is unrolled to better visualize the layout):
  2861. //
  2862. // ┌──W──┐
  2863. // │ H │ channel = R
  2864. // ├─────┤ │
  2865. // │ H │ channel = G
  2866. // ├─────┤ │
  2867. // │ H │ channel = B
  2868. // └─────┘ │
  2869. // ──────┘ x B
  2870. for (size_t i = 0; i < imgs.entries.size(); i++) {
  2871. const int nx = imgs.entries[i]->nx;
  2872. const int ny = imgs.entries[i]->ny;
  2873. const int n = nx * ny;
  2874. for (int b = 0; b < batch_size; b++) {
  2875. float * batch_entry = inp_raw.data() + b * (3*n);
  2876. for (int y = 0; y < ny; y++) {
  2877. for (int x = 0; x < nx; x++) {
  2878. size_t base_src = 3*(y * nx + x); // idx of the first channel
  2879. size_t base_dst = y * nx + x; // idx of the first channel
  2880. batch_entry[ base_dst] = imgs.entries[b]->buf[base_src ];
  2881. batch_entry[1*n + base_dst] = imgs.entries[b]->buf[base_src + 1];
  2882. batch_entry[2*n + base_dst] = imgs.entries[b]->buf[base_src + 2];
  2883. }
  2884. }
  2885. }
  2886. }
  2887. set_input_f32("inp_raw", inp_raw);
  2888. } else {
  2889. // audio input
  2890. GGML_ASSERT(imgs.entries.size() == 1);
  2891. const auto & mel_inp = imgs.entries[0];
  2892. const int n_step = mel_inp->nx;
  2893. const int n_mel = mel_inp->ny;
  2894. std::vector<float> inp_raw(n_step * n_mel);
  2895. std::memcpy(inp_raw.data(), mel_inp->buf.data(), n_step * n_mel * sizeof(float));
  2896. set_input_f32("inp_raw", inp_raw);
  2897. }
  2898. // set input per projector
  2899. switch (ctx->model.proj_type) {
  2900. case PROJECTOR_TYPE_MINICPMV:
  2901. {
  2902. // inspired from siglip:
  2903. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit
  2904. // -> https://huggingface.co/HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit/blob/d66538faeba44480d0bfaa42145eef26f9423199/modeling_siglip.py#L316
  2905. std::vector<int32_t> positions(pos_h * pos_w);
  2906. int bucket_coords_h[1024];
  2907. int bucket_coords_w[1024];
  2908. for (int i = 0; i < pos_h; i++){
  2909. bucket_coords_h[i] = std::floor(70.0*i/pos_h);
  2910. }
  2911. for (int i = 0; i < pos_w; i++){
  2912. bucket_coords_w[i] = std::floor(70.0*i/pos_w);
  2913. }
  2914. for (int i = 0, id = 0; i < pos_h; i++){
  2915. for (int j = 0; j < pos_w; j++){
  2916. positions[id++] = bucket_coords_h[i]*70 + bucket_coords_w[j];
  2917. }
  2918. }
  2919. set_input_i32("positions", positions);
  2920. // inputs for resampler projector
  2921. // set the 2D positions (using float for sinusoidal embedding)
  2922. int n_patches_per_col = image_size_width / patch_size;
  2923. std::vector<float> pos_data(n_pos);
  2924. // dimension H
  2925. for (int i = 0; i < n_pos; i++) {
  2926. pos_data[i] = static_cast<float>(i / n_patches_per_col);
  2927. }
  2928. set_input_f32("pos_h", pos_data);
  2929. // dimension W
  2930. for (int i = 0; i < n_pos; i++) {
  2931. pos_data[i] = static_cast<float>(i % n_patches_per_col);
  2932. }
  2933. set_input_f32("pos_w", pos_data);
  2934. // base frequency omega
  2935. const float base_freq = 10000.0f;
  2936. const int n_embd_proj = clip_n_mmproj_embd(ctx);
  2937. std::vector<float> omega(n_embd_proj / 4);
  2938. for (int i = 0; i < n_embd_proj / 4; ++i) {
  2939. omega[i] = 1.0f / std::pow(base_freq, static_cast<float>(i) / (n_embd_proj / 4));
  2940. }
  2941. set_input_f32("omega", omega);
  2942. } break;
  2943. case PROJECTOR_TYPE_QWEN2VL:
  2944. case PROJECTOR_TYPE_QWEN3VL:
  2945. case PROJECTOR_TYPE_GLM4V:
  2946. {
  2947. const int merge_ratio = hparams.n_merge;
  2948. const int pw = image_size_width / patch_size;
  2949. const int ph = image_size_height / patch_size;
  2950. std::vector<int> positions(n_pos * 4);
  2951. int ptr = 0;
  2952. for (int y = 0; y < ph; y += merge_ratio) {
  2953. for (int x = 0; x < pw; x += merge_ratio) {
  2954. for (int dy = 0; dy < 2; dy++) {
  2955. for (int dx = 0; dx < 2; dx++) {
  2956. positions[ ptr] = y + dy;
  2957. positions[ num_patches + ptr] = x + dx;
  2958. positions[2 * num_patches + ptr] = y + dy;
  2959. positions[3 * num_patches + ptr] = x + dx;
  2960. ptr++;
  2961. }
  2962. }
  2963. }
  2964. }
  2965. set_input_i32("positions", positions);
  2966. } break;
  2967. case PROJECTOR_TYPE_QWEN25VL:
  2968. case PROJECTOR_TYPE_YOUTUVL:
  2969. {
  2970. // pw * ph = number of tokens output by ViT after apply patch merger
  2971. // ipw * ipw = number of vision token been processed inside ViT
  2972. const bool use_window_attn = ctx->model.proj_type == PROJECTOR_TYPE_QWEN25VL ? hparams.n_wa_pattern > 0 : !hparams.wa_layer_indexes.empty();
  2973. const int merge_ratio = 2;
  2974. const int pw = image_size_width / patch_size / merge_ratio;
  2975. const int ph = image_size_height / patch_size / merge_ratio;
  2976. const int ipw = image_size_width / patch_size;
  2977. const int iph = image_size_height / patch_size;
  2978. std::vector<int> idx (ph * pw);
  2979. std::vector<int> inv_idx(ph * pw);
  2980. if (use_window_attn) {
  2981. const int attn_window_size = hparams.attn_window_size > 0 ? hparams.attn_window_size : 112;
  2982. const int grid_window = attn_window_size / patch_size / merge_ratio;
  2983. int dst = 0;
  2984. // [num_vision_tokens, num_vision_tokens] attention mask tensor
  2985. std::vector<float> mask(pow(ipw * iph, 2), std::numeric_limits<float>::lowest());
  2986. int mask_row = 0;
  2987. for (int y = 0; y < ph; y += grid_window) {
  2988. for (int x = 0; x < pw; x += grid_window) {
  2989. const int win_h = std::min(grid_window, ph - y);
  2990. const int win_w = std::min(grid_window, pw - x);
  2991. const int dst_0 = dst;
  2992. // group all tokens belong to the same window togather (to a continue range)
  2993. for (int dy = 0; dy < win_h; dy++) {
  2994. for (int dx = 0; dx < win_w; dx++) {
  2995. const int src = (y + dy) * pw + (x + dx);
  2996. GGML_ASSERT(src < (int)idx.size());
  2997. GGML_ASSERT(dst < (int)inv_idx.size());
  2998. idx [src] = dst;
  2999. inv_idx[dst] = src;
  3000. dst++;
  3001. }
  3002. }
  3003. for (int r=0; r < win_h * win_w * merge_ratio * merge_ratio; r++) {
  3004. int row_offset = mask_row * (ipw * iph);
  3005. std::fill(
  3006. mask.begin() + row_offset + (dst_0 * merge_ratio * merge_ratio),
  3007. mask.begin() + row_offset + (dst * merge_ratio * merge_ratio),
  3008. 0.0);
  3009. mask_row++;
  3010. }
  3011. }
  3012. }
  3013. set_input_i32("window_idx", idx);
  3014. set_input_i32("inv_window_idx", inv_idx);
  3015. set_input_f32("window_mask", mask);
  3016. } else {
  3017. for (int i = 0; i < ph * pw; i++) {
  3018. idx[i] = i;
  3019. }
  3020. }
  3021. const int mpow = merge_ratio * merge_ratio;
  3022. std::vector<int> positions(n_pos * 4);
  3023. int ptr = 0;
  3024. for (int y = 0; y < iph; y += merge_ratio) {
  3025. for (int x = 0; x < ipw; x += merge_ratio) {
  3026. for (int dy = 0; dy < 2; dy++) {
  3027. for (int dx = 0; dx < 2; dx++) {
  3028. auto remap = idx[ptr / mpow];
  3029. remap = (remap * mpow) + (ptr % mpow);
  3030. positions[ remap] = y + dy;
  3031. positions[ num_patches + remap] = x + dx;
  3032. positions[2 * num_patches + remap] = y + dy;
  3033. positions[3 * num_patches + remap] = x + dx;
  3034. ptr++;
  3035. }
  3036. }
  3037. }
  3038. }
  3039. set_input_i32("positions", positions);
  3040. } break;
  3041. case PROJECTOR_TYPE_PIXTRAL:
  3042. case PROJECTOR_TYPE_KIMIVL:
  3043. case PROJECTOR_TYPE_LIGHTONOCR:
  3044. {
  3045. // set the 2D positions
  3046. int n_patches_per_col = image_size_width / patch_size;
  3047. std::vector<int> pos_data(n_pos);
  3048. // dimension H
  3049. for (int i = 0; i < n_pos; i++) {
  3050. pos_data[i] = i / n_patches_per_col;
  3051. }
  3052. set_input_i32("pos_h", pos_data);
  3053. // dimension W
  3054. for (int i = 0; i < n_pos; i++) {
  3055. pos_data[i] = i % n_patches_per_col;
  3056. }
  3057. set_input_i32("pos_w", pos_data);
  3058. } break;
  3059. case PROJECTOR_TYPE_GLM_EDGE:
  3060. {
  3061. // llava and other models
  3062. std::vector<int32_t> positions(n_pos);
  3063. for (int i = 0; i < n_pos; i++) {
  3064. positions[i] = i;
  3065. }
  3066. set_input_i32("positions", positions);
  3067. } break;
  3068. case PROJECTOR_TYPE_MLP:
  3069. case PROJECTOR_TYPE_MLP_NORM:
  3070. case PROJECTOR_TYPE_LDP:
  3071. case PROJECTOR_TYPE_LDPV2:
  3072. {
  3073. // llava and other models
  3074. std::vector<int32_t> positions(n_pos);
  3075. for (int i = 0; i < n_pos; i++) {
  3076. positions[i] = i;
  3077. }
  3078. set_input_i32("positions", positions);
  3079. // The patches vector is used to get rows to index into the embeds with;
  3080. // we should skip dim 0 only if we have CLS to avoid going out of bounds
  3081. // when retrieving the rows.
  3082. int patch_offset = model.class_embedding ? 1 : 0;
  3083. std::vector<int32_t> patches(num_patches);
  3084. for (int i = 0; i < num_patches; i++) {
  3085. patches[i] = i + patch_offset;
  3086. }
  3087. set_input_i32("patches", patches);
  3088. } break;
  3089. case PROJECTOR_TYPE_GEMMA3:
  3090. case PROJECTOR_TYPE_IDEFICS3:
  3091. case PROJECTOR_TYPE_INTERNVL:
  3092. case PROJECTOR_TYPE_QWEN2A:
  3093. case PROJECTOR_TYPE_GLMA:
  3094. case PROJECTOR_TYPE_ULTRAVOX:
  3095. case PROJECTOR_TYPE_LFM2:
  3096. case PROJECTOR_TYPE_VOXTRAL:
  3097. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  3098. case PROJECTOR_TYPE_JANUS_PRO:
  3099. case PROJECTOR_TYPE_COGVLM:
  3100. {
  3101. // do nothing
  3102. } break;
  3103. case PROJECTOR_TYPE_LLAMA4:
  3104. {
  3105. // set the 2D positions
  3106. int n_patches_per_col = image_size_width / patch_size;
  3107. std::vector<int> pos_data(num_patches + 1, 0); // +1 for the [CLS] token
  3108. // last pos is always kept 0, it's for CLS
  3109. // dimension H
  3110. for (int i = 0; i < num_patches; i++) {
  3111. pos_data[i] = (i / n_patches_per_col) + 1;
  3112. }
  3113. set_input_i32("pos_h", pos_data);
  3114. // dimension W
  3115. for (int i = 0; i < num_patches; i++) {
  3116. pos_data[i] = (i % n_patches_per_col) + 1;
  3117. }
  3118. set_input_i32("pos_w", pos_data);
  3119. } break;
  3120. case PROJECTOR_TYPE_LFM2A:
  3121. {
  3122. GGML_ASSERT(imgs.entries.size() == 1);
  3123. const auto n_frames = clip_n_output_tokens(ctx, imgs.entries.front().get());
  3124. auto d_model = 512;
  3125. auto seq_len = n_frames * 2 - 1;
  3126. std::vector<float> pos_emb(d_model*seq_len);
  3127. std::vector<double> inv_freq(d_model / 2);
  3128. for (size_t i = 0; i < inv_freq.size(); ++i) {
  3129. inv_freq[i] = std::exp(-(std::log(10000.0) / (float)d_model) * (2.0f * (float)(i)));
  3130. }
  3131. for (int64_t pos = 0; pos < seq_len; ++pos) {
  3132. for (size_t i = 0; i < inv_freq.size(); ++i) {
  3133. const float ang = (n_frames - pos - 1) * inv_freq[i];
  3134. pos_emb[pos*d_model + 2*i + 0] = sinf(ang); // even
  3135. pos_emb[pos*d_model + 2*i + 1] = cosf(ang); // odd
  3136. }
  3137. }
  3138. set_input_f32("pos_emb", pos_emb);
  3139. } break;
  3140. default:
  3141. GGML_ABORT("Unknown projector type");
  3142. }
  3143. // ggml_backend_cpu_set_n_threads(ctx->backend_cpu, n_threads);
  3144. ggml_backend_dev_t dev = ggml_backend_get_device(ctx->backend_cpu);
  3145. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  3146. if (reg) {
  3147. 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");
  3148. if (ggml_backend_set_n_threads_fn) {
  3149. ggml_backend_set_n_threads_fn(ctx->backend_cpu, n_threads);
  3150. }
  3151. }
  3152. auto status = ggml_backend_sched_graph_compute(ctx->sched.get(), gf);
  3153. if (status != GGML_STATUS_SUCCESS) {
  3154. LOG_ERR("%s: ggml_backend_sched_graph_compute failed with error %d\n", __func__, status);
  3155. return false;
  3156. }
  3157. // print debug nodes
  3158. if (ctx->debug_graph) {
  3159. LOG_INF("\n\n---\n\n");
  3160. LOG_INF("\n\nDebug graph:\n\n");
  3161. for (ggml_tensor * t : ctx->debug_print_tensors) {
  3162. std::vector<uint8_t> data(ggml_nbytes(t));
  3163. ggml_backend_tensor_get(t, data.data(), 0, ggml_nbytes(t));
  3164. print_tensor_shape(t);
  3165. print_tensor_data(t, data.data(), 3);
  3166. }
  3167. }
  3168. // the last node is the embedding tensor
  3169. ggml_tensor * embeddings = ggml_graph_node(gf, -1);
  3170. // sanity check (only support batch size of 1 for now)
  3171. const int n_tokens_out = embeddings->ne[1];
  3172. const int expected_n_tokens_out = clip_n_output_tokens(ctx, imgs.entries[0].get());
  3173. if (n_tokens_out != expected_n_tokens_out) {
  3174. LOG_ERR("%s: expected output %d tokens, got %d\n", __func__, expected_n_tokens_out, n_tokens_out);
  3175. GGML_ABORT("Invalid number of output tokens");
  3176. }
  3177. // copy the embeddings to the location passed by the user
  3178. if (vec != nullptr) {
  3179. ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
  3180. }
  3181. return true;
  3182. }
  3183. int clip_n_mmproj_embd(const struct clip_ctx * ctx) {
  3184. switch (ctx->model.proj_type) {
  3185. case PROJECTOR_TYPE_LDP:
  3186. return ctx->model.mm_model_block_1_block_2_1_b->ne[0];
  3187. case PROJECTOR_TYPE_LDPV2:
  3188. return ctx->model.mm_model_peg_0_b->ne[0];
  3189. case PROJECTOR_TYPE_MLP:
  3190. case PROJECTOR_TYPE_PIXTRAL:
  3191. case PROJECTOR_TYPE_LIGHTONOCR:
  3192. return ctx->model.mm_2_w->ne[1];
  3193. case PROJECTOR_TYPE_MLP_NORM:
  3194. return ctx->model.mm_3_b->ne[0];
  3195. case PROJECTOR_TYPE_MINICPMV:
  3196. return ctx->model.mm_model_proj->ne[0];
  3197. case PROJECTOR_TYPE_GLM_EDGE:
  3198. return ctx->model.mm_model_mlp_3_w->ne[1];
  3199. case PROJECTOR_TYPE_QWEN2VL:
  3200. case PROJECTOR_TYPE_QWEN25VL:
  3201. case PROJECTOR_TYPE_JANUS_PRO:
  3202. case PROJECTOR_TYPE_YOUTUVL:
  3203. return ctx->model.mm_1_b->ne[0];
  3204. case PROJECTOR_TYPE_QWEN3VL:
  3205. // main path + deepstack paths
  3206. return ctx->model.mm_1_b->ne[0] * (1 + ctx->model.n_deepstack_layers);
  3207. case PROJECTOR_TYPE_GEMMA3:
  3208. return ctx->model.mm_input_proj_w->ne[0];
  3209. case PROJECTOR_TYPE_IDEFICS3:
  3210. return ctx->model.projection->ne[1];
  3211. case PROJECTOR_TYPE_ULTRAVOX:
  3212. case PROJECTOR_TYPE_VOXTRAL:
  3213. case PROJECTOR_TYPE_MUSIC_FLAMINGO:
  3214. return ctx->model.mm_2_w->ne[1];
  3215. case PROJECTOR_TYPE_INTERNVL:
  3216. return ctx->model.mm_3_w->ne[1];
  3217. case PROJECTOR_TYPE_LLAMA4:
  3218. return ctx->model.mm_model_proj->ne[1];
  3219. case PROJECTOR_TYPE_QWEN2A:
  3220. return ctx->model.mm_fc_w->ne[1];
  3221. case PROJECTOR_TYPE_GLMA:
  3222. return ctx->model.mm_2_w->ne[1];
  3223. case PROJECTOR_TYPE_LFM2:
  3224. case PROJECTOR_TYPE_KIMIVL:
  3225. return ctx->model.mm_2_w->ne[1];
  3226. case PROJECTOR_TYPE_COGVLM:
  3227. return ctx->model.mm_4h_to_h_w->ne[1];
  3228. case PROJECTOR_TYPE_LFM2A:
  3229. return ctx->model.position_embeddings->ne[0];
  3230. case PROJECTOR_TYPE_GLM4V:
  3231. return ctx->model.mm_ffn_down_w->ne[1];
  3232. default:
  3233. GGML_ABORT("Unknown projector type");
  3234. }
  3235. }
  3236. int clip_is_minicpmv(const struct clip_ctx * ctx) {
  3237. if (ctx->proj_type() == PROJECTOR_TYPE_MINICPMV) {
  3238. return ctx->model.hparams.minicpmv_version;
  3239. }
  3240. return 0;
  3241. }
  3242. bool clip_is_glm(const struct clip_ctx * ctx) {
  3243. return ctx->proj_type() == PROJECTOR_TYPE_GLM_EDGE;
  3244. }
  3245. bool clip_is_mrope(const struct clip_ctx * ctx) {
  3246. return ctx->proj_type() == PROJECTOR_TYPE_QWEN2VL
  3247. || ctx->proj_type() == PROJECTOR_TYPE_QWEN25VL
  3248. || ctx->proj_type() == PROJECTOR_TYPE_QWEN3VL
  3249. || ctx->proj_type() == PROJECTOR_TYPE_GLM4V;
  3250. }
  3251. bool clip_is_llava(const struct clip_ctx * ctx) {
  3252. return ctx->model.hparams.has_llava_projector;
  3253. }
  3254. bool clip_is_gemma3(const struct clip_ctx * ctx) {
  3255. return ctx->proj_type() == PROJECTOR_TYPE_GEMMA3;
  3256. }
  3257. bool clip_has_vision_encoder(const struct clip_ctx * ctx) {
  3258. return ctx->model.modality == CLIP_MODALITY_VISION;
  3259. }
  3260. bool clip_has_audio_encoder(const struct clip_ctx * ctx) {
  3261. return ctx->model.modality == CLIP_MODALITY_AUDIO;
  3262. }
  3263. bool clip_has_whisper_encoder(const struct clip_ctx * ctx) {
  3264. return ctx->proj_type() == PROJECTOR_TYPE_ULTRAVOX
  3265. || ctx->proj_type() == PROJECTOR_TYPE_QWEN2A
  3266. || ctx->proj_type() == PROJECTOR_TYPE_GLMA
  3267. || ctx->proj_type() == PROJECTOR_TYPE_VOXTRAL
  3268. || ctx->proj_type() == PROJECTOR_TYPE_MUSIC_FLAMINGO;
  3269. }
  3270. bool clip_encode_float_image (struct clip_ctx * ctx, int n_threads, float * img, int h, int w, float * vec) {
  3271. clip_image_f32 clip_img;
  3272. clip_img.buf.resize(h * w * 3);
  3273. for (int i = 0; i < h*w*3; i++)
  3274. {
  3275. clip_img.buf[i] = img[i];
  3276. }
  3277. clip_img.nx = w;
  3278. clip_img.ny = h;
  3279. clip_image_encode(ctx, n_threads, &clip_img, vec);
  3280. return true;
  3281. }
  3282. //
  3283. // API used internally with mtmd
  3284. //
  3285. projector_type clip_get_projector_type(const struct clip_ctx * ctx) {
  3286. return ctx->proj_type();
  3287. }
  3288. void clip_image_f32_batch_add_mel(struct clip_image_f32_batch * batch, int n_mel, int n_frames, float * mel) {
  3289. clip_image_f32 * audio = new clip_image_f32;
  3290. audio->nx = n_frames;
  3291. audio->ny = n_mel;
  3292. audio->buf.resize(n_frames * n_mel);
  3293. std::memcpy(audio->buf.data(), mel, n_frames * n_mel * sizeof(float));
  3294. batch->entries.push_back(clip_image_f32_ptr(audio));
  3295. batch->is_audio = true;
  3296. }
  3297. const clip_hparams * clip_get_hparams(const struct clip_ctx * ctx) {
  3298. return &ctx->model.hparams;
  3299. }
  3300. //
  3301. // API for debugging
  3302. //
  3303. void clip_debug_encode(clip_ctx * ctx, int h, int w, float fill_value) {
  3304. clip_image_f32 img;
  3305. img.nx = w;
  3306. img.ny = h;
  3307. img.buf.resize(h * w * 3);
  3308. for (int i = 0; i < h * w * 3; i++) {
  3309. img.buf[i] = static_cast<float>(fill_value);
  3310. }
  3311. bool cur_debug_graph = ctx->debug_graph;
  3312. ctx->debug_graph = true;
  3313. clip_image_encode(ctx, 1, &img, nullptr);
  3314. ctx->debug_graph = cur_debug_graph;
  3315. GGML_ASSERT(img.buf.empty() && "expected, always stop here");
  3316. }