ggml-hexagon.cpp 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554
  1. #include <assert.h>
  2. #include <inttypes.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <time.h>
  7. #include <atomic>
  8. #include <chrono>
  9. #include <mutex>
  10. #include <string>
  11. #include <stdexcept>
  12. #ifdef _WIN32
  13. # include <sal.h>
  14. # ifndef _WINDOWS
  15. # define _WINDOWS
  16. # endif
  17. #else
  18. # include <semaphore.h>
  19. # include <unistd.h>
  20. #endif
  21. #pragma clang diagnostic ignored "-Wnested-anon-types"
  22. #pragma clang diagnostic ignored "-Wgnu-anonymous-struct"
  23. #include "htp-utils.h"
  24. #include <AEEStdErr.h>
  25. #include <dspqueue.h>
  26. #include <rpcmem.h>
  27. #define GGML_COMMON_IMPL_CPP
  28. #include "ggml-backend-impl.h"
  29. #include "ggml-common.h"
  30. #include "ggml-hexagon.h"
  31. #include "ggml-impl.h"
  32. #include "ggml-quants.h"
  33. #include "htp-msg.h"
  34. #include "htp_iface.h"
  35. static size_t opt_ndev = 1;
  36. static size_t opt_nhvx = 0; // use all
  37. static int opt_arch = 0; // autodetect
  38. static int opt_etm = 0;
  39. static int opt_verbose = 0;
  40. static int opt_profile = 0;
  41. static int opt_hostbuf = 1;
  42. static int opt_experimental = 0;
  43. // Enable all stages by default
  44. static int opt_opmask = HTP_OPMASK_QUEUE | HTP_OPMASK_QUANTIZE | HTP_OPMASK_COMPUTE;
  45. static int opt_opsync = 0; // synchronous ops
  46. #define HEX_VERBOSE(...) \
  47. if (opt_verbose) GGML_LOG_DEBUG(__VA_ARGS__)
  48. #define HEX_PROFILE(...) \
  49. if (opt_profile) GGML_LOG_INFO(__VA_ARGS__)
  50. static inline uint64_t hex_is_aligned(void * addr, uint32_t align) {
  51. return ((size_t) addr & (align - 1)) == 0;
  52. }
  53. static inline size_t hex_round_up(size_t n, size_t m) {
  54. return m * ((n + m - 1) / m);
  55. }
  56. static const char * status_to_str(uint32_t status) {
  57. switch (status) {
  58. case HTP_STATUS_OK:
  59. return "OK";
  60. case HTP_STATUS_NO_SUPPORT:
  61. return "NO-SUPPORT";
  62. case HTP_STATUS_INVAL_PARAMS:
  63. return "INVAL-PARAMS";
  64. case HTP_STATUS_VTCM_TOO_SMALL:
  65. return "VTCM-TOO-SMALL";
  66. case HTP_STATUS_INTERNAL_ERR:
  67. return "INTERNAL-ERROR";
  68. default:
  69. return "UNKNOWN";
  70. }
  71. }
  72. // ** debug helpers
  73. static inline int hex_format_tensor_dims(char * str, const struct ggml_tensor * t) {
  74. if (t->ne[2] == 1 && t->ne[3] == 1) {
  75. return sprintf(str, "%d:%d", (int) t->ne[0], (int) t->ne[1]);
  76. } else {
  77. return sprintf(str, "%d:%d:%d:%d", (int) t->ne[0], (int) t->ne[1], (int) t->ne[2], (int) t->ne[3]);
  78. }
  79. }
  80. static inline void hex_format_op_dims(char * str, const struct ggml_tensor * t) {
  81. char * p = str;
  82. // append src0 and src1 (if any)
  83. if (t->src[0]) {
  84. p += hex_format_tensor_dims(p, t->src[0]);
  85. for (int i = 1; i < GGML_MAX_SRC && t->src[i]; i++) {
  86. p += sprintf(p, " x ");
  87. p += hex_format_tensor_dims(p, t->src[i]);
  88. }
  89. p += sprintf(p, " -> ");
  90. }
  91. // format self dims separately for better visual alignment
  92. char self[64];
  93. hex_format_tensor_dims(self, t);
  94. p += sprintf(p, "%s", self);
  95. }
  96. static inline int hex_format_tensor_strides(char * str, const struct ggml_tensor * t) {
  97. const char * c = ggml_is_contiguous(t) ? "" : "!";
  98. if (t->ne[2] == 1 && t->ne[3] == 1) {
  99. return sprintf(str, "%zu:%zu%s", (size_t) t->nb[0], (size_t) t->nb[1], c);
  100. } else {
  101. return sprintf(str, "%zu:%zu:%zu:%zu%s", (size_t) t->nb[0], (size_t) t->nb[1], (size_t) t->nb[2],
  102. (size_t) t->nb[3], c);
  103. }
  104. }
  105. static inline void hex_format_op_strides(char * str, const struct ggml_tensor * t) {
  106. char * p = str;
  107. // append src0 and src1 (if any)
  108. if (t->src[0]) {
  109. p += hex_format_tensor_strides(p, t->src[0]);
  110. for (int i = 1; i < GGML_MAX_SRC && t->src[i]; i++) {
  111. p += sprintf(p, " x ");
  112. p += hex_format_tensor_strides(p, t->src[i]);
  113. }
  114. p += sprintf(p, " -> ");
  115. }
  116. // format self dims separately for better visual alignment
  117. char self[64];
  118. hex_format_tensor_strides(self, t);
  119. p += sprintf(p, "%s", self);
  120. }
  121. static inline void hex_format_op_types(char * str, const struct ggml_tensor * t) {
  122. char * p = str;
  123. // append src0 and src1 (if any)
  124. if (t->src[0]) {
  125. p += sprintf(p, "%s", ggml_type_name(t->src[0]->type));
  126. for (int i = 1; i < GGML_MAX_SRC && t->src[i]; i++) {
  127. p += sprintf(p, " x ");
  128. p += sprintf(p, "%s", ggml_type_name(t->src[i]->type));
  129. }
  130. p += sprintf(p, " -> ");
  131. }
  132. p += sprintf(p, "%s", ggml_type_name(t->type));
  133. }
  134. static inline const char * hex_tensor_buff_name(const struct ggml_tensor * t) {
  135. if (t->buffer) {
  136. return ggml_backend_buffer_name(t->buffer);
  137. }
  138. return "NONE";
  139. }
  140. static inline void hex_format_op_buffs(char * str, const struct ggml_tensor * t) {
  141. char * p = str;
  142. // append src0 and src1 (if any)
  143. if (t->src[0]) {
  144. p += sprintf(p, "%s", hex_tensor_buff_name(t->src[0]));
  145. for (int i = 1; i < GGML_MAX_SRC && t->src[i]; i++) {
  146. p += sprintf(p, " x ");
  147. p += sprintf(p, "%s", hex_tensor_buff_name(t->src[i]));
  148. }
  149. p += sprintf(p, " -> ");
  150. }
  151. p += sprintf(p, "%s", hex_tensor_buff_name(t));
  152. }
  153. static inline void hex_format_op_names(char * str, const struct ggml_tensor * t) {
  154. char * p = str;
  155. // append src0 and src1 (if any)
  156. if (t->src[0]) {
  157. p += sprintf(p, "%s", t->src[0]->name);
  158. for (int i = 1; i < GGML_MAX_SRC && t->src[i]; i++) {
  159. p += sprintf(p, " x ");
  160. p += sprintf(p, "%s", t->src[i]->name);
  161. }
  162. p += sprintf(p, " -> ");
  163. }
  164. p += sprintf(p, "%s", t->name);
  165. }
  166. // ** backend sessions
  167. struct ggml_hexagon_session {
  168. ggml_hexagon_session(int dev_id, ggml_backend_dev_t dev) noexcept(false);
  169. ~ggml_hexagon_session() noexcept(true);
  170. void allocate(int dev_id) noexcept(false);
  171. void release() noexcept(true);
  172. void enqueue(struct htp_general_req &req, struct dspqueue_buffer *bufs, uint32_t n_bufs, bool sync = false);
  173. void flush();
  174. ggml_backend_buffer_type buffer_type;
  175. ggml_backend_buffer_type repack_buffer_type;
  176. std::string name;
  177. remote_handle64 handle;
  178. dspqueue_t queue;
  179. uint32_t session_id;
  180. uint32_t domain_id;
  181. uint64_t queue_id;
  182. int dev_id;
  183. bool valid_session;
  184. bool valid_handle;
  185. bool valid_queue;
  186. bool valid_iface;
  187. std::atomic<int> op_pending;
  188. uint32_t prof_usecs;
  189. uint32_t prof_cycles;
  190. uint32_t prof_pkts;
  191. };
  192. static inline void hex_print_op_info(const ggml_tensor * op, ggml_hexagon_session * sess, const uint32_t req_flags) {
  193. char dims[64 * GGML_MAX_SRC];
  194. char strides[64 * GGML_MAX_SRC];
  195. char types[16 * GGML_MAX_SRC];
  196. char buffs[64 * GGML_MAX_SRC];
  197. char names[64 * GGML_MAX_SRC];
  198. hex_format_op_dims(dims, op);
  199. hex_format_op_strides(strides, op);
  200. hex_format_op_types(types, op);
  201. hex_format_op_buffs(buffs, op);
  202. hex_format_op_names(names, op);
  203. HEX_VERBOSE("ggml-hex: %s %s: %s : %s : %s : %s : %s: flags 0x%x\n", sess->name.c_str(), ggml_op_name(op->op),
  204. names, dims, types, strides, buffs, req_flags);
  205. }
  206. void ggml_hexagon_session::enqueue(struct htp_general_req &req, struct dspqueue_buffer *bufs, uint32_t n_bufs, bool sync) {
  207. // Bump pending flag (cleared in the session::flush once we get the responce)
  208. this->op_pending++; // atomic inc
  209. int err = dspqueue_write(this->queue,
  210. 0, // flags - the framework will autoset this
  211. n_bufs, // number of buffers
  212. bufs, // buffer references
  213. sizeof(req),
  214. (const uint8_t *) &req, // Message
  215. 1000000 // Timeout
  216. );
  217. if (err != 0) {
  218. GGML_ABORT("ggml-hex: %s dspqueue_write failed: 0x%08x\n", this->name.c_str(), (unsigned) err);
  219. }
  220. if (sync) {
  221. flush();
  222. }
  223. }
  224. // Flush HTP response queue i.e wait for all outstanding requests to complete
  225. void ggml_hexagon_session::flush() {
  226. dspqueue_t q = this->queue;
  227. // Repeatedly read packets from the queue until it's empty. We don't
  228. // necessarily get a separate callback for each packet, and new packets
  229. // may arrive while we're processing the previous one.
  230. while (this->op_pending) {
  231. struct htp_general_rsp rsp;
  232. uint32_t rsp_size;
  233. uint32_t flags;
  234. struct dspqueue_buffer bufs[HTP_MAX_PACKET_BUFFERS];
  235. uint32_t n_bufs;
  236. // Read response packet from queue
  237. int err = dspqueue_read(q, &flags,
  238. HTP_MAX_PACKET_BUFFERS, // Maximum number of buffer references
  239. &n_bufs, // Number of buffer references
  240. bufs, // Buffer references
  241. sizeof(rsp), // Max message length
  242. &rsp_size, // Message length
  243. (uint8_t *) &rsp,
  244. 1000000); // Timeout
  245. if (err == AEE_EEXPIRED) {
  246. // TODO: might need to bail out if the HTP is stuck on something
  247. continue;
  248. }
  249. if (err != 0) {
  250. GGML_ABORT("ggml-hex: dspqueue_read failed: 0x%08x\n", (unsigned) err);
  251. }
  252. // Basic sanity checks
  253. if (rsp_size != sizeof(rsp)) {
  254. GGML_ABORT("ggml-hex: dspcall : bad response (size)\n");
  255. }
  256. if (rsp.status != HTP_STATUS_OK) {
  257. GGML_LOG_ERROR("ggml-hex: dspcall : dsp-rsp: %s\n", status_to_str(rsp.status));
  258. // TODO: handle errors
  259. }
  260. // TODO: update profiling implementation, currently only works for opt_opsync mode
  261. this->prof_usecs = rsp.prof_usecs;
  262. this->prof_cycles = rsp.prof_cycles;
  263. this->prof_pkts = rsp.prof_pkts;
  264. this->op_pending--; // atomic dec
  265. }
  266. }
  267. // ** backend buffers
  268. struct ggml_backend_hexagon_buffer_type_context {
  269. ggml_backend_hexagon_buffer_type_context(const std::string & name, ggml_hexagon_session * sess) {
  270. this->sess = sess;
  271. this->name = name;
  272. }
  273. ggml_hexagon_session * sess;
  274. std::string name;
  275. };
  276. struct ggml_backend_hexagon_buffer_context {
  277. bool mmap_to(ggml_hexagon_session * s) {
  278. HEX_VERBOSE("ggml-hex: %s mmaping buffer: base %p domain-id %d session-id %d size %zu fd %d repack %d\n",
  279. s->name.c_str(), (void *) this->base, s->domain_id, s->session_id, this->size, this->fd,
  280. (int) this->repack);
  281. int err = fastrpc_mmap(s->domain_id, this->fd, (void *) this->base, 0, this->size, FASTRPC_MAP_FD);
  282. if (err != 0) {
  283. GGML_LOG_ERROR("ggml-hex: buffer mapping failed : domain_id %d size %zu fd %d error 0x%08x\n",
  284. s->domain_id, this->size, this->fd, (unsigned) err);
  285. return false;
  286. }
  287. return true;
  288. }
  289. bool mmap() {
  290. if (this->mapped) {
  291. return true;
  292. }
  293. if (!mmap_to(this->sess)) {
  294. return false;
  295. }
  296. this->mapped = true;
  297. return true;
  298. }
  299. void munmap() {
  300. if (!this->mapped) {
  301. return;
  302. }
  303. fastrpc_munmap(this->sess->domain_id, this->fd, this->base, this->size);
  304. this->mapped = false;
  305. }
  306. ggml_backend_hexagon_buffer_context(ggml_hexagon_session * sess, size_t size, bool repack) {
  307. size += 4 * 1024; // extra page for padding
  308. if (rpcmem_alloc2) {
  309. this->base = (uint8_t *) rpcmem_alloc2(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS | RPCMEM_HEAP_NOREG, size);
  310. } else {
  311. GGML_LOG_INFO("ggml-hex: %s rpcmem_alloc2 not found, falling back to rpcmem_alloc\n", sess->name.c_str());
  312. this->base = (uint8_t *) rpcmem_alloc(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS | RPCMEM_HEAP_NOREG, size);
  313. }
  314. if (!this->base) {
  315. GGML_LOG_ERROR("ggml-hex: %s failed to allocate buffer : size %zu\n", sess->name.c_str(), size);
  316. throw std::runtime_error("ggml-hex: rpcmem_alloc failed (see log for details)");
  317. }
  318. this->fd = rpcmem_to_fd(this->base);
  319. if (this->fd < 0) {
  320. GGML_LOG_ERROR("ggml-hex: %s failed to get FD for buffer %p\n", sess->name.c_str(), (void *) this->base);
  321. rpcmem_free(this->base);
  322. this->base = NULL;
  323. throw std::runtime_error("ggml-hex: rpcmem_to_fd failed (see log for details)");
  324. }
  325. HEX_VERBOSE("ggml-hex: %s allocated buffer: base %p size %zu fd %d repack %d\n", sess->name.c_str(),
  326. (void *) this->base, size, this->fd, (int) repack);
  327. this->sess = sess;
  328. this->size = size;
  329. this->mapped = false;
  330. this->repack = repack;
  331. }
  332. ~ggml_backend_hexagon_buffer_context() {
  333. munmap();
  334. if (this->base) {
  335. rpcmem_free(this->base);
  336. this->base = NULL;
  337. }
  338. }
  339. ggml_hexagon_session * sess; // primary session
  340. uint8_t * base;
  341. size_t size;
  342. int fd;
  343. bool mapped; // mmap is done
  344. bool repack; // repacked buffer
  345. };
  346. static ggml_hexagon_session * ggml_backend_hexagon_buffer_get_sess(ggml_backend_buffer_t buffer) {
  347. return static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer->buft->context)->sess;
  348. }
  349. static void ggml_backend_hexagon_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  350. auto ctx = static_cast<ggml_backend_hexagon_buffer_context *>(buffer->context);
  351. delete ctx;
  352. }
  353. static void * ggml_backend_hexagon_buffer_get_base(ggml_backend_buffer_t buffer) {
  354. auto ctx = static_cast<ggml_backend_hexagon_buffer_context *>(buffer->context);
  355. return ctx->base;
  356. }
  357. static enum ggml_status ggml_backend_hexagon_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  358. auto ctx = static_cast<ggml_backend_hexagon_buffer_context *>(buffer->context);
  359. auto sess = ctx->sess;
  360. HEX_VERBOSE("ggml-hex: %s init-tensor %s : base %p data %p nbytes %zu usage %d repack %d\n", sess->name.c_str(),
  361. tensor->name, (void *) ctx->base, tensor->data, ggml_nbytes(tensor), (int) buffer->usage,
  362. (int) ctx->repack);
  363. if (tensor->view_src != NULL && tensor->view_offs == 0) {
  364. ; // nothing to do for the view
  365. } else {
  366. if (!ctx->mapped) {
  367. ctx->mmap();
  368. }
  369. }
  370. return GGML_STATUS_SUCCESS;
  371. }
  372. // ======== Q4x4x2 ====================
  373. struct x2_q4 {
  374. int v[2];
  375. };
  376. static x2_q4 unpack_q4(uint8_t v) {
  377. x2_q4 x = { (int) (v & 0x0f) - 8, (int) (v >> 4) - 8 };
  378. return x;
  379. }
  380. static void dump_block_q4_0(const block_q4_0 * b, int i) {
  381. HEX_VERBOSE("ggml-hex: repack q4_0 %d: %d %d %d %d ... %d %d %d %d : %.6f\n", i, unpack_q4(b->qs[0]).v[0],
  382. unpack_q4(b->qs[1]).v[0], unpack_q4(b->qs[2]).v[0], unpack_q4(b->qs[3]).v[0], unpack_q4(b->qs[12]).v[1],
  383. unpack_q4(b->qs[13]).v[1], unpack_q4(b->qs[14]).v[1], unpack_q4(b->qs[15]).v[1],
  384. GGML_FP16_TO_FP32(b->d));
  385. }
  386. static void dump_packed_block_q4x4x2(const uint8_t * v, unsigned int i, size_t k) {
  387. static const int qk = QK_Q4_0x4x2;
  388. const int dblk_size = 8 * 2; // 8x __fp16
  389. const int qblk_size = qk / 2; // int4
  390. const int qrow_size = k / 2; // int4 (not padded)
  391. const uint8_t * v_q = v + 0; // quants first
  392. const uint8_t * v_d = v + qrow_size; // then scales
  393. const uint8_t * q = v_q + i * qblk_size;
  394. const ggml_half * d = (const ggml_half *) (v_d + i * dblk_size);
  395. HEX_VERBOSE("ggml-hex: repack q4x4x2-%d: %d %d %d %d ... %d %d %d %d ... %d %d %d %d : %.6f %.6f %.6f %.6f\n", i,
  396. unpack_q4(q[0]).v[0], unpack_q4(q[1]).v[0], unpack_q4(q[2]).v[0], unpack_q4(q[3]).v[0],
  397. unpack_q4(q[60]).v[0], unpack_q4(q[61]).v[0], unpack_q4(q[62]).v[0], unpack_q4(q[63]).v[0],
  398. unpack_q4(q[124]).v[0], unpack_q4(q[125]).v[0], unpack_q4(q[126]).v[0], unpack_q4(q[127]).v[0],
  399. GGML_FP16_TO_FP32(d[0]), GGML_FP16_TO_FP32(d[1]), GGML_FP16_TO_FP32(d[2]), GGML_FP16_TO_FP32(d[3]));
  400. HEX_VERBOSE("ggml-hex: repack q4x4x2-%d: %d %d %d %d ... %d %d %d %d ... %d %d %d %d : %.6f %.6f %.6f %.6f\n",
  401. i + 1, unpack_q4(q[0]).v[1], unpack_q4(q[1]).v[1], unpack_q4(q[2]).v[1], unpack_q4(q[3]).v[1],
  402. unpack_q4(q[60]).v[1], unpack_q4(q[61]).v[1], unpack_q4(q[62]).v[1], unpack_q4(q[63]).v[1],
  403. unpack_q4(q[124]).v[1], unpack_q4(q[125]).v[1], unpack_q4(q[126]).v[1], unpack_q4(q[127]).v[1],
  404. GGML_FP16_TO_FP32(d[4]), GGML_FP16_TO_FP32(d[5]), GGML_FP16_TO_FP32(d[6]), GGML_FP16_TO_FP32(d[7]));
  405. }
  406. static void unpack_q4_0_quants(uint8_t * qs, const block_q4_0 * x, unsigned int bi) {
  407. static const int qk = QK4_0;
  408. for (unsigned int i = 0; i < qk / 2; ++i) {
  409. const int x0 = (x->qs[i] & 0x0F);
  410. const int x1 = (x->qs[i] >> 4);
  411. qs[bi * qk + i + 0] = x0;
  412. qs[bi * qk + i + qk / 2] = x1;
  413. }
  414. }
  415. static void pack_q4_0_quants(block_q4_0 * x, const uint8_t * qs, unsigned int bi) {
  416. static const int qk = QK4_0;
  417. for (unsigned int i = 0; i < qk / 2; ++i) {
  418. const uint8_t x0 = qs[bi * qk + i + 0];
  419. const uint8_t x1 = qs[bi * qk + i + qk / 2];
  420. x->qs[i] = x0 | (x1 << 4);
  421. }
  422. }
  423. static void repack_row_q4x4x2(uint8_t * y, const block_q4_0 * x, int64_t k) {
  424. static const int qk = QK_Q4_0x4x2;
  425. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  426. const int dblk_size = 8 * 2; // 8x __fp16
  427. const int qblk_size = qk / 2; // int4
  428. const int qrow_size = k / 2; // int4 (not padded to blocks)
  429. uint8_t * y_q = y + 0; // quants first
  430. uint8_t * y_d = y + qrow_size; // then scales
  431. if (opt_verbose > 2) {
  432. for (int i = 0; i < nb; i++) {
  433. dump_block_q4_0(&x[i * 8 + 0], 0);
  434. dump_block_q4_0(&x[i * 8 + 1], 1);
  435. dump_block_q4_0(&x[i * 8 + 2], 2);
  436. dump_block_q4_0(&x[i * 8 + 3], 3);
  437. dump_block_q4_0(&x[i * 8 + 4], 4);
  438. dump_block_q4_0(&x[i * 8 + 5], 5);
  439. dump_block_q4_0(&x[i * 8 + 6], 6);
  440. dump_block_q4_0(&x[i * 8 + 7], 7);
  441. }
  442. }
  443. // Repack the quants
  444. for (int i = 0; i < nb; i++) {
  445. uint8_t qs[QK_Q4_0x4x2]; // unpacked quants
  446. unpack_q4_0_quants(qs, &x[i * 8 + 0], 0);
  447. unpack_q4_0_quants(qs, &x[i * 8 + 1], 1);
  448. unpack_q4_0_quants(qs, &x[i * 8 + 2], 2);
  449. unpack_q4_0_quants(qs, &x[i * 8 + 3], 3);
  450. unpack_q4_0_quants(qs, &x[i * 8 + 4], 4);
  451. unpack_q4_0_quants(qs, &x[i * 8 + 5], 5);
  452. unpack_q4_0_quants(qs, &x[i * 8 + 6], 6);
  453. unpack_q4_0_quants(qs, &x[i * 8 + 7], 7);
  454. uint8_t * q = y_q + (i * qblk_size);
  455. for (int j = 0; j < qk / 2; j++) {
  456. q[j] = (qs[j + 128] << 4) | qs[j];
  457. }
  458. }
  459. // Repack the scales
  460. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_Q4_0x4x2)
  461. // the last block is truncated and overriden by the scales.
  462. for (int i = 0; i < nb; i++) {
  463. // Repack the scales
  464. ggml_half * d = (ggml_half *) (y_d + i * dblk_size);
  465. d[0] = x[i * 8 + 0].d;
  466. d[1] = x[i * 8 + 1].d;
  467. d[2] = x[i * 8 + 2].d;
  468. d[3] = x[i * 8 + 3].d;
  469. d[4] = x[i * 8 + 4].d;
  470. d[5] = x[i * 8 + 5].d;
  471. d[6] = x[i * 8 + 6].d;
  472. d[7] = x[i * 8 + 7].d;
  473. }
  474. if (opt_verbose > 1) {
  475. for (int i = 0; i < nb; i++) {
  476. dump_packed_block_q4x4x2(y, i, k);
  477. }
  478. }
  479. }
  480. static void unpack_row_q4x4x2(block_q4_0 * x, const uint8_t * y, int64_t k) {
  481. static const int qk = QK_Q4_0x4x2;
  482. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  483. const int dblk_size = 8 * 2; // 8x __fp16
  484. const int qblk_size = qk / 2; // int4
  485. const int qrow_size = k / 2; // int4 (not padded to blocks)
  486. const uint8_t * y_q = y + 0; // quants first
  487. const uint8_t * y_d = y + qrow_size; // then scales
  488. if (opt_verbose > 1) {
  489. for (int i = 0; i < nb; i++) {
  490. dump_packed_block_q4x4x2(y, i, k);
  491. }
  492. }
  493. // Unpack the quants
  494. for (int i = 0; i < nb; i++) {
  495. uint8_t qs[QK_Q4_0x4x2]; // unpacked quants
  496. const uint8_t * q = y_q + (i * qblk_size);
  497. for (int j = 0; j < qk / 2; j++) {
  498. qs[j] = q[j] & 0xf;
  499. qs[j + 128] = q[j] >> 4;
  500. }
  501. pack_q4_0_quants(&x[i * 8 + 0], qs, 0);
  502. pack_q4_0_quants(&x[i * 8 + 1], qs, 1);
  503. pack_q4_0_quants(&x[i * 8 + 2], qs, 2);
  504. pack_q4_0_quants(&x[i * 8 + 3], qs, 3);
  505. pack_q4_0_quants(&x[i * 8 + 4], qs, 4);
  506. pack_q4_0_quants(&x[i * 8 + 5], qs, 5);
  507. pack_q4_0_quants(&x[i * 8 + 6], qs, 6);
  508. pack_q4_0_quants(&x[i * 8 + 7], qs, 7);
  509. }
  510. // Repack the scales
  511. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_Q4_0x4x2)
  512. // the last block is truncated and overriden by the scales.
  513. for (int i = 0; i < nb; i++) {
  514. // Unpack the scales
  515. const ggml_half * d = (const ggml_half *) (y_d + i * dblk_size);
  516. x[i * 8 + 0].d = d[0];
  517. x[i * 8 + 1].d = d[1];
  518. x[i * 8 + 2].d = d[2];
  519. x[i * 8 + 3].d = d[3];
  520. x[i * 8 + 4].d = d[4];
  521. x[i * 8 + 5].d = d[5];
  522. x[i * 8 + 6].d = d[6];
  523. x[i * 8 + 7].d = d[7];
  524. }
  525. if (opt_verbose > 2) {
  526. for (int i = 0; i < nb; i++) {
  527. dump_block_q4_0(&x[i * 8 + 0], 0);
  528. dump_block_q4_0(&x[i * 8 + 1], 1);
  529. dump_block_q4_0(&x[i * 8 + 2], 2);
  530. dump_block_q4_0(&x[i * 8 + 3], 3);
  531. dump_block_q4_0(&x[i * 8 + 4], 4);
  532. dump_block_q4_0(&x[i * 8 + 5], 5);
  533. dump_block_q4_0(&x[i * 8 + 6], 6);
  534. dump_block_q4_0(&x[i * 8 + 7], 7);
  535. }
  536. }
  537. }
  538. static void init_row_q4x4x2(block_q4_0 * x, int64_t k) {
  539. static const int qk = QK_Q4_0x4x2;
  540. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  541. // Init the quants such that they unpack into zeros
  542. uint8_t qs[QK_Q4_0x4x2]; // unpacked quants
  543. memset(qs, 8, sizeof(qs));
  544. for (int i = 0; i < nb; i++) {
  545. pack_q4_0_quants(&x[i * 8 + 0], qs, 0);
  546. pack_q4_0_quants(&x[i * 8 + 1], qs, 1);
  547. pack_q4_0_quants(&x[i * 8 + 2], qs, 2);
  548. pack_q4_0_quants(&x[i * 8 + 3], qs, 3);
  549. pack_q4_0_quants(&x[i * 8 + 4], qs, 4);
  550. pack_q4_0_quants(&x[i * 8 + 5], qs, 5);
  551. pack_q4_0_quants(&x[i * 8 + 6], qs, 6);
  552. pack_q4_0_quants(&x[i * 8 + 7], qs, 7);
  553. }
  554. // Init the scales
  555. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_Q4_0x4x2)
  556. // the last block is truncated and overriden by the scales.
  557. for (int i = 0; i < nb; i++) {
  558. // Unpack the scales
  559. x[i * 8 + 0].d = 0;
  560. x[i * 8 + 1].d = 0;
  561. x[i * 8 + 2].d = 0;
  562. x[i * 8 + 3].d = 0;
  563. x[i * 8 + 4].d = 0;
  564. x[i * 8 + 5].d = 0;
  565. x[i * 8 + 6].d = 0;
  566. x[i * 8 + 7].d = 0;
  567. }
  568. }
  569. // repack q4_0 data into q4x4x2 tensor
  570. static void repack_q4_0_q4x4x2(ggml_tensor * t, const void * data, size_t size) {
  571. int64_t nrows = ggml_nrows(t);
  572. size_t row_size = ggml_row_size(t->type, t->ne[0]);
  573. size_t row_size_pd = ggml_row_size(t->type, hex_round_up(t->ne[0], QK_Q4_0x4x2)); // extra elements for the pad
  574. size_t row_size_rp = row_size * 2; // extra space for tmp pad (if any)
  575. // Ensure we don't try to read more data than is available in the source buffer 'data'
  576. // or write more than the tensor can hold.
  577. const size_t total_tensor_size = (size_t)nrows * row_size;
  578. const size_t n_bytes_to_copy = size < total_tensor_size ? size : total_tensor_size;
  579. // Calculate how many full rows and how many remaining bytes we need to process.
  580. const int64_t n_full_rows = n_bytes_to_copy / row_size;
  581. const size_t n_rem_bytes = n_bytes_to_copy % row_size;
  582. void * buf_pd = ggml_aligned_malloc(row_size_pd);
  583. GGML_ASSERT(buf_pd != NULL);
  584. void * buf_rp = ggml_aligned_malloc(row_size_rp);
  585. GGML_ASSERT(buf_rp != NULL);
  586. HEX_VERBOSE("ggml-hex: repack-q4_0-q4x4x2 %s : data %p size %zu dims %ldx%ld row-size %zu\n", t->name, data, size,
  587. t->ne[0], nrows, row_size);
  588. init_row_q4x4x2((block_q4_0 *) buf_pd, t->ne[0]); // init padded buffer to make sure the tail is all zeros
  589. // 1. Process all the full rows
  590. for (int64_t i = 0; i < n_full_rows; i++) {
  591. const uint8_t * src = (const uint8_t *) data + (i * row_size);
  592. uint8_t * dst = (uint8_t *) t->data + (i * row_size);
  593. memcpy(buf_pd, src, row_size);
  594. repack_row_q4x4x2((uint8_t *) buf_rp, (const block_q4_0 *) buf_pd, t->ne[0]);
  595. memcpy(dst, buf_rp, row_size);
  596. }
  597. // 2. Process the final, potentially partial, row
  598. if (n_rem_bytes > 0) {
  599. const int64_t i = n_full_rows;
  600. const uint8_t * src = (const uint8_t *) data + (i * row_size);
  601. uint8_t * dst = (uint8_t *) t->data + (i * row_size);
  602. // re-init the row because we are potentially copying a partial row
  603. init_row_q4x4x2((block_q4_0 *) buf_pd, t->ne[0]);
  604. // Copy only the remaining bytes from the source.
  605. memcpy(buf_pd, src, n_rem_bytes);
  606. // Repack the entire buffer
  607. repack_row_q4x4x2((uint8_t *) buf_rp, (const block_q4_0 *) buf_pd, t->ne[0]);
  608. // Write only the corresponding remaining bytes to the destination tensor.
  609. memcpy(dst, buf_rp, n_rem_bytes);
  610. }
  611. ggml_aligned_free(buf_pd, row_size_pd);
  612. ggml_aligned_free(buf_rp, row_size_rp);
  613. }
  614. // repack q4x4x2 tensor into q4_0 data
  615. static void repack_q4x4x2_q4_0(void * data, const ggml_tensor * t, size_t size) {
  616. int64_t nrows = ggml_nrows(t);
  617. size_t row_size = ggml_row_size(t->type, t->ne[0]);
  618. size_t row_size_pd = ggml_row_size(t->type, hex_round_up(t->ne[0], QK_Q4_0x4x2)); // extra elements for the pad
  619. size_t row_size_rp = row_size * 2; // extra space for tmp pad (if any)
  620. // Ensure we don't try to copy more data than the tensor actually contains.
  621. const size_t total_tensor_size = (size_t)nrows * row_size;
  622. const size_t n_bytes_to_copy = size < total_tensor_size ? size : total_tensor_size;
  623. // Calculate how many full rows and how many remaining bytes we need to process.
  624. const int64_t n_full_rows = n_bytes_to_copy / row_size;
  625. const size_t n_rem_bytes = n_bytes_to_copy % row_size;
  626. void * buf_pd = ggml_aligned_malloc(row_size_pd);
  627. GGML_ASSERT(buf_pd != NULL);
  628. void * buf_rp = ggml_aligned_malloc(row_size_rp);
  629. GGML_ASSERT(buf_rp != NULL);
  630. HEX_VERBOSE("ggml-hex: repack-q4x4x2-q4_0 %s : data %p size %zu dims %ldx%ld row-size %zu\n", t->name, data, size,
  631. t->ne[0], nrows, row_size);
  632. memset(buf_pd, 0, row_size_pd); // clear-out padded buffer to make sure the tail is all zeros
  633. // 1. Process all the full rows
  634. for (int64_t i = 0; i < n_full_rows; i++) {
  635. const uint8_t * src = (const uint8_t *) t->data + (i * row_size);
  636. uint8_t * dst = (uint8_t *) data + (i * row_size);
  637. memcpy(buf_pd, src, row_size);
  638. unpack_row_q4x4x2((block_q4_0 *) buf_rp, (const uint8_t *) buf_pd, t->ne[0]);
  639. memcpy(dst, buf_rp, row_size);
  640. }
  641. // 2. Process the final, potentially partial, row
  642. if (n_rem_bytes > 0) {
  643. const int64_t i = n_full_rows;
  644. const uint8_t * src = (const uint8_t *) t->data + (i * row_size);
  645. uint8_t * dst = (uint8_t *) data + (i * row_size);
  646. // We still need to read and unpack the entire source row because quantization is block-based.
  647. memcpy(buf_pd, src, row_size);
  648. unpack_row_q4x4x2((block_q4_0 *) buf_rp, (const uint8_t *) buf_pd, t->ne[0]);
  649. // But we only copy the remaining number of bytes to the destination.
  650. memcpy(dst, buf_rp, n_rem_bytes);
  651. }
  652. ggml_aligned_free(buf_pd, row_size_pd);
  653. ggml_aligned_free(buf_rp, row_size_rp);
  654. }
  655. // ======== Q8x4x2 ====================
  656. static void dump_block_q8_0(const block_q8_0 * b, int i) {
  657. HEX_VERBOSE("ggml-hex: repack q8_0 %d: %d %d %d %d ... %d %d %d %d : %.6f\n", i, b->qs[0], b->qs[1], b->qs[2],
  658. b->qs[3], b->qs[28], b->qs[29], b->qs[30], b->qs[31], GGML_FP16_TO_FP32(b->d));
  659. }
  660. static void dump_packed_block_q8x4x2(const uint8_t * v, unsigned int i, size_t k) {
  661. static const int qk = QK_Q8_0x4x2;
  662. const int dblk_size = 8 * 2; // 8x __fp16
  663. const int qblk_size = qk; // int8
  664. const int qrow_size = k; // int8 (not padded)
  665. const uint8_t * v_q = v + 0; // quants first
  666. const uint8_t * v_d = v + qrow_size; // then scales
  667. const uint8_t * q = v_q + i * qblk_size;
  668. const ggml_half * d = (const ggml_half *) (v_d + i * dblk_size);
  669. HEX_VERBOSE("ggml-hex: repack q8x4x2-%d: %d %d %d %d ... %d %d %d %d ... %d %d %d %d : %.6f %.6f %.6f %.6f\n", i,
  670. q[0], q[1], q[2], q[3], q[60], q[61], q[62], q[63], q[124], q[125], q[126], q[127],
  671. GGML_FP16_TO_FP32(d[0]), GGML_FP16_TO_FP32(d[1]), GGML_FP16_TO_FP32(d[2]), GGML_FP16_TO_FP32(d[3]));
  672. HEX_VERBOSE("ggml-hex: repack q8x4x2-%d: %d %d %d %d ... %d %d %d %d ... %d %d %d %d : %.6f %.6f %.6f %.6f\n",
  673. i + 1, q[128], q[129], q[130], q[131], q[192], q[193], q[194], q[195], q[252], q[253], q[254], q[255],
  674. GGML_FP16_TO_FP32(d[4]), GGML_FP16_TO_FP32(d[5]), GGML_FP16_TO_FP32(d[6]), GGML_FP16_TO_FP32(d[7]));
  675. }
  676. static void unpack_q8_0_quants(uint8_t * qs, const block_q8_0 * x, unsigned int bi) {
  677. static const int qk = QK8_0;
  678. for (unsigned int i = 0; i < qk; ++i) {
  679. qs[bi * qk + i] = x->qs[i];
  680. }
  681. }
  682. static void pack_q8_0_quants(block_q8_0 * x, const uint8_t * qs, unsigned int bi) {
  683. static const int qk = QK8_0;
  684. for (unsigned int i = 0; i < qk; ++i) {
  685. x->qs[i] = qs[bi * qk + i];
  686. }
  687. }
  688. static void repack_row_q8x4x2(uint8_t * y, const block_q8_0 * x, int64_t k) {
  689. static const int qk = QK_Q8_0x4x2;
  690. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  691. const int dblk_size = 8 * 2; // 8x __fp16
  692. const int qblk_size = qk; // int8
  693. const int qrow_size = k; // int8 (not padded to blocks)
  694. uint8_t * y_q = y + 0; // quants first
  695. uint8_t * y_d = y + qrow_size; // then scales
  696. if (opt_verbose > 2) {
  697. for (int i = 0; i < nb; i++) {
  698. dump_block_q8_0(&x[i * 8 + 0], 0);
  699. dump_block_q8_0(&x[i * 8 + 1], 1);
  700. dump_block_q8_0(&x[i * 8 + 2], 2);
  701. dump_block_q8_0(&x[i * 8 + 3], 3);
  702. dump_block_q8_0(&x[i * 8 + 4], 4);
  703. dump_block_q8_0(&x[i * 8 + 5], 5);
  704. dump_block_q8_0(&x[i * 8 + 6], 6);
  705. dump_block_q8_0(&x[i * 8 + 7], 7);
  706. }
  707. }
  708. // Repack the quants
  709. for (int i = 0; i < nb; i++) {
  710. uint8_t qs[QK_Q8_0x4x2]; // unpacked quants
  711. unpack_q8_0_quants(qs, &x[i * 8 + 0], 0);
  712. unpack_q8_0_quants(qs, &x[i * 8 + 1], 1);
  713. unpack_q8_0_quants(qs, &x[i * 8 + 2], 2);
  714. unpack_q8_0_quants(qs, &x[i * 8 + 3], 3);
  715. unpack_q8_0_quants(qs, &x[i * 8 + 4], 4);
  716. unpack_q8_0_quants(qs, &x[i * 8 + 5], 5);
  717. unpack_q8_0_quants(qs, &x[i * 8 + 6], 6);
  718. unpack_q8_0_quants(qs, &x[i * 8 + 7], 7);
  719. uint8_t * q = y_q + (i * qblk_size);
  720. for (int j = 0; j < qk; j++) {
  721. q[j] = qs[j];
  722. }
  723. }
  724. // Repack the scales
  725. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_Q4_0x4x2)
  726. // the last block is truncated and overriden by the scales.
  727. for (int i = 0; i < nb; i++) {
  728. // Repack the scales
  729. ggml_half * d = (ggml_half *) (y_d + i * dblk_size);
  730. d[0] = x[i * 8 + 0].d;
  731. d[1] = x[i * 8 + 1].d;
  732. d[2] = x[i * 8 + 2].d;
  733. d[3] = x[i * 8 + 3].d;
  734. d[4] = x[i * 8 + 4].d;
  735. d[5] = x[i * 8 + 5].d;
  736. d[6] = x[i * 8 + 6].d;
  737. d[7] = x[i * 8 + 7].d;
  738. }
  739. if (opt_verbose > 1) {
  740. for (int i = 0; i < nb; i++) {
  741. dump_packed_block_q8x4x2(y, i, k);
  742. }
  743. }
  744. }
  745. static void unpack_row_q8x4x2(block_q8_0 * x, const uint8_t * y, int64_t k) {
  746. static const int qk = QK_Q8_0x4x2;
  747. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  748. const int dblk_size = 8 * 2; // 8x __fp16
  749. const int qblk_size = qk; // int8
  750. const int qrow_size = k; // int8 (not padded to blocks)
  751. const uint8_t * y_q = y + 0; // quants first
  752. const uint8_t * y_d = y + qrow_size; // then scales
  753. if (opt_verbose > 1) {
  754. for (int i = 0; i < nb; i++) {
  755. dump_packed_block_q8x4x2(y, i, k);
  756. }
  757. }
  758. // Unpack the quants
  759. for (int i = 0; i < nb; i++) {
  760. uint8_t qs[QK_Q4_0x4x2]; // unpacked quants
  761. const uint8_t * q = y_q + (i * qblk_size);
  762. for (int j = 0; j < qk; j++) {
  763. qs[j] = q[j];
  764. }
  765. pack_q8_0_quants(&x[i * 8 + 0], qs, 0);
  766. pack_q8_0_quants(&x[i * 8 + 1], qs, 1);
  767. pack_q8_0_quants(&x[i * 8 + 2], qs, 2);
  768. pack_q8_0_quants(&x[i * 8 + 3], qs, 3);
  769. pack_q8_0_quants(&x[i * 8 + 4], qs, 4);
  770. pack_q8_0_quants(&x[i * 8 + 5], qs, 5);
  771. pack_q8_0_quants(&x[i * 8 + 6], qs, 6);
  772. pack_q8_0_quants(&x[i * 8 + 7], qs, 7);
  773. }
  774. // Repack the scales
  775. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_Q4_0x4x2)
  776. // the last block is truncated and overriden by the scales.
  777. for (int i = 0; i < nb; i++) {
  778. // Unpack the scales
  779. const ggml_half * d = (const ggml_half *) (y_d + i * dblk_size);
  780. x[i * 8 + 0].d = d[0];
  781. x[i * 8 + 1].d = d[1];
  782. x[i * 8 + 2].d = d[2];
  783. x[i * 8 + 3].d = d[3];
  784. x[i * 8 + 4].d = d[4];
  785. x[i * 8 + 5].d = d[5];
  786. x[i * 8 + 6].d = d[6];
  787. x[i * 8 + 7].d = d[7];
  788. }
  789. if (opt_verbose > 2) {
  790. for (int i = 0; i < nb; i++) {
  791. dump_block_q8_0(&x[i * 8 + 0], 0);
  792. dump_block_q8_0(&x[i * 8 + 1], 1);
  793. dump_block_q8_0(&x[i * 8 + 2], 2);
  794. dump_block_q8_0(&x[i * 8 + 3], 3);
  795. dump_block_q8_0(&x[i * 8 + 4], 4);
  796. dump_block_q8_0(&x[i * 8 + 5], 5);
  797. dump_block_q8_0(&x[i * 8 + 6], 6);
  798. dump_block_q8_0(&x[i * 8 + 7], 7);
  799. }
  800. }
  801. }
  802. static void init_row_q8x4x2(block_q8_0 * x, int64_t k) {
  803. static const int qk = QK_Q8_0x4x2;
  804. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  805. // Init the quants such that they unpack into zeros
  806. uint8_t qs[QK_Q8_0x4x2]; // unpacked quants
  807. memset(qs, 0, sizeof(qs));
  808. for (int i = 0; i < nb; i++) {
  809. pack_q8_0_quants(&x[i * 8 + 0], qs, 0);
  810. pack_q8_0_quants(&x[i * 8 + 1], qs, 1);
  811. pack_q8_0_quants(&x[i * 8 + 2], qs, 2);
  812. pack_q8_0_quants(&x[i * 8 + 3], qs, 3);
  813. pack_q8_0_quants(&x[i * 8 + 4], qs, 4);
  814. pack_q8_0_quants(&x[i * 8 + 5], qs, 5);
  815. pack_q8_0_quants(&x[i * 8 + 6], qs, 6);
  816. pack_q8_0_quants(&x[i * 8 + 7], qs, 7);
  817. }
  818. // Init the scales
  819. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_Q8_0x4x2)
  820. // the last block is truncated and overriden by the scales.
  821. for (int i = 0; i < nb; i++) {
  822. // Unpack the scales
  823. x[i * 8 + 0].d = 0;
  824. x[i * 8 + 1].d = 0;
  825. x[i * 8 + 2].d = 0;
  826. x[i * 8 + 3].d = 0;
  827. x[i * 8 + 4].d = 0;
  828. x[i * 8 + 5].d = 0;
  829. x[i * 8 + 6].d = 0;
  830. x[i * 8 + 7].d = 0;
  831. }
  832. }
  833. // repack q8_0 data into q8x4x2 tensor
  834. static void repack_q8_0_q8x4x2(ggml_tensor * t, const void * data, size_t size) {
  835. int64_t nrows = ggml_nrows(t);
  836. size_t row_size = ggml_row_size(t->type, t->ne[0]);
  837. size_t row_size_pd = ggml_row_size(t->type, hex_round_up(t->ne[0], QK_Q8_0x4x2)); // extra elements for the pad
  838. size_t row_size_rp = row_size * 2; // extra space for tmp pad (if any)
  839. // Ensure we don't try to read more data than is available in the source buffer 'data'
  840. // or write more than the tensor can hold.
  841. const size_t total_tensor_size = (size_t)nrows * row_size;
  842. const size_t n_bytes_to_copy = size < total_tensor_size ? size : total_tensor_size;
  843. // Calculate how many full rows and how many remaining bytes we need to process.
  844. const int64_t n_full_rows = n_bytes_to_copy / row_size;
  845. const size_t n_rem_bytes = n_bytes_to_copy % row_size;
  846. void * buf_pd = ggml_aligned_malloc(row_size_pd);
  847. GGML_ASSERT(buf_pd != NULL);
  848. void * buf_rp = ggml_aligned_malloc(row_size_rp);
  849. GGML_ASSERT(buf_rp != NULL);
  850. HEX_VERBOSE("ggml-hex: repack-q8_0-q8x4x2 %s : data %p size %zu dims %ldx%ld row-size %zu\n", t->name, data, size,
  851. t->ne[0], nrows, row_size);
  852. init_row_q8x4x2((block_q8_0 *) buf_pd, t->ne[0]); // init padded buffer to make sure the tail is all zeros
  853. // 1. Process all the full rows
  854. for (int64_t i = 0; i < n_full_rows; i++) {
  855. const uint8_t * src = (const uint8_t *) data + (i * row_size);
  856. uint8_t * dst = (uint8_t *) t->data + (i * row_size);
  857. memcpy(buf_pd, src, row_size);
  858. repack_row_q8x4x2((uint8_t *) buf_rp, (const block_q8_0 *) buf_pd, t->ne[0]);
  859. memcpy(dst, buf_rp, row_size);
  860. }
  861. // 2. Process the final, potentially partial, row
  862. if (n_rem_bytes > 0) {
  863. const int64_t i = n_full_rows;
  864. const uint8_t * src = (const uint8_t *) data + (i * row_size);
  865. uint8_t * dst = (uint8_t *) t->data + (i * row_size);
  866. // re-init the row because we are potentially copying a partial row
  867. init_row_q8x4x2((block_q8_0 *) buf_pd, t->ne[0]);
  868. // Copy only the remaining bytes from the source.
  869. memcpy(buf_pd, src, n_rem_bytes);
  870. // Repack the entire buffer
  871. repack_row_q8x4x2((uint8_t *) buf_rp, (const block_q8_0 *) buf_pd, t->ne[0]);
  872. // Write only the corresponding remaining bytes to the destination tensor.
  873. memcpy(dst, buf_rp, n_rem_bytes);
  874. }
  875. ggml_aligned_free(buf_pd, row_size_pd);
  876. ggml_aligned_free(buf_rp, row_size_rp);
  877. }
  878. // repack q8x4x2 tensor into q8_0 data
  879. static void repack_q8x4x2_q8_0(void * data, const ggml_tensor * t, size_t size) {
  880. int64_t nrows = ggml_nrows(t);
  881. size_t row_size = ggml_row_size(t->type, t->ne[0]);
  882. size_t row_size_pd = ggml_row_size(t->type, hex_round_up(t->ne[0], QK_Q8_0x4x2)); // extra elements for the pad
  883. size_t row_size_rp = row_size * 2; // extra space for tmp pad (if any)
  884. // Ensure we don't try to copy more data than the tensor actually contains.
  885. const size_t total_tensor_size = (size_t)nrows * row_size;
  886. const size_t n_bytes_to_copy = size < total_tensor_size ? size : total_tensor_size;
  887. // Calculate how many full rows and how many remaining bytes we need to process.
  888. const int64_t n_full_rows = n_bytes_to_copy / row_size;
  889. const size_t n_rem_bytes = n_bytes_to_copy % row_size;
  890. void * buf_pd = ggml_aligned_malloc(row_size_pd);
  891. GGML_ASSERT(buf_pd != NULL);
  892. void * buf_rp = ggml_aligned_malloc(row_size_rp);
  893. GGML_ASSERT(buf_rp != NULL);
  894. HEX_VERBOSE("ggml-hex: repack-q8x4x2-q8_0 %s : data %p size %zu dims %ldx%ld row-size %zu\n", t->name, data, size,
  895. t->ne[0], nrows, row_size);
  896. memset(buf_pd, 0, row_size_pd); // clear-out padded buffer to make sure the tail is all zeros
  897. // 1. Process all the full rows
  898. for (int64_t i = 0; i < n_full_rows; i++) {
  899. const uint8_t * src = (const uint8_t *) t->data + (i * row_size);
  900. uint8_t * dst = (uint8_t *) data + (i * row_size);
  901. memcpy(buf_pd, src, row_size);
  902. unpack_row_q8x4x2((block_q8_0 *) buf_rp, (const uint8_t *) buf_pd, t->ne[0]);
  903. memcpy(dst, buf_rp, row_size);
  904. }
  905. // 2. Process the final, potentially partial, row
  906. if (n_rem_bytes > 0) {
  907. const int64_t i = n_full_rows;
  908. const uint8_t * src = (const uint8_t *) t->data + (i * row_size);
  909. uint8_t * dst = (uint8_t *) data + (i * row_size);
  910. // We still need to read and unpack the entire source row because quantization is block-based.
  911. memcpy(buf_pd, src, row_size);
  912. unpack_row_q8x4x2((block_q8_0 *) buf_rp, (const uint8_t *) buf_pd, t->ne[0]);
  913. // But we only copy the remaining number of bytes to the destination.
  914. memcpy(dst, buf_rp, n_rem_bytes);
  915. }
  916. ggml_aligned_free(buf_pd, row_size_pd);
  917. ggml_aligned_free(buf_rp, row_size_rp);
  918. }
  919. // ======== MXFP4x4x2 ====================
  920. struct x2_mxfp4 {
  921. int v[2];
  922. };
  923. static x2_mxfp4 unpack_mxfp4(uint8_t v) {
  924. x2_mxfp4 x;
  925. x.v[0] = kvalues_mxfp4[(v & 0x0f)];
  926. x.v[1] = kvalues_mxfp4[(v >> 4)];
  927. return x;
  928. }
  929. static void dump_block_mxfp4(const block_mxfp4 * b, int i) {
  930. HEX_VERBOSE("ggml-hex: repack mxfp4 %d: %d %d %d %d ... %d %d %d %d : %.6f\n", i, unpack_mxfp4(b->qs[0]).v[0],
  931. unpack_mxfp4(b->qs[1]).v[0], unpack_mxfp4(b->qs[2]).v[0], unpack_mxfp4(b->qs[3]).v[0],
  932. unpack_mxfp4(b->qs[12]).v[1], unpack_mxfp4(b->qs[13]).v[1], unpack_mxfp4(b->qs[14]).v[1],
  933. unpack_mxfp4(b->qs[15]).v[1], GGML_E8M0_TO_FP32_HALF(b->e));
  934. }
  935. static void dump_packed_block_mxfp4x4x2(const uint8_t * v, unsigned int i, size_t k) {
  936. static const int qk = QK_MXFP4x4x2;
  937. const int eblk_size = 8 * 1; // 8x E8M0
  938. const int qblk_size = qk / 2; // int4
  939. const int qrow_size = k / 2; // int4 (not padded)
  940. const uint8_t * v_q = v + 0; // quants first
  941. const uint8_t * v_e = v + qrow_size; // then scales
  942. const uint8_t * q = v_q + i * qblk_size;
  943. const uint8_t * e = (const uint8_t *) (v_e + i * eblk_size);
  944. HEX_VERBOSE("ggml-hex: repack mxfp4x4x2-%d: %d %d %d %d ... %d %d %d %d ... %d %d %d %d : %.6f %.6f %.6f %.6f\n", i,
  945. unpack_mxfp4(q[0]).v[0], unpack_mxfp4(q[1]).v[0], unpack_mxfp4(q[2]).v[0], unpack_mxfp4(q[3]).v[0],
  946. unpack_mxfp4(q[60]).v[0], unpack_mxfp4(q[61]).v[0], unpack_mxfp4(q[62]).v[0], unpack_mxfp4(q[63]).v[0],
  947. unpack_mxfp4(q[124]).v[0], unpack_mxfp4(q[125]).v[0], unpack_mxfp4(q[126]).v[0],
  948. unpack_mxfp4(q[127]).v[0], GGML_E8M0_TO_FP32_HALF(e[0]), GGML_E8M0_TO_FP32_HALF(e[1]),
  949. GGML_E8M0_TO_FP32_HALF(e[2]), GGML_E8M0_TO_FP32_HALF(e[3]));
  950. HEX_VERBOSE("ggml-hex: repack mxfp4x4x2-%d: %d %d %d %d ... %d %d %d %d ... %d %d %d %d : %.6f %.6f %.6f %.6f\n",
  951. i + 1, unpack_mxfp4(q[0]).v[1], unpack_mxfp4(q[1]).v[1], unpack_mxfp4(q[2]).v[1],
  952. unpack_mxfp4(q[3]).v[1], unpack_mxfp4(q[60]).v[1], unpack_mxfp4(q[61]).v[1], unpack_mxfp4(q[62]).v[1],
  953. unpack_mxfp4(q[63]).v[1], unpack_mxfp4(q[124]).v[1], unpack_mxfp4(q[125]).v[1],
  954. unpack_mxfp4(q[126]).v[1], unpack_mxfp4(q[127]).v[1], GGML_E8M0_TO_FP32_HALF(e[4]),
  955. GGML_E8M0_TO_FP32_HALF(e[5]), GGML_E8M0_TO_FP32_HALF(e[6]), GGML_E8M0_TO_FP32_HALF(e[7]));
  956. }
  957. static void unpack_mxfp4_quants(uint8_t * qs, const block_mxfp4 * x, unsigned int bi) {
  958. static const int qk = QK_MXFP4;
  959. for (unsigned int i = 0; i < qk / 2; ++i) {
  960. const uint8_t x0 = (x->qs[i] & 0x0F);
  961. const uint8_t x1 = (x->qs[i] >> 4);
  962. qs[bi * qk + i + 0] = x0;
  963. qs[bi * qk + i + qk / 2] = x1;
  964. }
  965. }
  966. static void pack_mxfp4_quants(block_mxfp4 * x, const uint8_t * qs, unsigned int bi) {
  967. static const int qk = QK4_0;
  968. for (unsigned int i = 0; i < qk / 2; ++i) {
  969. const uint8_t x0 = qs[bi * qk + i + 0];
  970. const uint8_t x1 = qs[bi * qk + i + qk / 2];
  971. x->qs[i] = x0 | (x1 << 4);
  972. }
  973. }
  974. static void repack_row_mxfp4x4x2(uint8_t * y, const block_mxfp4 * x, int64_t k) {
  975. static const int qk = QK_MXFP4x4x2;
  976. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  977. const int eblk_size = 8 * 1; // 8x E8M0
  978. const int qblk_size = qk / 2; // int4
  979. const int qrow_size = k / 2; // int4 (not padded to blocks)
  980. uint8_t * y_q = y + 0; // quants first
  981. uint8_t * y_e = y + qrow_size; // then scales
  982. if (opt_verbose > 2) {
  983. for (int i = 0; i < nb; i++) {
  984. dump_block_mxfp4(&x[i * 8 + 0], 0);
  985. dump_block_mxfp4(&x[i * 8 + 1], 1);
  986. dump_block_mxfp4(&x[i * 8 + 2], 2);
  987. dump_block_mxfp4(&x[i * 8 + 3], 3);
  988. dump_block_mxfp4(&x[i * 8 + 4], 4);
  989. dump_block_mxfp4(&x[i * 8 + 5], 5);
  990. dump_block_mxfp4(&x[i * 8 + 6], 6);
  991. dump_block_mxfp4(&x[i * 8 + 7], 7);
  992. }
  993. }
  994. // Repack the quants
  995. for (int i = 0; i < nb; i++) {
  996. uint8_t qs[QK_MXFP4x4x2]; // unpacked quants
  997. unpack_mxfp4_quants(qs, &x[i * 8 + 0], 0);
  998. unpack_mxfp4_quants(qs, &x[i * 8 + 1], 1);
  999. unpack_mxfp4_quants(qs, &x[i * 8 + 2], 2);
  1000. unpack_mxfp4_quants(qs, &x[i * 8 + 3], 3);
  1001. unpack_mxfp4_quants(qs, &x[i * 8 + 4], 4);
  1002. unpack_mxfp4_quants(qs, &x[i * 8 + 5], 5);
  1003. unpack_mxfp4_quants(qs, &x[i * 8 + 6], 6);
  1004. unpack_mxfp4_quants(qs, &x[i * 8 + 7], 7);
  1005. uint8_t * q = y_q + (i * qblk_size);
  1006. for (int j = 0; j < qk / 2; j++) {
  1007. q[j] = (qs[j + 128] << 4) | qs[j];
  1008. }
  1009. }
  1010. // Repack the scales
  1011. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_MXFP4x4x2)
  1012. // the last block is truncated and overriden by the scales.
  1013. for (int i = 0; i < nb; i++) {
  1014. // Repack the scales
  1015. uint8_t * e = (uint8_t *) (y_e + i * eblk_size);
  1016. e[0] = x[i * 8 + 0].e;
  1017. e[1] = x[i * 8 + 1].e;
  1018. e[2] = x[i * 8 + 2].e;
  1019. e[3] = x[i * 8 + 3].e;
  1020. e[4] = x[i * 8 + 4].e;
  1021. e[5] = x[i * 8 + 5].e;
  1022. e[6] = x[i * 8 + 6].e;
  1023. e[7] = x[i * 8 + 7].e;
  1024. }
  1025. if (opt_verbose > 1) {
  1026. for (int i = 0; i < nb; i++) {
  1027. dump_packed_block_mxfp4x4x2(y, i, k);
  1028. }
  1029. }
  1030. }
  1031. static void unpack_row_mxfp4x4x2(block_mxfp4 * x, const uint8_t * y, int64_t k) {
  1032. static const int qk = QK_MXFP4x4x2;
  1033. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  1034. const int eblk_size = 8 * 1; // 8x E8M0
  1035. const int qblk_size = qk / 2; // int4
  1036. const int qrow_size = k / 2; // int4 (not padded to blocks)
  1037. const uint8_t * y_q = y + 0; // quants first
  1038. const uint8_t * y_e = y + qrow_size; // then scales
  1039. if (opt_verbose > 1) {
  1040. for (int i = 0; i < nb; i++) {
  1041. dump_packed_block_mxfp4x4x2(y, i, k);
  1042. }
  1043. }
  1044. // Unpack the quants
  1045. for (int i = 0; i < nb; i++) {
  1046. uint8_t qs[QK_MXFP4x4x2]; // unpacked quants
  1047. const uint8_t * q = y_q + (i * qblk_size);
  1048. for (int j = 0; j < qk / 2; j++) {
  1049. qs[j] = q[j] & 0xf;
  1050. qs[j + 128] = q[j] >> 4;
  1051. }
  1052. pack_mxfp4_quants(&x[i * 8 + 0], qs, 0);
  1053. pack_mxfp4_quants(&x[i * 8 + 1], qs, 1);
  1054. pack_mxfp4_quants(&x[i * 8 + 2], qs, 2);
  1055. pack_mxfp4_quants(&x[i * 8 + 3], qs, 3);
  1056. pack_mxfp4_quants(&x[i * 8 + 4], qs, 4);
  1057. pack_mxfp4_quants(&x[i * 8 + 5], qs, 5);
  1058. pack_mxfp4_quants(&x[i * 8 + 6], qs, 6);
  1059. pack_mxfp4_quants(&x[i * 8 + 7], qs, 7);
  1060. }
  1061. // Repack the scales
  1062. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_MXFP4_0x4x2)
  1063. // the last block is truncated and overriden by the scales.
  1064. for (int i = 0; i < nb; i++) {
  1065. // Unpack the scales
  1066. const uint8_t * e = (const uint8_t *) (y_e + i * eblk_size);
  1067. x[i * 8 + 0].e = e[0];
  1068. x[i * 8 + 1].e = e[1];
  1069. x[i * 8 + 2].e = e[2];
  1070. x[i * 8 + 3].e = e[3];
  1071. x[i * 8 + 4].e = e[4];
  1072. x[i * 8 + 5].e = e[5];
  1073. x[i * 8 + 6].e = e[6];
  1074. x[i * 8 + 7].e = e[7];
  1075. }
  1076. if (opt_verbose > 2) {
  1077. for (int i = 0; i < nb; i++) {
  1078. dump_block_mxfp4(&x[i * 8 + 0], 0);
  1079. dump_block_mxfp4(&x[i * 8 + 1], 1);
  1080. dump_block_mxfp4(&x[i * 8 + 2], 2);
  1081. dump_block_mxfp4(&x[i * 8 + 3], 3);
  1082. dump_block_mxfp4(&x[i * 8 + 4], 4);
  1083. dump_block_mxfp4(&x[i * 8 + 5], 5);
  1084. dump_block_mxfp4(&x[i * 8 + 6], 6);
  1085. dump_block_mxfp4(&x[i * 8 + 7], 7);
  1086. }
  1087. }
  1088. }
  1089. static void init_row_mxfp4x4x2(block_mxfp4 * x, int64_t k) {
  1090. static const int qk = QK_MXFP4x4x2;
  1091. const int nb = (k + qk - 1) / qk; // number of blocks (padded)
  1092. // Init the quants such that they unpack into zeros
  1093. uint8_t qs[QK_MXFP4x4x2]; // unpacked quants
  1094. memset(qs, 0, sizeof(qs));
  1095. for (int i = 0; i < nb; i++) {
  1096. pack_mxfp4_quants(&x[i * 8 + 0], qs, 0);
  1097. pack_mxfp4_quants(&x[i * 8 + 1], qs, 1);
  1098. pack_mxfp4_quants(&x[i * 8 + 2], qs, 2);
  1099. pack_mxfp4_quants(&x[i * 8 + 3], qs, 3);
  1100. pack_mxfp4_quants(&x[i * 8 + 4], qs, 4);
  1101. pack_mxfp4_quants(&x[i * 8 + 5], qs, 5);
  1102. pack_mxfp4_quants(&x[i * 8 + 6], qs, 6);
  1103. pack_mxfp4_quants(&x[i * 8 + 7], qs, 7);
  1104. }
  1105. // Init the scales
  1106. // Note: Do not combine with the loop above. For tensor sizes not multiple of 256 (QK_MXFP4x4x2)
  1107. // the last block is truncated and overriden by the scales.
  1108. for (int i = 0; i < nb; i++) {
  1109. // Unpack the scales
  1110. x[i * 8 + 0].e = 0;
  1111. x[i * 8 + 1].e = 0;
  1112. x[i * 8 + 2].e = 0;
  1113. x[i * 8 + 3].e = 0;
  1114. x[i * 8 + 4].e = 0;
  1115. x[i * 8 + 5].e = 0;
  1116. x[i * 8 + 6].e = 0;
  1117. x[i * 8 + 7].e = 0;
  1118. }
  1119. }
  1120. // repack mxfp4 data into mxfp4x4x2 tensor
  1121. static void repack_mxfp4_mxfp4x4x2(ggml_tensor * t, const void * data, size_t size) {
  1122. int64_t nrows = ggml_nrows(t);
  1123. size_t row_size = ggml_row_size(t->type, t->ne[0]);
  1124. size_t row_size_pd = ggml_row_size(t->type, hex_round_up(t->ne[0], QK_MXFP4x4x2)); // extra elements for the pad
  1125. size_t row_size_rp = row_size * 2; // extra space for tmp pad (if any)
  1126. // Ensure we don't try to read more data than is available in the source buffer 'data'
  1127. // or write more than the tensor can hold.
  1128. const size_t total_tensor_size = (size_t)nrows * row_size;
  1129. const size_t n_bytes_to_copy = size < total_tensor_size ? size : total_tensor_size;
  1130. // Calculate how many full rows and how many remaining bytes we need to process.
  1131. const int64_t n_full_rows = n_bytes_to_copy / row_size;
  1132. const size_t n_rem_bytes = n_bytes_to_copy % row_size;
  1133. void * buf_pd = ggml_aligned_malloc(row_size_pd);
  1134. GGML_ASSERT(buf_pd != NULL);
  1135. void * buf_rp = ggml_aligned_malloc(row_size_rp);
  1136. GGML_ASSERT(buf_rp != NULL);
  1137. HEX_VERBOSE("ggml-hex: repack-mxfp4-mxfp4x4x2 %s : data %p size %zu dims %ldx%ld row-size %zu\n", t->name, data,
  1138. size, t->ne[0], nrows, row_size);
  1139. init_row_mxfp4x4x2((block_mxfp4 *) buf_pd, t->ne[0]); // init padded buffer to make sure the tail is all zeros
  1140. // 1. Process all the full rows
  1141. for (int64_t i = 0; i < n_full_rows; i++) {
  1142. const uint8_t * src = (const uint8_t *) data + (i * row_size);
  1143. uint8_t * dst = (uint8_t *) t->data + (i * row_size);
  1144. memcpy(buf_pd, src, row_size);
  1145. repack_row_mxfp4x4x2((uint8_t *) buf_rp, (const block_mxfp4 *) buf_pd, t->ne[0]);
  1146. memcpy(dst, buf_rp, row_size);
  1147. }
  1148. // 2. Process the final, potentially partial, row
  1149. if (n_rem_bytes > 0) {
  1150. const int64_t i = n_full_rows;
  1151. const uint8_t * src = (const uint8_t *) data + (i * row_size);
  1152. uint8_t * dst = (uint8_t *) t->data + (i * row_size);
  1153. // re-init the row because we are potentially copying a partial row
  1154. init_row_mxfp4x4x2((block_mxfp4 *) buf_pd, t->ne[0]);
  1155. // Copy only the remaining bytes from the source.
  1156. memcpy(buf_pd, src, n_rem_bytes);
  1157. // Repack the entire buffer (partial data + zero padding).
  1158. repack_row_mxfp4x4x2((uint8_t *) buf_rp, (const block_mxfp4 *) buf_pd, t->ne[0]);
  1159. // Write only the corresponding remaining bytes to the destination tensor.
  1160. memcpy(dst, buf_rp, n_rem_bytes);
  1161. }
  1162. ggml_aligned_free(buf_pd, row_size_pd);
  1163. ggml_aligned_free(buf_rp, row_size_rp);
  1164. }
  1165. // repack mxfp4x4x2 tensor into mxfp4 data
  1166. static void repack_mxfp4x4x2_mxfp4(void * data, const ggml_tensor * t, size_t size) {
  1167. int64_t nrows = ggml_nrows(t);
  1168. size_t row_size = ggml_row_size(t->type, t->ne[0]);
  1169. size_t row_size_pd = ggml_row_size(t->type, hex_round_up(t->ne[0], QK_MXFP4x4x2)); // extra elements for the pad
  1170. size_t row_size_rp = row_size * 2; // extra space for tmp pad (if any)
  1171. // Ensure we don't try to copy more data than the tensor actually contains.
  1172. const size_t total_tensor_size = (size_t)nrows * row_size;
  1173. const size_t n_bytes_to_copy = size < total_tensor_size ? size : total_tensor_size;
  1174. // Calculate how many full rows and how many remaining bytes we need to process.
  1175. const int64_t n_full_rows = n_bytes_to_copy / row_size;
  1176. const size_t n_rem_bytes = n_bytes_to_copy % row_size;
  1177. void * buf_pd = ggml_aligned_malloc(row_size_pd);
  1178. GGML_ASSERT(buf_pd != NULL);
  1179. void * buf_rp = ggml_aligned_malloc(row_size_rp);
  1180. GGML_ASSERT(buf_rp != NULL);
  1181. HEX_VERBOSE("ggml-hex: repack-mxfp4x4x2-mxfp4 %s : data %p size %zu dims %ldx%ld row-size %zu\n", t->name, data,
  1182. size, t->ne[0], nrows, row_size);
  1183. memset(buf_pd, 0, row_size_pd); // clear-out padded buffer to make sure the tail is all zeros
  1184. // 1. Process all the full rows
  1185. for (int64_t i = 0; i < n_full_rows; i++) {
  1186. const uint8_t * src = (const uint8_t *) t->data + (i * row_size);
  1187. uint8_t * dst = (uint8_t *) data + (i * row_size);
  1188. memcpy(buf_pd, src, row_size);
  1189. unpack_row_mxfp4x4x2((block_mxfp4 *) buf_rp, (const uint8_t *) buf_pd, t->ne[0]);
  1190. memcpy(dst, buf_rp, row_size);
  1191. }
  1192. // 2. Process the final, potentially partial, row
  1193. if (n_rem_bytes > 0) {
  1194. const int64_t i = n_full_rows;
  1195. const uint8_t * src = (const uint8_t *) t->data + (i * row_size);
  1196. uint8_t * dst = (uint8_t *) data + (i * row_size);
  1197. // We still need to read and unpack the entire source row because the format is block-based.
  1198. memcpy(buf_pd, src, row_size);
  1199. unpack_row_mxfp4x4x2((block_mxfp4 *) buf_rp, (const uint8_t *) buf_pd, t->ne[0]);
  1200. // But we only copy the remaining number of bytes to the destination to respect the size limit.
  1201. memcpy(dst, buf_rp, n_rem_bytes);
  1202. }
  1203. ggml_aligned_free(buf_pd, row_size_pd);
  1204. ggml_aligned_free(buf_rp, row_size_rp);
  1205. }
  1206. static void ggml_backend_hexagon_buffer_set_tensor(ggml_backend_buffer_t buffer,
  1207. ggml_tensor * tensor,
  1208. const void * data,
  1209. size_t offset,
  1210. size_t size) {
  1211. auto ctx = (ggml_backend_hexagon_buffer_context *) buffer->context;
  1212. auto sess = ctx->sess;
  1213. HEX_VERBOSE("ggml-hex: %s set-tensor %s : data %p offset %zu size %zu\n", sess->name.c_str(), tensor->name, data,
  1214. offset, size);
  1215. switch (tensor->type) {
  1216. case GGML_TYPE_Q4_0:
  1217. GGML_ASSERT(offset == 0);
  1218. GGML_ASSERT(offset + size <= ggml_nbytes(tensor));
  1219. repack_q4_0_q4x4x2(tensor, data, size);
  1220. break;
  1221. case GGML_TYPE_Q8_0:
  1222. GGML_ASSERT(offset == 0);
  1223. GGML_ASSERT(offset + size <= ggml_nbytes(tensor));
  1224. repack_q8_0_q8x4x2(tensor, data, size);
  1225. break;
  1226. case GGML_TYPE_MXFP4:
  1227. GGML_ASSERT(offset == 0);
  1228. GGML_ASSERT(offset + size <= ggml_nbytes(tensor));
  1229. repack_mxfp4_mxfp4x4x2(tensor, data, size);
  1230. break;
  1231. default:
  1232. memcpy((char *) tensor->data + offset, data, size);
  1233. break;
  1234. }
  1235. }
  1236. static void ggml_backend_hexagon_buffer_get_tensor(ggml_backend_buffer_t buffer,
  1237. const ggml_tensor * tensor,
  1238. void * data,
  1239. size_t offset,
  1240. size_t size) {
  1241. auto ctx = (ggml_backend_hexagon_buffer_context *) buffer->context;
  1242. auto sess = ctx->sess;
  1243. HEX_VERBOSE("ggml-hex: %s get-tensor %s : data %p offset %zu size %zu\n", sess->name.c_str(), tensor->name, data,
  1244. offset, size);
  1245. switch (tensor->type) {
  1246. case GGML_TYPE_Q4_0:
  1247. GGML_ASSERT(offset == 0);
  1248. GGML_ASSERT(offset + size <= ggml_nbytes(tensor));
  1249. repack_q4x4x2_q4_0(data, tensor, size);
  1250. break;
  1251. case GGML_TYPE_Q8_0:
  1252. GGML_ASSERT(offset == 0);
  1253. GGML_ASSERT(offset + size <= ggml_nbytes(tensor));
  1254. repack_q8x4x2_q8_0(data, tensor, size);
  1255. break;
  1256. case GGML_TYPE_MXFP4:
  1257. GGML_ASSERT(offset == 0);
  1258. GGML_ASSERT(offset + size <= ggml_nbytes(tensor));
  1259. repack_mxfp4x4x2_mxfp4(data, tensor, size);
  1260. break;
  1261. default:
  1262. memcpy(data, (const char *) tensor->data + offset, size);
  1263. break;
  1264. }
  1265. }
  1266. static bool ggml_backend_hexagon_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
  1267. const struct ggml_tensor * src,
  1268. struct ggml_tensor * dst) {
  1269. GGML_UNUSED(buffer);
  1270. GGML_UNUSED(src);
  1271. GGML_UNUSED(dst);
  1272. // we might optimize this later, for now take the slow path (ie get/set_tensor)
  1273. return false;
  1274. }
  1275. static void ggml_backend_hexagon_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  1276. auto ctx = (ggml_backend_hexagon_buffer_context *) buffer->context;
  1277. auto sess = ctx->sess;
  1278. HEX_VERBOSE("ggml-hex: %s clear-buff base %p size %zu\n", sess->name.c_str(), (void *) ctx->base, ctx->size);
  1279. memset(ctx->base, value, ctx->size);
  1280. }
  1281. static ggml_backend_buffer_i ggml_backend_hexagon_buffer_interface = {
  1282. /* .free_buffer = */ ggml_backend_hexagon_buffer_free_buffer,
  1283. /* .get_base = */ ggml_backend_hexagon_buffer_get_base,
  1284. /* .init_tensor = */ ggml_backend_hexagon_buffer_init_tensor,
  1285. /* .memset_tensor = */ NULL,
  1286. /* .set_tensor = */ ggml_backend_hexagon_buffer_set_tensor,
  1287. /* .get_tensor = */ ggml_backend_hexagon_buffer_get_tensor,
  1288. /* .cpy_tensor = */ ggml_backend_hexagon_buffer_cpy_tensor,
  1289. /* .clear = */ ggml_backend_hexagon_buffer_clear,
  1290. /* .reset = */ NULL,
  1291. };
  1292. // ** backend buffer type
  1293. static const char * ggml_backend_hexagon_buffer_type_name(ggml_backend_buffer_type_t buffer_type) {
  1294. return static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer_type->context)->name.c_str();
  1295. }
  1296. static ggml_backend_buffer_t ggml_backend_hexagon_buffer_type_alloc_buffer(
  1297. ggml_backend_buffer_type_t buffer_type, size_t size) {
  1298. auto sess = static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer_type->context)->sess;
  1299. try {
  1300. ggml_backend_hexagon_buffer_context * ctx = new ggml_backend_hexagon_buffer_context(sess, size, false /*repack*/);
  1301. return ggml_backend_buffer_init(buffer_type, ggml_backend_hexagon_buffer_interface, ctx, size);
  1302. } catch (std::exception const &exc) {
  1303. GGML_LOG_ERROR("ggml-hex: %s failed to allocate buffer context: %s\n", sess->name.c_str(), exc.what());
  1304. return nullptr;
  1305. }
  1306. }
  1307. static ggml_backend_buffer_t ggml_backend_hexagon_repack_buffer_type_alloc_buffer(
  1308. ggml_backend_buffer_type_t buffer_type, size_t size) {
  1309. auto sess = static_cast<ggml_backend_hexagon_buffer_type_context *>(buffer_type->context)->sess;
  1310. try {
  1311. ggml_backend_hexagon_buffer_context * ctx = new ggml_backend_hexagon_buffer_context(sess, size, true /*repack*/);
  1312. return ggml_backend_buffer_init(buffer_type, ggml_backend_hexagon_buffer_interface, ctx, size);
  1313. } catch (std::exception const &exc) {
  1314. GGML_LOG_ERROR("ggml-hex: %s failed to allocate buffer context: %s\n", sess->name.c_str(), exc.what());
  1315. return nullptr;
  1316. }
  1317. }
  1318. static size_t ggml_backend_hexagon_buffer_type_get_alignment(ggml_backend_buffer_type_t buffer_type) {
  1319. return 128; // HVX alignment
  1320. GGML_UNUSED(buffer_type);
  1321. }
  1322. static size_t ggml_backend_hexagon_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const struct ggml_tensor * t) {
  1323. return ggml_nbytes(t);
  1324. }
  1325. static size_t ggml_backend_hexagon_buffer_type_get_max_size(ggml_backend_buffer_type_t buffer_type) {
  1326. return 1 * 1024 * 1024 * 1024; // 1GB per buffer
  1327. GGML_UNUSED(buffer_type);
  1328. }
  1329. static bool ggml_backend_hexagon_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
  1330. return opt_hostbuf;
  1331. GGML_UNUSED(buft);
  1332. }
  1333. static bool ggml_backend_hexagon_repack_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
  1334. return false;
  1335. GGML_UNUSED(buft);
  1336. }
  1337. static ggml_backend_buffer_type_i ggml_backend_hexagon_buffer_type_interface = {
  1338. /* .get_name = */ ggml_backend_hexagon_buffer_type_name,
  1339. /* .alloc_buffer = */ ggml_backend_hexagon_buffer_type_alloc_buffer,
  1340. /* .get_alignment = */ ggml_backend_hexagon_buffer_type_get_alignment,
  1341. /* .get_max_size = */ ggml_backend_hexagon_buffer_type_get_max_size,
  1342. /* .get_alloc_size = */ ggml_backend_hexagon_buffer_type_get_alloc_size,
  1343. /* .is_host = */ ggml_backend_hexagon_buffer_type_is_host,
  1344. };
  1345. static ggml_backend_buffer_type_i ggml_backend_hexagon_repack_buffer_type_interface = {
  1346. /* .get_name = */ ggml_backend_hexagon_buffer_type_name,
  1347. /* .alloc_buffer = */ ggml_backend_hexagon_repack_buffer_type_alloc_buffer,
  1348. /* .get_alignment = */ ggml_backend_hexagon_buffer_type_get_alignment,
  1349. /* .get_max_size = */ ggml_backend_hexagon_buffer_type_get_max_size,
  1350. /* .get_alloc_size = */ ggml_backend_hexagon_buffer_type_get_alloc_size,
  1351. /* .is_host = */ ggml_backend_hexagon_repack_buffer_type_is_host,
  1352. };
  1353. void ggml_hexagon_session::allocate(int dev_id) noexcept(false) {
  1354. this->valid_session = false;
  1355. this->valid_handle = false;
  1356. this->valid_queue = false;
  1357. this->valid_iface = false;
  1358. this->domain_id = 3; // Default for CDSP, updated after the session is created
  1359. this->session_id = 0; // Default for CDSP, updated after the session is created
  1360. this->dev_id = dev_id;
  1361. this->name = std::string("HTP") + std::to_string(dev_id);
  1362. this->op_pending = 0;
  1363. this->prof_usecs = 0;
  1364. this->prof_cycles = 0;
  1365. this->prof_pkts = 0;
  1366. GGML_LOG_INFO("ggml-hex: allocating new session: %s\n", this->name.c_str());
  1367. domain * my_domain = get_domain(this->domain_id);
  1368. if (my_domain == NULL) {
  1369. GGML_LOG_ERROR("ggml-hex: unable to get domain struct for CDSP\n");
  1370. throw std::runtime_error("ggml-hex: failed to get CDSP domain (see log for details)");
  1371. }
  1372. // Create new session
  1373. if (dev_id != 0) {
  1374. struct remote_rpc_reserve_new_session n;
  1375. n.domain_name_len = strlen(CDSP_DOMAIN_NAME);
  1376. n.domain_name = const_cast<char *>(CDSP_DOMAIN_NAME);
  1377. n.session_name = const_cast<char *>(this->name.c_str());
  1378. n.session_name_len = this->name.size();
  1379. int err = remote_session_control(FASTRPC_RESERVE_NEW_SESSION, (void *) &n, sizeof(n));
  1380. if (err != AEE_SUCCESS) {
  1381. GGML_LOG_ERROR("ggml-hex: failed to reserve new session %d : error 0x%x\n", dev_id, err);
  1382. throw std::runtime_error("ggml-hex: remote_session_control(new-sess) failed (see log for details)");
  1383. }
  1384. // Save the IDs
  1385. this->session_id = n.session_id;
  1386. this->domain_id = n.effective_domain_id;
  1387. this->valid_session = true;
  1388. }
  1389. // Get session URI
  1390. char session_uri[256];
  1391. {
  1392. char htp_uri[256];
  1393. snprintf(htp_uri, sizeof(htp_uri), "file:///libggml-htp-v%u.so?htp_iface_skel_handle_invoke&_modver=1.0", opt_arch);
  1394. struct remote_rpc_get_uri u = {};
  1395. u.session_id = this->session_id;
  1396. u.domain_name = const_cast<char *>(CDSP_DOMAIN_NAME);
  1397. u.domain_name_len = strlen(CDSP_DOMAIN_NAME);
  1398. u.module_uri = const_cast<char *>(htp_uri);
  1399. u.module_uri_len = strlen(htp_uri);
  1400. u.uri = session_uri;
  1401. u.uri_len = sizeof(session_uri);
  1402. int err = remote_session_control(FASTRPC_GET_URI, (void *) &u, sizeof(u));
  1403. if (err != AEE_SUCCESS) {
  1404. // fallback to single session uris
  1405. int htp_URI_domain_len = strlen(htp_uri) + MAX_DOMAIN_NAMELEN;
  1406. snprintf(session_uri, htp_URI_domain_len, "%s%s", htp_uri, my_domain->uri);
  1407. GGML_LOG_WARN("ggml-hex: failed to get URI for session %d : error 0x%x. Falling back to single session URI: %s\n", dev_id, err, session_uri);
  1408. }
  1409. }
  1410. // Enable Unsigned PD
  1411. {
  1412. struct remote_rpc_control_unsigned_module u;
  1413. u.domain = this->domain_id;
  1414. u.enable = 1;
  1415. int err = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, (void *) &u, sizeof(u));
  1416. if (err != AEE_SUCCESS) {
  1417. GGML_LOG_ERROR("ggml-hex: failed to enable unsigned PD for session %d : error 0x%x\n", dev_id, err);
  1418. throw std::runtime_error("ggml-hex: remote_session_control(unsign) failed (see log for details)");
  1419. }
  1420. }
  1421. // Open session
  1422. int err = htp_iface_open(session_uri, &this->handle);
  1423. if (err != AEE_SUCCESS) {
  1424. GGML_LOG_ERROR("ggml-hex: failed to open session %d : error 0x%x\n", dev_id, err);
  1425. throw std::runtime_error("ggml-hex: failed to open session (see log for details)");
  1426. }
  1427. this->valid_handle = true;
  1428. GGML_LOG_INFO("ggml-hex: new session: %s : session-id %d domain-id %d uri %s handle 0x%lx\n", this->name.c_str(),
  1429. this->session_id, this->domain_id, session_uri, (unsigned long) this->handle);
  1430. // Enable FastRPC QoS mode
  1431. {
  1432. struct remote_rpc_control_latency l;
  1433. l.enable = 1;
  1434. int err = remote_handle64_control(this->handle, DSPRPC_CONTROL_LATENCY, (void *) &l, sizeof(l));
  1435. if (err != 0) {
  1436. GGML_LOG_WARN("ggml-hex: failed to enable fastrpc QOS mode: 0x%08x\n", (unsigned) err);
  1437. }
  1438. }
  1439. // Now let's setup the DSP queue
  1440. err = dspqueue_create(this->domain_id,
  1441. 0, // Flags
  1442. 128 * 1024, // Request queue size (in bytes)
  1443. 64 * 1024, // Response queue size (in bytes)
  1444. nullptr, // Read packet callback (we handle reads explicitly)
  1445. nullptr, // Error callback (we handle errors during reads)
  1446. (void *) this, // Callback context
  1447. &queue);
  1448. if (err != 0) {
  1449. GGML_LOG_ERROR("ggml-hex: %s dspqueue_create failed: 0x%08x\n", this->name.c_str(), (unsigned) err);
  1450. throw std::runtime_error("ggml-hex: failed to create dspqueue (see log for details)");
  1451. }
  1452. this->valid_queue = true;
  1453. // Export queue for use on the DSP
  1454. err = dspqueue_export(queue, &this->queue_id);
  1455. if (err != 0) {
  1456. GGML_LOG_ERROR("ggml-hex: dspqueue_export failed: 0x%08x\n", (unsigned) err);
  1457. throw std::runtime_error("ggml-hex: dspqueue export failed (see log for details)");
  1458. }
  1459. if (opt_etm) {
  1460. err = htp_iface_enable_etm(this->handle);
  1461. if (err != 0) {
  1462. GGML_LOG_ERROR("ggml-hex: failed to enable ETM tracing: 0x%08x\n", (unsigned) err);
  1463. }
  1464. }
  1465. // Start the DSP-side service. We need to pass the queue ID to the
  1466. // DSP in a FastRPC call; the DSP side will import the queue and start
  1467. // listening for packets in a callback.
  1468. err = htp_iface_start(this->handle, dev_id, this->queue_id, opt_nhvx);
  1469. if (err != 0) {
  1470. GGML_LOG_ERROR("ggml-hex: failed to start session: 0x%08x\n", (unsigned) err);
  1471. throw std::runtime_error("ggml-hex: iface start failed (see log for details)");
  1472. }
  1473. this->valid_iface = true;
  1474. }
  1475. void ggml_hexagon_session::release() noexcept(true) {
  1476. GGML_LOG_INFO("ggml-hex: releasing session: %s\n", this->name.c_str());
  1477. int err;
  1478. // Stop the DSP-side service and close the queue
  1479. if (this->valid_iface) {
  1480. err = htp_iface_stop(this->handle);
  1481. if (err != 0) {
  1482. GGML_ABORT("ggml-hex: htp_iface_stop failed: 0x%08x\n", (unsigned) err);
  1483. }
  1484. }
  1485. if (opt_etm) {
  1486. err = htp_iface_disable_etm(this->handle);
  1487. if (err != 0) {
  1488. GGML_LOG_ERROR("ggml-hex: warn : failed to disable ETM tracing: 0x%08x\n", (unsigned) err);
  1489. }
  1490. }
  1491. if (this->valid_queue) {
  1492. err = dspqueue_close(queue);
  1493. if (err != 0) {
  1494. GGML_ABORT("ggml-hex: dspqueue_close failed: 0x%08x\n", (unsigned) err);
  1495. }
  1496. }
  1497. if (this->valid_handle) {
  1498. htp_iface_close(this->handle);
  1499. }
  1500. }
  1501. ggml_hexagon_session::ggml_hexagon_session(int dev_id, ggml_backend_dev_t dev) noexcept(false) {
  1502. buffer_type.context = nullptr;
  1503. repack_buffer_type.context = nullptr;
  1504. buffer_type.device = dev;
  1505. repack_buffer_type.device = dev;
  1506. try {
  1507. allocate(dev_id);
  1508. buffer_type.iface = ggml_backend_hexagon_buffer_type_interface;
  1509. buffer_type.context = new ggml_backend_hexagon_buffer_type_context(this->name, this);
  1510. repack_buffer_type.iface = ggml_backend_hexagon_repack_buffer_type_interface;
  1511. repack_buffer_type.context = new ggml_backend_hexagon_buffer_type_context(this->name + "-REPACK", this);
  1512. } catch (std::exception const &exc) {
  1513. release();
  1514. throw;
  1515. }
  1516. }
  1517. ggml_hexagon_session::~ggml_hexagon_session() noexcept(true) {
  1518. release();
  1519. delete static_cast<ggml_backend_hexagon_buffer_type_context*>(buffer_type.context);
  1520. delete static_cast<ggml_backend_hexagon_buffer_type_context*>(repack_buffer_type.context);
  1521. }
  1522. // ** backend interface
  1523. static bool ggml_backend_buffer_is_hexagon(const struct ggml_backend_buffer * b) {
  1524. return b->buft->iface.get_alignment == ggml_backend_hexagon_buffer_type_get_alignment;
  1525. }
  1526. static inline bool ggml_backend_buffer_is_hexagon_repack(const struct ggml_backend_buffer * b) {
  1527. return b->buft->iface.alloc_buffer == ggml_backend_hexagon_repack_buffer_type_alloc_buffer;
  1528. }
  1529. static bool hex_supported_dims2(const struct ggml_tensor * x, const struct ggml_tensor * y) {
  1530. if (x->ne[0] != y->ne[0]) {
  1531. return false;
  1532. }
  1533. if (x->ne[1] != y->ne[1]) {
  1534. return false;
  1535. }
  1536. if (x->ne[2] != y->ne[2]) {
  1537. return false;
  1538. }
  1539. if (x->ne[3] != y->ne[3]) {
  1540. return false;
  1541. }
  1542. return true;
  1543. }
  1544. static bool hex_supported_src0_type(ggml_type t) {
  1545. return t == GGML_TYPE_F32;
  1546. }
  1547. static bool hex_supported_src1_type(ggml_type t) {
  1548. return t == GGML_TYPE_F32;
  1549. }
  1550. static bool hex_supported_src2_type(ggml_type t) {
  1551. return t == GGML_TYPE_F32;
  1552. }
  1553. static bool hex_supported_src1_type2(ggml_type t) {
  1554. return t == GGML_TYPE_F16;
  1555. }
  1556. static bool hex_supported_src1_type3(ggml_type t) {
  1557. return t == GGML_TYPE_I32;
  1558. }
  1559. static bool hex_supported_dst_type(ggml_type t) {
  1560. return t == GGML_TYPE_F32;
  1561. }
  1562. static bool hex_supported_dims(const struct ggml_tensor * x, const struct ggml_tensor * y) {
  1563. // TODO: support broadcast for ne[2 and 3]
  1564. if (x->ne[0] != y->ne[0]) {
  1565. return false;
  1566. }
  1567. if (x->ne[2] != y->ne[2]) {
  1568. return false;
  1569. }
  1570. if (x->ne[3] != y->ne[3]) {
  1571. return false;
  1572. }
  1573. return true;
  1574. }
  1575. template <typename... _TTensor>
  1576. static inline bool hex_supported_buffer(const struct ggml_hexagon_session * sess, _TTensor... tensors) {
  1577. return ([&]() -> bool {
  1578. return !tensors || !tensors->buffer ||
  1579. (ggml_backend_buffer_is_hexagon(tensors->buffer) &&
  1580. ggml_backend_hexagon_buffer_get_sess(tensors->buffer) == sess);
  1581. }() && ...);
  1582. }
  1583. static bool ggml_hexagon_supported_mul_mat(const struct ggml_hexagon_session * sess, const struct ggml_tensor * dst) {
  1584. const struct ggml_tensor * src0 = dst->src[0];
  1585. const struct ggml_tensor * src1 = dst->src[1];
  1586. if (src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
  1587. return false;
  1588. }
  1589. // TODO: add support for non-cont tensors
  1590. if (!ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) {
  1591. return false;
  1592. }
  1593. switch (src0->type) {
  1594. case GGML_TYPE_Q4_0:
  1595. case GGML_TYPE_Q8_0:
  1596. case GGML_TYPE_MXFP4:
  1597. if (src0->ne[0] % 32) {
  1598. return false;
  1599. }
  1600. if (src0->ne[1] > 16 * 1024) {
  1601. return false; // typically the lm-head which would be too large for VTCM
  1602. }
  1603. // if ((src0->ne[2] != src1->ne[2] || src0->ne[3] != src1->ne[3])) return false;
  1604. if ((src1->ne[2] != 1 || src1->ne[3] != 1)) {
  1605. return false;
  1606. }
  1607. // src0 (weights) must be repacked
  1608. if (src0->buffer && !ggml_backend_buffer_is_hexagon_repack(src0->buffer)) {
  1609. return false;
  1610. }
  1611. break;
  1612. case GGML_TYPE_F16:
  1613. break;
  1614. default:
  1615. return false;
  1616. }
  1617. // src0 & src1 & dst must be mapped to the same session
  1618. if (!hex_supported_buffer(sess, src0, src1, dst)) {
  1619. return false;
  1620. }
  1621. return true;
  1622. }
  1623. static bool ggml_hexagon_supported_mul_mat_id(const struct ggml_hexagon_session * sess, const struct ggml_tensor * op) {
  1624. const struct ggml_tensor * src0 = op->src[0];
  1625. const struct ggml_tensor * src1 = op->src[1];
  1626. const struct ggml_tensor * src2 = op->src[2];
  1627. const struct ggml_tensor * dst = op;
  1628. if (src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || src2->type != GGML_TYPE_I32) {
  1629. return false;
  1630. }
  1631. switch (src0->type) {
  1632. case GGML_TYPE_Q4_0:
  1633. case GGML_TYPE_Q8_0:
  1634. case GGML_TYPE_MXFP4:
  1635. if ((src0->ne[0] % 32)) {
  1636. return false;
  1637. }
  1638. // src0 (weights) must be repacked
  1639. if (src0->buffer && !ggml_backend_buffer_is_hexagon_repack(src0->buffer)) {
  1640. return false;
  1641. }
  1642. break;
  1643. case GGML_TYPE_F16:
  1644. if (!opt_experimental) {
  1645. return false;
  1646. }
  1647. break;
  1648. default:
  1649. return false;
  1650. }
  1651. // TODO: add support for non-cont tensors
  1652. if (!ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) {
  1653. return false;
  1654. }
  1655. // src0 (weights) must be repacked and mapped to the same session
  1656. // src1 & sr2 & dst must be mapped to the same session
  1657. if (!hex_supported_buffer(sess, src0, src1, src2, dst)) {
  1658. return false;
  1659. }
  1660. return true;
  1661. }
  1662. static bool ggml_hexagon_supported_binary(const struct ggml_hexagon_session * sess, const struct ggml_tensor * op) {
  1663. const struct ggml_tensor * src0 = op->src[0];
  1664. const struct ggml_tensor * src1 = op->src[1];
  1665. const struct ggml_tensor * dst = op;
  1666. if (!hex_supported_src0_type(src0->type)) {
  1667. return false;
  1668. }
  1669. if (!hex_supported_src1_type(src1->type)) {
  1670. return false;
  1671. }
  1672. if (!hex_supported_dst_type(dst->type)) {
  1673. return false;
  1674. }
  1675. if (!hex_supported_dims2(src0, dst)) {
  1676. return false;
  1677. }
  1678. if (!ggml_can_repeat(src1, src0)) {
  1679. return false;
  1680. }
  1681. // TODO: add support for non-contigiuos tensors
  1682. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) {
  1683. return false;
  1684. }
  1685. // src0, src1 & dst must be mapped to the same session
  1686. if (!hex_supported_buffer(sess, src0, src1, dst)) {
  1687. return false;
  1688. }
  1689. return true;
  1690. }
  1691. static bool ggml_hexagon_supported_add_id(const struct ggml_hexagon_session * sess, const struct ggml_tensor * op) {
  1692. const struct ggml_tensor * src0 = op->src[0];
  1693. const struct ggml_tensor * src1 = op->src[1];
  1694. const struct ggml_tensor * src2 = op->src[2];
  1695. const struct ggml_tensor * dst = op;
  1696. if (!hex_supported_src0_type(src0->type)) {
  1697. return false;
  1698. }
  1699. if (!hex_supported_src1_type(src1->type)) {
  1700. return false;
  1701. }
  1702. if (!hex_supported_dst_type(dst->type)) {
  1703. return false;
  1704. }
  1705. if (!hex_supported_dims2(src0, dst)) {
  1706. return false;
  1707. }
  1708. // REVISIT: add support for non-contigiuos tensors
  1709. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) {
  1710. return false;
  1711. }
  1712. // src0, src1 & dst must be mapped to the same session
  1713. if (!hex_supported_buffer(sess, src0, src1, src2, dst)) {
  1714. return false;
  1715. }
  1716. return true;
  1717. }
  1718. static bool ggml_hexagon_supported_unary(const struct ggml_hexagon_session * sess, const struct ggml_tensor * op) {
  1719. const struct ggml_tensor * src0 = op->src[0];
  1720. const struct ggml_tensor * dst = op;
  1721. if (!hex_supported_src0_type(src0->type)) {
  1722. return false;
  1723. }
  1724. if (!hex_supported_dst_type(dst->type)) {
  1725. return false;
  1726. }
  1727. if (!hex_supported_dims2(src0, dst)) {
  1728. return false;
  1729. }
  1730. // TODO: add support for non-contigiuos tensors
  1731. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) {
  1732. return false;
  1733. }
  1734. // src0 & dst must be mapped to the same session
  1735. if (!hex_supported_buffer(sess, src0, dst)) {
  1736. return false;
  1737. }
  1738. return true;
  1739. }
  1740. static bool ggml_hexagon_supported_activations(const struct ggml_hexagon_session * sess,
  1741. const struct ggml_tensor * op) {
  1742. const struct ggml_tensor * src0 = op->src[0];
  1743. const struct ggml_tensor * src1 = op->src[1];
  1744. const struct ggml_tensor * dst = op;
  1745. if (!hex_supported_src0_type(src0->type)) {
  1746. return false;
  1747. }
  1748. if (!hex_supported_dst_type(dst->type)) {
  1749. return false;
  1750. }
  1751. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) {
  1752. return false;
  1753. }
  1754. if (src1) {
  1755. if (!hex_supported_src1_type(src1->type)) {
  1756. return false;
  1757. }
  1758. if (!hex_supported_dims2(src0, src1)) {
  1759. return false;
  1760. }
  1761. if (!ggml_is_contiguous(src1)) {
  1762. return false;
  1763. }
  1764. }
  1765. // src0, src1 & dst must be mapped to the same session
  1766. if(src1){
  1767. if (!hex_supported_buffer(sess, src0, src1, dst)) {
  1768. return false;
  1769. }
  1770. }else{
  1771. if (!hex_supported_buffer(sess, src0, dst)) {
  1772. return false;
  1773. }
  1774. }
  1775. return true;
  1776. }
  1777. static bool ggml_hexagon_supported_softmax(const struct ggml_hexagon_session * sess, const struct ggml_tensor * op) {
  1778. const struct ggml_tensor * src0 = op->src[0];
  1779. const struct ggml_tensor * src1 = op->src[1];
  1780. const struct ggml_tensor * src2 = op->src[2];
  1781. const struct ggml_tensor * dst = op;
  1782. if (src2) {
  1783. return false; // FIXME: add support for sinks
  1784. }
  1785. if (!hex_supported_src0_type(src0->type)) {
  1786. return false;
  1787. }
  1788. if (!hex_supported_dst_type(dst->type)) {
  1789. return false;
  1790. }
  1791. if (src1) {
  1792. if (!hex_supported_src1_type(src1->type) && !hex_supported_src1_type2(src1->type)) {
  1793. return false;
  1794. }
  1795. if (src0->ne[0] != src1->ne[0]) {
  1796. return false;
  1797. }
  1798. if (src1->ne[1] < src0->ne[1]) {
  1799. return false;
  1800. }
  1801. if (src0->ne[2] % src1->ne[2] != 0) {
  1802. return false;
  1803. }
  1804. if (src0->ne[3] % src1->ne[3] != 0) {
  1805. return false;
  1806. }
  1807. }
  1808. if (src1) {
  1809. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) {
  1810. return false;
  1811. }
  1812. } else {
  1813. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) {
  1814. return false;
  1815. }
  1816. }
  1817. // src0, src1 & dst must be mapped to the same session
  1818. if (!hex_supported_buffer(sess, src0, src1, dst)) {
  1819. return false;
  1820. }
  1821. return true;
  1822. }
  1823. static bool ggml_hexagon_supported_rope(const struct ggml_hexagon_session * sess, const struct ggml_tensor * op) {
  1824. const int32_t * op_params = &op->op_params[0];
  1825. int mode = op_params[2];
  1826. if ((mode & GGML_ROPE_TYPE_MROPE) || (mode & GGML_ROPE_TYPE_VISION)) {
  1827. return false;
  1828. }
  1829. if (mode & 1) {
  1830. return false;
  1831. }
  1832. const struct ggml_tensor * src0 = op->src[0];
  1833. const struct ggml_tensor * src1 = op->src[1];
  1834. const struct ggml_tensor * src2 = op->src[2];
  1835. const struct ggml_tensor * dst = op;
  1836. if (!hex_supported_src0_type(src0->type)) {
  1837. return false; // FIXME: add support for GGML_TYPE_F16 for src0
  1838. }
  1839. if (!hex_supported_dst_type(dst->type)) {
  1840. return false;
  1841. }
  1842. if (!hex_supported_src1_type3(src1->type)) {
  1843. return false;
  1844. }
  1845. if (src2) {
  1846. if (!hex_supported_src2_type(src2->type)) {
  1847. return false;
  1848. }
  1849. int n_dims = op_params[1];
  1850. if (src2->ne[0] < (n_dims / 2)) {
  1851. return false;
  1852. }
  1853. }
  1854. if (src2) {
  1855. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(src2) ||
  1856. !ggml_is_contiguous(dst)) {
  1857. return false;
  1858. }
  1859. } else {
  1860. if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) {
  1861. return false;
  1862. }
  1863. }
  1864. // src0, src1, src2 & dst must be mapped to the same session
  1865. if (!hex_supported_buffer(sess, src0, src1, src2, dst)) {
  1866. return false;
  1867. }
  1868. return true;
  1869. }
  1870. // Init hexagon tensor from GGML tensor and Hexagon buffer
  1871. static void init_htp_tensor(htp_tensor * h, const ggml_tensor * t) {
  1872. h->data = 0; // updated by the receiver
  1873. h->type = t->type;
  1874. h->ne[0] = t->ne[0];
  1875. h->ne[1] = t->ne[1];
  1876. h->ne[2] = t->ne[2];
  1877. h->ne[3] = t->ne[3];
  1878. h->nb[0] = t->nb[0];
  1879. h->nb[1] = t->nb[1];
  1880. h->nb[2] = t->nb[2];
  1881. h->nb[3] = t->nb[3];
  1882. }
  1883. static size_t dspqueue_buffers_init(dspqueue_buffer * buf, const ggml_tensor * t, bool flush_host, bool flush_htp) {
  1884. if (!t) {
  1885. return 0;
  1886. }
  1887. memset(buf, 0, sizeof(*buf));
  1888. auto tensor_buf = static_cast<ggml_backend_hexagon_buffer_context *>(t->buffer->context);
  1889. buf->fd = tensor_buf->fd;
  1890. buf->ptr = t->data;
  1891. buf->offset = (uint8_t *) t->data - tensor_buf->base;
  1892. buf->size = ggml_nbytes(t);
  1893. buf->flags = (flush_host ? DSPQUEUE_BUFFER_FLAG_FLUSH_SENDER : 0); // Flush CPU
  1894. buf->flags |= (flush_htp ? DSPQUEUE_BUFFER_FLAG_INVALIDATE_RECIPIENT : 0); // Invalidate DSP
  1895. return 1;
  1896. }
  1897. static ggml_hexagon_session * get_session_from_tensor(const ggml_tensor * t) {
  1898. return static_cast<ggml_backend_hexagon_buffer_context *>(t->buffer->context)->sess;
  1899. }
  1900. static void hex_dump_dspbuf(const struct ggml_tensor * t, const dspqueue_buffer * d) {
  1901. auto buf = static_cast<ggml_backend_hexagon_buffer_context *>(t->buffer->context);
  1902. auto sess = buf->sess;
  1903. HEX_VERBOSE("ggml-hex: %s dspqbuf : %s base-addr %p base-size %zu data %p offset %u size %u\n", sess->name.c_str(),
  1904. t->name, (void *) buf->base, buf->size, (void *) d->ptr, (unsigned int) d->offset,
  1905. (unsigned int) d->size);
  1906. }
  1907. static void ggml_hexagon_mul_mat(const struct ggml_tensor * op, uint32_t flags) {
  1908. const struct ggml_tensor * src0 = op->src[0];
  1909. const struct ggml_tensor * src1 = op->src[1];
  1910. const struct ggml_tensor * dst = op;
  1911. uint64_t t1, t2;
  1912. t1 = ggml_time_us();
  1913. // Construct HTP message
  1914. htp_general_req req;
  1915. req.op = HTP_OP_MUL_MAT;
  1916. req.flags = flags;
  1917. init_htp_tensor(&req.src0, src0);
  1918. init_htp_tensor(&req.src1, src1);
  1919. init_htp_tensor(&req.dst, dst);
  1920. // Use opmask to override flags
  1921. if (!(opt_opmask & HTP_OPMASK_QUANTIZE)) {
  1922. req.flags |= HTP_OPFLAGS_SKIP_QUANTIZE;
  1923. }
  1924. if (!(opt_opmask & HTP_OPMASK_COMPUTE)) {
  1925. req.flags |= HTP_OPFLAGS_SKIP_COMPUTE;
  1926. }
  1927. dspqueue_buffer bufs[3];
  1928. // First buffer Weights.
  1929. // The content is static, there is no need to do any cache management
  1930. dspqueue_buffers_init(bufs, src0, false, false);
  1931. // Second buffer Input Activations. This is a buffer that the CPU
  1932. // writes and the DSP reads, so we'll need to flush CPU caches and
  1933. // invalidate DSP ones. On platforms with I/O coherency support the
  1934. // framework will automatically skip cache operations where possible.
  1935. dspqueue_buffers_init(&bufs[1], src1, true, true);
  1936. // Third buffer Output Activations. We'll handle DSP
  1937. // cache maintenance in the response message but need to flush
  1938. // CPU caches to ensure any previously written dirty lines are
  1939. // written out before writes from the DSP start.
  1940. dspqueue_buffers_init(&bufs[2], dst, true, false);
  1941. auto * sess = get_session_from_tensor(src0);
  1942. if (opt_verbose) {
  1943. hex_print_op_info(op, sess, req.flags);
  1944. if (opt_verbose > 1) {
  1945. hex_dump_dspbuf(src0, &bufs[0]);
  1946. hex_dump_dspbuf(src1, &bufs[1]);
  1947. hex_dump_dspbuf(dst, &bufs[2]);
  1948. }
  1949. }
  1950. if ((opt_opmask & HTP_OPMASK_QUEUE)) {
  1951. sess->enqueue(req, bufs, 3, opt_opsync);
  1952. }
  1953. t2 = ggml_time_us();
  1954. HEX_PROFILE(
  1955. "ggml-hex: %s %s %s %u:%u:%u:%u x %s %u:%u:%u:%u -> %s %u:%u:%u:%u : op-usec %u op-cycles %u op-pkts %u (%f) "
  1956. "call-usec %llu\n",
  1957. sess->name.c_str(), ggml_op_name(op->op), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1],
  1958. (uint32_t) src0->ne[2], (uint32_t) src0->ne[3], src1->name, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1],
  1959. (uint32_t) src1->ne[2], (uint32_t) src1->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1],
  1960. (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  1961. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  1962. }
  1963. static void ggml_hexagon_mul_mat_id(const struct ggml_tensor * op, uint32_t flags) {
  1964. const struct ggml_tensor * src0 = op->src[0];
  1965. const struct ggml_tensor * src1 = op->src[1];
  1966. const struct ggml_tensor * src2 = op->src[2];
  1967. const struct ggml_tensor * dst = op;
  1968. uint64_t t1, t2;
  1969. t1 = ggml_time_us();
  1970. // Construct HTP message
  1971. htp_general_req req;
  1972. req.op = HTP_OP_MUL_MAT_ID;
  1973. req.flags = flags;
  1974. init_htp_tensor(&req.src0, src0);
  1975. init_htp_tensor(&req.src1, src1);
  1976. init_htp_tensor(&req.src2, src2);
  1977. init_htp_tensor(&req.dst, dst);
  1978. // Use opmask to override flags
  1979. if (!(opt_opmask & HTP_OPMASK_QUANTIZE)) {
  1980. req.flags |= HTP_OPFLAGS_SKIP_QUANTIZE;
  1981. }
  1982. if (!(opt_opmask & HTP_OPMASK_COMPUTE)) {
  1983. req.flags |= HTP_OPFLAGS_SKIP_COMPUTE;
  1984. }
  1985. dspqueue_buffer bufs[4];
  1986. // First buffer Weights.
  1987. // The content is static, there is no need to do any cache management
  1988. dspqueue_buffers_init(bufs, src0, false, false);
  1989. // Second buffer Input Activations. This is a buffer that the CPU
  1990. // writes and the DSP reads, so we'll need to flush CPU caches and
  1991. // invalidate DSP ones. On platforms with I/O coherency support the
  1992. // framework will automatically skip cache operations where possible.
  1993. dspqueue_buffers_init(&bufs[1], src1, true, true);
  1994. // Third buffer expert IDs. This is a buffer that the CPU
  1995. // writes and the DSP reads, so we'll need to flush CPU caches and
  1996. // invalidate DSP ones. On platforms with I/O coherency support the
  1997. // framework will automatically skip cache operations where possible.
  1998. dspqueue_buffers_init(&bufs[2], src2, true, true);
  1999. // Forth buffer Output Activations. We'll handle DSP
  2000. // cache maintenance in the response message but need to flush
  2001. // CPU caches to ensure any previously written dirty lines are
  2002. // written out before writes from the DSP start.
  2003. dspqueue_buffers_init(&bufs[3], dst, true, false);
  2004. auto * sess = get_session_from_tensor(src0);
  2005. if (opt_verbose) {
  2006. hex_print_op_info(op, sess, req.flags);
  2007. if (opt_verbose > 1) {
  2008. hex_dump_dspbuf(src0, &bufs[0]);
  2009. hex_dump_dspbuf(src1, &bufs[1]);
  2010. hex_dump_dspbuf(src2, &bufs[2]);
  2011. hex_dump_dspbuf(dst, &bufs[3]);
  2012. }
  2013. }
  2014. if ((opt_opmask & HTP_OPMASK_QUEUE)) {
  2015. sess->enqueue(req, bufs, 4, opt_opsync);
  2016. }
  2017. t2 = ggml_time_us();
  2018. HEX_PROFILE(
  2019. "ggml-hex: %s matmul-id %s %u:%u:%u:%u x %s %u:%u:%u:%u (%s %u:%u:%u:%u) -> %s %u:%u:%u:%u : op-usec %u "
  2020. "op-cycles %u op-pkts %u (%f) call-usec %llu\n",
  2021. sess->name.c_str(), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1], (uint32_t) src0->ne[2],
  2022. (uint32_t) src0->ne[3], src1->name, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1], (uint32_t) src1->ne[2],
  2023. (uint32_t) src1->ne[3], src2->name, (uint32_t) src2->ne[0], (uint32_t) src2->ne[1], (uint32_t) src2->ne[2],
  2024. (uint32_t) src2->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],
  2025. (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  2026. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  2027. }
  2028. static void ggml_hexagon_binary(const struct ggml_tensor * op, uint32_t flags) {
  2029. const struct ggml_tensor * node = op;
  2030. const struct ggml_tensor * src0 = node->src[0];
  2031. const struct ggml_tensor * src1 = node->src[1];
  2032. const struct ggml_tensor * dst = node;
  2033. uint64_t t1 = 0;
  2034. uint64_t t2 = 0;
  2035. t1 = ggml_time_us();
  2036. // Construct HTP message
  2037. htp_general_req req;
  2038. req.flags = flags;
  2039. // Use opmask to override flags
  2040. if (!(opt_opmask & HTP_OPMASK_QUANTIZE)) {
  2041. req.flags |= HTP_OPFLAGS_SKIP_QUANTIZE;
  2042. }
  2043. if (!(opt_opmask & HTP_OPMASK_COMPUTE)) {
  2044. req.flags |= HTP_OPFLAGS_SKIP_COMPUTE;
  2045. }
  2046. switch (node->op) {
  2047. case GGML_OP_MUL:
  2048. req.op = HTP_OP_MUL;
  2049. break;
  2050. case GGML_OP_ADD:
  2051. req.op = HTP_OP_ADD;
  2052. break;
  2053. case GGML_OP_SUB:
  2054. req.op = HTP_OP_SUB;
  2055. break;
  2056. default:
  2057. GGML_ABORT("ggml-hex: binary : unsupported op:%d\n", node->op);
  2058. }
  2059. init_htp_tensor(&req.src0, src0);
  2060. init_htp_tensor(&req.src1, src1);
  2061. init_htp_tensor(&req.dst, dst);
  2062. dspqueue_buffer bufs[3];
  2063. // First buffer = First Operand of Binary op
  2064. // This is a buffer that the CPU writes and the DSP reads, so we'll
  2065. // need to flush CPU caches and invalidate DSP ones. On platforms
  2066. // with I/O coherency support the framework will automatically skip
  2067. // cache operations where possible.
  2068. dspqueue_buffers_init(bufs, src0, true, true);
  2069. // Second buffer = Second Operand of Binary op
  2070. // This is a buffer that the CPU writes and the DSP reads, so we'll
  2071. // need to flush CPU caches and invalidate DSP ones. On platforms
  2072. // with I/O coherency support the framework will automatically skip
  2073. // cache operations where possible.
  2074. dspqueue_buffers_init(&bufs[1], src1, true, true);
  2075. // Third buffer = Output Activations. We'll handle DSP
  2076. // cache maintenance in the response message but need to flush
  2077. // CPU caches to ensure any previously written dirty lines are
  2078. // written out before writes from the DSP start.
  2079. dspqueue_buffers_init(&bufs[2], dst, true, false);
  2080. auto * sess = get_session_from_tensor(src0);
  2081. if (opt_verbose) {
  2082. hex_print_op_info(op, sess, req.flags);
  2083. if (opt_verbose > 1) {
  2084. hex_dump_dspbuf(src0, &bufs[0]);
  2085. hex_dump_dspbuf(src1, &bufs[1]);
  2086. hex_dump_dspbuf(dst, &bufs[2]);
  2087. }
  2088. }
  2089. if ((opt_opmask & HTP_OPMASK_QUEUE)) {
  2090. sess->enqueue(req, bufs, 3, opt_opsync);
  2091. }
  2092. t2 = ggml_time_us();
  2093. HEX_PROFILE(
  2094. "ggml-hex: %s %s %s %u:%u:%u:%u x %s %u:%u:%u:%u -> %s %u:%u:%u:%u : op-usec %u op-cycles %u op-pkts %u (%f) "
  2095. "call-usec %llu\n",
  2096. sess->name.c_str(), ggml_op_name(node->op), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1],
  2097. (uint32_t) src0->ne[2], (uint32_t) src0->ne[3], src1->name, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1],
  2098. (uint32_t) src1->ne[2], (uint32_t) src1->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1],
  2099. (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  2100. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  2101. }
  2102. static void ggml_hexagon_add_id(const struct ggml_tensor * op, uint32_t flags) {
  2103. const struct ggml_tensor * node = op;
  2104. const struct ggml_tensor * src0 = node->src[0];
  2105. const struct ggml_tensor * src1 = node->src[1];
  2106. const struct ggml_tensor * src2 = node->src[2];
  2107. const struct ggml_tensor * dst = node;
  2108. uint64_t t1 = 0;
  2109. uint64_t t2 = 0;
  2110. t1 = ggml_time_us();
  2111. // Construct HTP message
  2112. htp_general_req req;
  2113. req.flags = flags;
  2114. // Use opmask to override flags
  2115. if (!(opt_opmask & HTP_OPMASK_QUANTIZE)) {
  2116. req.flags |= HTP_OPFLAGS_SKIP_QUANTIZE;
  2117. }
  2118. if (!(opt_opmask & HTP_OPMASK_COMPUTE)) {
  2119. req.flags |= HTP_OPFLAGS_SKIP_COMPUTE;
  2120. }
  2121. switch (node->op) {
  2122. case GGML_OP_ADD_ID:
  2123. req.op = HTP_OP_ADD_ID;
  2124. break;
  2125. default:
  2126. GGML_ABORT("ggml-hex: unsupported op:%d\n", node->op);
  2127. }
  2128. init_htp_tensor(&req.src0, src0);
  2129. init_htp_tensor(&req.src1, src1);
  2130. init_htp_tensor(&req.src2, src2);
  2131. init_htp_tensor(&req.dst, dst);
  2132. dspqueue_buffer bufs[4];
  2133. // First buffer = input activations
  2134. dspqueue_buffers_init(bufs, src0, true, true);
  2135. // Second buffer = experts bias
  2136. dspqueue_buffers_init(&bufs[1], src1, true, true);
  2137. // Third buffer = activated experts
  2138. dspqueue_buffers_init(&bufs[2], src2, true, true);
  2139. // Forth buffer = output activations
  2140. dspqueue_buffers_init(&bufs[3], dst, true, true);
  2141. auto * sess = get_session_from_tensor(src0);
  2142. if (opt_verbose) {
  2143. hex_print_op_info(op, sess, req.flags);
  2144. if (opt_verbose > 1) {
  2145. hex_dump_dspbuf(src0, &bufs[0]);
  2146. hex_dump_dspbuf(src1, &bufs[1]);
  2147. hex_dump_dspbuf(src2, &bufs[2]);
  2148. hex_dump_dspbuf(dst, &bufs[3]);
  2149. }
  2150. }
  2151. if ((opt_opmask & HTP_OPMASK_QUEUE)) {
  2152. sess->enqueue(req, bufs, 4, opt_opsync);
  2153. }
  2154. t2 = ggml_time_us();
  2155. HEX_PROFILE(
  2156. "ggml-hex: %s %s %s %u:%u:%u:%u x %s %u:%u:%u:%u -> %s %u:%u:%u:%u : op-usec %u op-cycles %u op-pkts %u (%f) "
  2157. "call-usec %llu\n",
  2158. sess->name.c_str(), ggml_op_name(node->op), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1],
  2159. (uint32_t) src0->ne[2], (uint32_t) src0->ne[3], src1->name, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1],
  2160. (uint32_t) src1->ne[2], (uint32_t) src1->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1],
  2161. (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  2162. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  2163. }
  2164. static void ggml_hexagon_unary(const struct ggml_tensor * op, uint32_t flags) {
  2165. const struct ggml_tensor * src0 = op->src[0];
  2166. const struct ggml_tensor * src1 = op->src[1];
  2167. const struct ggml_tensor * dst = op;
  2168. uint64_t t1 = 0;
  2169. uint64_t t2 = 0;
  2170. t1 = ggml_time_us();
  2171. // Construct HTP message
  2172. htp_general_req req;
  2173. memset(&req, 0, sizeof(htp_general_req));
  2174. memcpy(&req.op_params, &op->op_params, sizeof(op->op_params));
  2175. req.flags = flags;
  2176. bool supported = false;
  2177. switch (op->op) {
  2178. case GGML_OP_RMS_NORM:
  2179. req.op = HTP_OP_RMS_NORM;
  2180. supported = true;
  2181. break;
  2182. case GGML_OP_UNARY:
  2183. if (ggml_get_unary_op(dst) == GGML_UNARY_OP_SILU) {
  2184. req.op = HTP_OP_UNARY_SILU;
  2185. supported = true;
  2186. }
  2187. else if (ggml_get_unary_op(dst) == GGML_UNARY_OP_GELU){
  2188. req.op = HTP_OP_UNARY_GELU;
  2189. supported = true;
  2190. }
  2191. break;
  2192. case GGML_OP_GLU:
  2193. if (ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU) {
  2194. req.op = HTP_OP_GLU_SWIGLU;
  2195. supported = true;
  2196. } else if (ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU_OAI) {
  2197. req.op = HTP_OP_GLU_SWIGLU_OAI;
  2198. supported = true;
  2199. }
  2200. break;
  2201. case GGML_OP_SOFT_MAX:
  2202. req.op = HTP_OP_SOFTMAX;
  2203. supported = true;
  2204. break;
  2205. default:
  2206. break;
  2207. }
  2208. if (!supported) {
  2209. GGML_ABORT("ggml-hex: unary : unsupported op:%d\n", op->op);
  2210. }
  2211. init_htp_tensor(&req.dst, dst);
  2212. init_htp_tensor(&req.src0, src0);
  2213. if (src1) {
  2214. init_htp_tensor(&req.src1, src1);
  2215. }
  2216. // Use opmask to override flags
  2217. if (!(opt_opmask & HTP_OPMASK_QUANTIZE)) {
  2218. req.flags |= HTP_OPFLAGS_SKIP_QUANTIZE;
  2219. }
  2220. if (!(opt_opmask & HTP_OPMASK_COMPUTE)) {
  2221. req.flags |= HTP_OPFLAGS_SKIP_COMPUTE;
  2222. }
  2223. dspqueue_buffer bufs[3];
  2224. // First buffer = Only Operand of Unary op
  2225. // This is a buffer that the CPU writes and the DSP reads, so we'll
  2226. // need to flush CPU caches and invalidate DSP ones. On platforms
  2227. // with I/O coherency support the framework will automatically skip
  2228. // cache operations where possible.
  2229. size_t n_bufs = dspqueue_buffers_init(bufs, src0, true, true);
  2230. // Second buffer(nullable) = Second Operand of Binary op
  2231. // This is a buffer that the CPU writes and the DSP reads, so we'll
  2232. // need to flush CPU caches and invalidate DSP ones. On platforms
  2233. // with I/O coherency support the framework will automatically skip
  2234. // cache operations where possible.
  2235. n_bufs += dspqueue_buffers_init(&bufs[n_bufs], src1, true, true);
  2236. // Second or third buffer = Output Activations. We'll handle DSP
  2237. // Second buffer = Output Activations. We'll handle DSP
  2238. // cache maintenance in the response message but need to flush
  2239. // CPU caches to ensure any previously written dirty lines are
  2240. // written out before writes from the DSP start.
  2241. n_bufs += dspqueue_buffers_init(&bufs[n_bufs], dst, true, false);
  2242. // Primary DSP session from the src0 tensor
  2243. auto * sess = get_session_from_tensor(src0);
  2244. if (opt_verbose) {
  2245. hex_print_op_info(op, sess, req.flags);
  2246. if (opt_verbose > 1) {
  2247. hex_dump_dspbuf(src0, &bufs[0]);
  2248. if (src1) {
  2249. hex_dump_dspbuf(src1, &bufs[1]);
  2250. hex_dump_dspbuf(dst, &bufs[2]);
  2251. } else {
  2252. hex_dump_dspbuf(dst, &bufs[1]);
  2253. }
  2254. }
  2255. }
  2256. if ((opt_opmask & HTP_OPMASK_QUEUE)) {
  2257. sess->enqueue(req, bufs, n_bufs, opt_opsync);
  2258. }
  2259. t2 = ggml_time_us();
  2260. if (src1) {
  2261. HEX_PROFILE(
  2262. "ggml-hex: %s %s %s %u:%u:%u:%u x %s %u:%u:%u:%u -> %s %u:%u:%u:%u : op-usec %u op-cycles %u op-pkts %u "
  2263. "(%f) call-usec %llu\n",
  2264. sess->name.c_str(), ggml_op_name(op->op), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1],
  2265. (uint32_t) src0->ne[2], (uint32_t) src0->ne[3], src1->name, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1],
  2266. (uint32_t) src1->ne[2], (uint32_t) src1->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1],
  2267. (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  2268. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  2269. } else {
  2270. HEX_PROFILE(
  2271. "ggml-hex: %s %s %s %u:%u:%u:%u -> %s %u:%u:%u:%u : op-usec %u op-cycles %u op-pkts %u (%f) call-usec "
  2272. "%llu\n",
  2273. sess->name.c_str(), ggml_op_name(op->op), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1],
  2274. (uint32_t) src0->ne[2], (uint32_t) src0->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1],
  2275. (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  2276. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  2277. }
  2278. }
  2279. static void ggml_hexagon_rope(const struct ggml_tensor * op, uint32_t flags) {
  2280. const struct ggml_tensor * src0 = op->src[0];
  2281. const struct ggml_tensor * src1 = op->src[1];
  2282. const struct ggml_tensor * src2 = op->src[2];
  2283. const struct ggml_tensor * dst = op;
  2284. uint64_t t1 = 0;
  2285. uint64_t t2 = 0;
  2286. t1 = ggml_time_us();
  2287. // Construct HTP message
  2288. htp_general_req req;
  2289. memset(&req, 0, sizeof(htp_general_req));
  2290. memcpy(&req.op_params, &op->op_params, sizeof(op->op_params));
  2291. req.flags = flags;
  2292. req.op = HTP_OP_ROPE;
  2293. init_htp_tensor(&req.dst, dst);
  2294. init_htp_tensor(&req.src0, src0);
  2295. init_htp_tensor(&req.src1, src1);
  2296. if (src2) {
  2297. init_htp_tensor(&req.src2, src2);
  2298. }
  2299. // Use opmask to override flags
  2300. if (!(opt_opmask & HTP_OPMASK_QUANTIZE)) {
  2301. req.flags |= HTP_OPFLAGS_SKIP_QUANTIZE;
  2302. }
  2303. if (!(opt_opmask & HTP_OPMASK_COMPUTE)) {
  2304. req.flags |= HTP_OPFLAGS_SKIP_COMPUTE;
  2305. }
  2306. dspqueue_buffer bufs[4];
  2307. // First buffer
  2308. // This is a buffer that the CPU writes and the DSP reads, so we'll
  2309. // need to flush CPU caches and invalidate DSP ones. On platforms
  2310. // with I/O coherency support the framework will automatically skip
  2311. // cache operations where possible.
  2312. size_t n_bufs = dspqueue_buffers_init(bufs, src0, true, true);
  2313. // Second buffer
  2314. // This is a buffer that the CPU writes and the DSP reads, so we'll
  2315. // need to flush CPU caches and invalidate DSP ones. On platforms
  2316. // with I/O coherency support the framework will automatically skip
  2317. // cache operations where possible.
  2318. n_bufs += dspqueue_buffers_init(&bufs[n_bufs], src1, true, true);
  2319. // Third buffer(nullable)
  2320. // This is a buffer that the CPU writes and the DSP reads, so we'll
  2321. // need to flush CPU caches and invalidate DSP ones. On platforms
  2322. // with I/O coherency support the framework will automatically skip
  2323. // cache operations where possible.
  2324. n_bufs += dspqueue_buffers_init(&bufs[n_bufs], src2, true, true);
  2325. // Final buffer = Output Activations. We'll handle DSP
  2326. // Second buffer = Output Activations. We'll handle DSP
  2327. // cache maintenance in the response message but need to flush
  2328. // CPU caches to ensure any previously written dirty lines are
  2329. // written out before writes from the DSP start.
  2330. n_bufs += dspqueue_buffers_init(&bufs[n_bufs], dst, true, false);
  2331. // Primary DSP session from the src0 tensor
  2332. auto * sess = get_session_from_tensor(src0);
  2333. if (opt_verbose) {
  2334. hex_print_op_info(op, sess, req.flags);
  2335. if (opt_verbose > 1) {
  2336. hex_dump_dspbuf(src0, &bufs[0]);
  2337. if (src1) {
  2338. hex_dump_dspbuf(src1, &bufs[1]);
  2339. hex_dump_dspbuf(dst, &bufs[2]);
  2340. } else {
  2341. hex_dump_dspbuf(dst, &bufs[1]);
  2342. }
  2343. }
  2344. }
  2345. if ((opt_opmask & HTP_OPMASK_QUEUE)) {
  2346. sess->enqueue(req, bufs, n_bufs, opt_opsync);
  2347. }
  2348. t2 = ggml_time_us();
  2349. if (src2) {
  2350. HEX_PROFILE(
  2351. "ggml-hex: %s %s %s %u:%u:%u:%u x %s %u:%u:%u:%u x %s %u:%u:%u:%u -> %s %u:%u:%u:%u : op-usec %u op-cycles "
  2352. "%u op-pkts %u (%f) call-usec %llu\n",
  2353. sess->name.c_str(), ggml_op_name(op->op), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1],
  2354. (uint32_t) src0->ne[2], (uint32_t) src0->ne[3], src1->name, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1],
  2355. (uint32_t) src1->ne[2], (uint32_t) src1->ne[3], src2->name, (uint32_t) src2->ne[0], (uint32_t) src2->ne[1],
  2356. (uint32_t) src2->ne[2], (uint32_t) src2->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1],
  2357. (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  2358. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  2359. } else {
  2360. HEX_PROFILE(
  2361. "ggml-hex: %s %s %s %u:%u:%u:%u x %s %u:%u:%u:%u -> %s %u:%u:%u:%u : op-usec %u op-cycles %u op-pkts %u "
  2362. "(%f) call-usec %llu\n",
  2363. sess->name.c_str(), ggml_op_name(op->op), src0->name, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1],
  2364. (uint32_t) src0->ne[2], (uint32_t) src0->ne[3], src1->name, (uint32_t) src1->ne[0], (uint32_t) src1->ne[1],
  2365. (uint32_t) src1->ne[2], (uint32_t) src1->ne[3], dst->name, (uint32_t) dst->ne[0], (uint32_t) dst->ne[1],
  2366. (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], sess->prof_usecs, sess->prof_cycles, sess->prof_pkts,
  2367. (float) sess->prof_cycles / sess->prof_pkts, (unsigned long long) t2 - t1);
  2368. }
  2369. }
  2370. static const char * ggml_backend_hexagon_name(ggml_backend_t backend) {
  2371. auto sess = static_cast<ggml_hexagon_session *>(backend->context);
  2372. return sess->name.c_str();
  2373. }
  2374. static void ggml_backend_hexagon_free(ggml_backend_t backend) {
  2375. // we just need to delete the backend here
  2376. // the sessions are allocated & freed as part of the registry
  2377. delete backend;
  2378. }
  2379. static inline bool op_reuse_src1(const ggml_tensor * op1, const ggml_tensor * op0) {
  2380. return (op0 && op0->src[1] == op1->src[1]);
  2381. }
  2382. static inline bool is_compute_op(ggml_tensor *node)
  2383. {
  2384. return !(ggml_op_is_empty(node->op) || ggml_is_empty(node));
  2385. }
  2386. // scan the graph and figure out last compute op index
  2387. static inline int last_compute_op(ggml_cgraph * graph) {
  2388. int last = 0;
  2389. for (int i = 0; i < graph->n_nodes; ++i) {
  2390. if (is_compute_op(graph->nodes[i])) {
  2391. last = i;
  2392. }
  2393. }
  2394. return last;
  2395. }
  2396. static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, ggml_cgraph * graph) {
  2397. auto sess = static_cast<ggml_hexagon_session *>(backend->context);
  2398. HEX_VERBOSE("ggml-hex: %s graph-compute n_nodes %d\n", sess->name.c_str(), graph->n_nodes);
  2399. const int last = last_compute_op(graph);
  2400. const struct ggml_tensor * prev_quant_op = nullptr; // prev executed op with quantizer
  2401. for (int i = 0; i < graph->n_nodes; ++i) {
  2402. ggml_tensor * node = graph->nodes[i];
  2403. if (!is_compute_op(node)) {
  2404. continue;
  2405. }
  2406. uint32_t flags = 0;
  2407. // skip quantizer if src1 is reused
  2408. if (op_reuse_src1(node, prev_quant_op)) {
  2409. flags |= HTP_OPFLAGS_SKIP_QUANTIZE;
  2410. }
  2411. // ask for early notification for the last Op
  2412. if (i == last) {
  2413. flags |= HTP_OPFLAGS_EARLY_WAKEUP;
  2414. }
  2415. switch (node->op) {
  2416. case GGML_OP_MUL_MAT:
  2417. ggml_hexagon_mul_mat(node, flags);
  2418. prev_quant_op = node;
  2419. break;
  2420. case GGML_OP_MUL_MAT_ID:
  2421. ggml_hexagon_mul_mat_id(node, flags);
  2422. prev_quant_op = node;
  2423. break;
  2424. case GGML_OP_MUL:
  2425. case GGML_OP_ADD:
  2426. case GGML_OP_SUB:
  2427. ggml_hexagon_binary(node, flags);
  2428. break;
  2429. case GGML_OP_ADD_ID:
  2430. ggml_hexagon_add_id(node, flags);
  2431. break;
  2432. case GGML_OP_RMS_NORM:
  2433. ggml_hexagon_unary(node, flags);
  2434. break;
  2435. case GGML_OP_UNARY:
  2436. if (ggml_get_unary_op(node) == GGML_UNARY_OP_SILU) {
  2437. ggml_hexagon_unary(node, flags);
  2438. } else if (ggml_get_unary_op(node) == GGML_UNARY_OP_GELU) {
  2439. ggml_hexagon_unary(node, flags);
  2440. }
  2441. break;
  2442. case GGML_OP_GLU:
  2443. if ((ggml_get_glu_op(node) == GGML_GLU_OP_SWIGLU) ||
  2444. (ggml_get_glu_op(node) == GGML_GLU_OP_SWIGLU_OAI)) {
  2445. ggml_hexagon_unary(node, flags);
  2446. }
  2447. break;
  2448. case GGML_OP_SOFT_MAX:
  2449. ggml_hexagon_unary(node, flags);
  2450. break;
  2451. case GGML_OP_ROPE:
  2452. ggml_hexagon_rope(node, flags);
  2453. break;
  2454. default:
  2455. GGML_ABORT("\nggml-hex: graph-compute %s is not supported\n", ggml_op_desc(node));
  2456. }
  2457. }
  2458. // Wait until all pending ops complete
  2459. sess->flush();
  2460. return GGML_STATUS_SUCCESS;
  2461. }
  2462. static void ggml_backend_hexagon_synchronize(ggml_backend_t backend) {
  2463. auto sess = static_cast<ggml_hexagon_session *>(backend->context);
  2464. HEX_VERBOSE("ggml-hex: %s synchronize\n", sess->name.c_str());
  2465. // Wait until all pending ops complete
  2466. sess->flush();
  2467. }
  2468. struct node_info {
  2469. ggml_tensor * node;
  2470. std::vector<ggml_tensor *> fused;
  2471. ggml_op op() const {
  2472. return node->op;
  2473. }
  2474. const ggml_tensor * dst() const {
  2475. return fused.empty() ? node : fused.back();
  2476. }
  2477. const ggml_tensor * src0() const {
  2478. return node->src[0];
  2479. }
  2480. const ggml_tensor * src1() const {
  2481. return node->src[1];
  2482. }
  2483. bool is_empty() const {
  2484. return ggml_op_is_empty(node->op);
  2485. }
  2486. void add_fused(ggml_tensor * t) {
  2487. fused.push_back(t);
  2488. }
  2489. bool stackable() const {
  2490. switch (this->op()) {
  2491. case GGML_OP_MUL_MAT:
  2492. case GGML_OP_MUL_MAT_ID:
  2493. return ggml_is_quantized(this->src0()->type);
  2494. default:
  2495. return false;
  2496. }
  2497. }
  2498. bool same_input(const node_info& n) const {
  2499. return n.src1() == this->src1();
  2500. }
  2501. };
  2502. static std::vector<int> ggml_hexagon_graph_optimize_reorder(const std::vector<node_info> & nodes) {
  2503. const int n = nodes.size();
  2504. std::vector<int> res;
  2505. res.reserve(n);
  2506. std::vector<bool> used(n, false);
  2507. // The main goal here is to stack the MUL_MAT ops with the same src1 input.
  2508. // This allows use to reuse dynamically quantized src1 in VTCM.
  2509. // TODO: the current version might do incorrect reodering in cases where quantized src0
  2510. // input is an output of another Op.
  2511. for (int i0 = 0; i0 < n; i0++) {
  2512. if (used[i0]) {
  2513. continue;
  2514. }
  2515. res.push_back(i0);
  2516. const auto & node0 = nodes[i0];
  2517. if (!node0.stackable()) {
  2518. continue;
  2519. }
  2520. // that many nodes forward to search for stackable nodes that can reuse VTCM
  2521. constexpr int N_FORWARD = 8;
  2522. for (int i1 = i0 + 1; i1 < i0 + N_FORWARD && i1 < n; i1++) {
  2523. if (used[i1]) {
  2524. continue;
  2525. }
  2526. const auto & node1 = nodes[i1];
  2527. if (node1.stackable() && node1.same_input(node0)) {
  2528. res.push_back(i1);
  2529. used[i1] = true;
  2530. }
  2531. }
  2532. }
  2533. return res;
  2534. }
  2535. static void ggml_backend_hexagon_graph_optimize(ggml_backend_t backend, ggml_cgraph * gf) {
  2536. const int n = gf->n_nodes;
  2537. constexpr int MAX_FUSE = 16;
  2538. enum ggml_op ops[MAX_FUSE];
  2539. std::vector<node_info> nodes;
  2540. nodes.reserve(gf->n_nodes);
  2541. // fuse nodes:
  2542. // we don't want to make reorders that break fusing, so we first pack all fusable tensors
  2543. // and perform the reorder over the fused nodes. after the reorder is done, we unfuse
  2544. for (int i = 0; i < n; i++) {
  2545. node_info node = {
  2546. /*.node =*/ gf->nodes[i],
  2547. /*.fused =*/ {},
  2548. };
  2549. // fuse only ops that start with these operations
  2550. // can be expanded when needed
  2551. if (node.op() == GGML_OP_ADD ||
  2552. node.op() == GGML_OP_NORM ||
  2553. node.op() == GGML_OP_RMS_NORM) {
  2554. ops[0] = node.op();
  2555. int f = i + 1;
  2556. while (f < n && f < i + MAX_FUSE) {
  2557. // conservatively allow fusing only these ops
  2558. // can be expanded when needed
  2559. if (gf->nodes[f]->op != GGML_OP_ADD &&
  2560. gf->nodes[f]->op != GGML_OP_MUL &&
  2561. gf->nodes[f]->op != GGML_OP_NORM &&
  2562. gf->nodes[f]->op != GGML_OP_RMS_NORM) {
  2563. break;
  2564. }
  2565. ops[f - i] = gf->nodes[f]->op;
  2566. f++;
  2567. }
  2568. f -= i;
  2569. for (; f > 1; f--) {
  2570. if (ggml_can_fuse(gf, i, ops, f)) {
  2571. break;
  2572. }
  2573. }
  2574. // add the fused tensors into the node info so we can unfuse them later
  2575. for (int k = 1; k < f; k++) {
  2576. ++i;
  2577. // the .dst() becomes the last fused tensor
  2578. node.add_fused(gf->nodes[i]);
  2579. }
  2580. }
  2581. nodes.push_back(std::move(node));
  2582. }
  2583. const auto order = ggml_hexagon_graph_optimize_reorder(nodes);
  2584. // unfuse
  2585. {
  2586. int j = 0;
  2587. for (const auto i : order) {
  2588. const auto & node = nodes[i];
  2589. gf->nodes[j++] = node.node;
  2590. for (auto * fused : node.fused) {
  2591. gf->nodes[j++] = fused;
  2592. }
  2593. }
  2594. }
  2595. }
  2596. static struct ggml_backend_i hexagon_backend_i = {
  2597. /* .get_name = */ ggml_backend_hexagon_name,
  2598. /* .free = */ ggml_backend_hexagon_free,
  2599. /* .set_tensor_async = */ NULL,
  2600. /* .get_tensor_async = */ NULL,
  2601. /* .cpy_tensor_async = */ NULL,
  2602. /* .synchronize = */ ggml_backend_hexagon_synchronize,
  2603. /* .graph_plan_create = */ NULL,
  2604. /* .graph_plan_free = */ NULL,
  2605. /* .graph_plan_update = */ NULL,
  2606. /* .graph_plan_compute = */ NULL,
  2607. /* .graph_compute = */ ggml_backend_hexagon_graph_compute,
  2608. /* .event_record = */ NULL,
  2609. /* .event_wait = */ NULL,
  2610. /* .graph_optimize = */ ggml_backend_hexagon_graph_optimize,
  2611. };
  2612. static ggml_guid_t ggml_backend_hexagon_guid() {
  2613. static ggml_guid guid = { 0x7b, 0x57, 0xdc, 0xaf, 0xde, 0x12, 0x1d, 0x49,
  2614. 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 };
  2615. return &guid;
  2616. }
  2617. bool ggml_backend_is_hexagon(ggml_backend_t backend) {
  2618. return backend && backend->iface.get_name == ggml_backend_hexagon_name;
  2619. }
  2620. // device interface
  2621. static ggml_backend_t ggml_backend_hexagon_device_init(ggml_backend_dev_t dev, const char * params) {
  2622. auto sess = static_cast<ggml_hexagon_session *>(dev->context);
  2623. return new ggml_backend{
  2624. /* .guid = */ ggml_backend_hexagon_guid(),
  2625. /* .interface = */ hexagon_backend_i,
  2626. /* .device = */ dev,
  2627. /* .context = */ sess,
  2628. };
  2629. GGML_UNUSED(params);
  2630. }
  2631. static const char * ggml_backend_hexagon_device_get_name(ggml_backend_dev_t dev) {
  2632. auto sess = static_cast<ggml_hexagon_session *>(dev->context);
  2633. return sess->name.c_str();
  2634. GGML_UNUSED(dev);
  2635. }
  2636. static const char * ggml_backend_hexagon_device_get_description(ggml_backend_dev_t dev) {
  2637. return "Hexagon";
  2638. GGML_UNUSED(dev);
  2639. }
  2640. static void ggml_backend_hexagon_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
  2641. // ~2GB per session for now
  2642. *free = 2ULL * 1024 * 1024 * 1024;
  2643. *total = *free;
  2644. GGML_UNUSED(dev);
  2645. }
  2646. static enum ggml_backend_dev_type ggml_backend_hexagon_device_get_type(ggml_backend_dev_t dev) {
  2647. return GGML_BACKEND_DEVICE_TYPE_GPU;
  2648. GGML_UNUSED(dev);
  2649. }
  2650. static void ggml_backend_hexagon_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  2651. props->name = ggml_backend_hexagon_device_get_name(dev);
  2652. props->description = ggml_backend_hexagon_device_get_description(dev);
  2653. props->type = ggml_backend_hexagon_device_get_type(dev);
  2654. ggml_backend_hexagon_device_get_memory(dev, &props->memory_free, &props->memory_total);
  2655. props->caps = {
  2656. /* .async = */ true,
  2657. /* .host_buffer = */ (bool) opt_hostbuf,
  2658. /* .buffer_from_host_ptr = */ false,
  2659. /* .events = */ false,
  2660. };
  2661. }
  2662. static ggml_backend_buffer_type_t ggml_backend_hexagon_device_get_buffer_type(ggml_backend_dev_t dev) {
  2663. auto sess = static_cast<ggml_hexagon_session *>(dev->context);
  2664. return &sess->buffer_type;
  2665. }
  2666. static ggml_backend_buffer_type_t ggml_backend_hexagon_device_get_repack_buffer_type(ggml_backend_dev_t dev) {
  2667. auto sess = static_cast<ggml_hexagon_session *>(dev->context);
  2668. return &sess->repack_buffer_type;
  2669. }
  2670. static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
  2671. auto sess = static_cast<ggml_hexagon_session *>(dev->context);
  2672. bool supp = false;
  2673. switch (op->op) {
  2674. case GGML_OP_NONE:
  2675. case GGML_OP_RESHAPE:
  2676. case GGML_OP_VIEW:
  2677. case GGML_OP_PERMUTE:
  2678. case GGML_OP_TRANSPOSE:
  2679. supp = true;
  2680. break;
  2681. case GGML_OP_MUL_MAT:
  2682. supp = ggml_hexagon_supported_mul_mat(sess, op);
  2683. break;
  2684. case GGML_OP_MUL_MAT_ID:
  2685. supp = ggml_hexagon_supported_mul_mat_id(sess, op);
  2686. break;
  2687. case GGML_OP_MUL:
  2688. case GGML_OP_ADD:
  2689. case GGML_OP_SUB:
  2690. supp = ggml_hexagon_supported_binary(sess, op);
  2691. break;
  2692. case GGML_OP_ADD_ID:
  2693. supp = ggml_hexagon_supported_add_id(sess, op);
  2694. break;
  2695. case GGML_OP_RMS_NORM:
  2696. supp = ggml_hexagon_supported_unary(sess, op);
  2697. break;
  2698. case GGML_OP_SOFT_MAX:
  2699. supp = ggml_hexagon_supported_softmax(sess, op);
  2700. break;
  2701. case GGML_OP_UNARY:
  2702. if (ggml_get_unary_op(op) == GGML_UNARY_OP_SILU) {
  2703. supp = ggml_hexagon_supported_activations(sess, op);
  2704. }
  2705. else if (ggml_get_unary_op(op) == GGML_UNARY_OP_GELU){
  2706. supp = ggml_hexagon_supported_activations(sess, op);
  2707. }
  2708. break;
  2709. case GGML_OP_GLU:
  2710. if ((ggml_get_glu_op(op) == GGML_GLU_OP_SWIGLU) /* || (ggml_get_glu_op(op) == GGML_GLU_OP_SWIGLU_OAI) */) {
  2711. supp = ggml_hexagon_supported_activations(sess, op);
  2712. }
  2713. break;
  2714. case GGML_OP_ROPE:
  2715. supp = ggml_hexagon_supported_rope(sess, op);
  2716. break;
  2717. default:
  2718. break;
  2719. }
  2720. if (opt_verbose) {
  2721. char dims[64 * GGML_MAX_SRC];
  2722. char strides[64 * GGML_MAX_SRC];
  2723. char types[16 * GGML_MAX_SRC];
  2724. char buffs[64 * GGML_MAX_SRC];
  2725. char names[64 * GGML_MAX_SRC];
  2726. hex_format_op_dims(dims, op);
  2727. hex_format_op_strides(strides, op);
  2728. hex_format_op_types(types, op);
  2729. hex_format_op_buffs(buffs, op);
  2730. hex_format_op_names(names, op);
  2731. HEX_VERBOSE("ggml-hex: %s device-supports-op %s : %s : %s : %s : %s : %s : (%d)\n", sess->name.c_str(),
  2732. ggml_op_name(op->op), names, dims, types, strides, buffs, (int) supp);
  2733. }
  2734. return supp;
  2735. GGML_UNUSED(dev);
  2736. }
  2737. static bool ggml_backend_hexagon_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  2738. if (buft->iface.get_alignment != ggml_backend_hexagon_buffer_type_get_alignment) {
  2739. return false;
  2740. }
  2741. auto s0 = static_cast<ggml_hexagon_session *>(dev->context);
  2742. auto s1 = static_cast<ggml_backend_hexagon_buffer_type_context *>(buft->context)->sess;
  2743. // Need session/domain-id for buffers to be compatible
  2744. bool supp = (s0->session_id == s1->session_id);
  2745. HEX_VERBOSE("ggml-hex: %s device-supports-buft %s (%d)\n", s0->name.c_str(), s1->name.c_str(), (int) supp);
  2746. return supp;
  2747. }
  2748. static ggml_backend_buffer_type_t * ggml_backend_hexagon_device_get_extra_buffers_type(ggml_backend_dev_t dev) {
  2749. auto s0 = static_cast<ggml_hexagon_session *>(dev->context);
  2750. HEX_VERBOSE("ggml-hex: device-get-extra-buft : %s \n", s0->name.c_str());
  2751. static ggml_backend_buffer_type_t bufts[2];
  2752. bufts[0] = ggml_backend_hexagon_device_get_repack_buffer_type(dev);
  2753. bufts[1] = NULL;
  2754. return bufts;
  2755. }
  2756. static const struct ggml_backend_device_i ggml_backend_hexagon_device_i = {
  2757. /* .get_name = */ ggml_backend_hexagon_device_get_name,
  2758. /* .get_description = */ ggml_backend_hexagon_device_get_description,
  2759. /* .get_memory = */ ggml_backend_hexagon_device_get_memory,
  2760. /* .get_type = */ ggml_backend_hexagon_device_get_type,
  2761. /* .get_props = */ ggml_backend_hexagon_device_get_props,
  2762. /* .init_backend = */ ggml_backend_hexagon_device_init,
  2763. /* .get_buffer_type = */ ggml_backend_hexagon_device_get_buffer_type,
  2764. /* .get_host_buffer_type = */ NULL, // ggml_backend_hexagon_device_get_host_buffer_type,
  2765. /* .buffer_from_host_ptr = */ NULL, // ggml_backend_hexagon_device_buffer_from_ptr,
  2766. /* .supports_op = */ ggml_backend_hexagon_device_supports_op,
  2767. /* .supports_buft = */ ggml_backend_hexagon_device_supports_buft,
  2768. /* .offload_op = */ NULL, // ggml_backend_hexagon_device_offload_op,
  2769. /* .event_new = */ NULL,
  2770. /* .event_free = */ NULL,
  2771. /* .event_synchronize = */ NULL,
  2772. };
  2773. //** backend registry
  2774. #define GGML_HEXAGON_MAX_SESSIONS 16
  2775. struct ggml_hexagon_registry {
  2776. ggml_hexagon_registry(ggml_backend_reg_t reg);
  2777. ~ggml_hexagon_registry();
  2778. ggml_backend_device devices[GGML_HEXAGON_MAX_SESSIONS];
  2779. };
  2780. ggml_hexagon_registry::ggml_hexagon_registry(ggml_backend_reg_t reg) {
  2781. GGML_LOG_INFO("ggml-hex: Hexagon backend (experimental) : allocating new registry : ndev %zu\n", opt_ndev);
  2782. if (!opt_arch) {
  2783. int err = get_hex_arch_ver(CDSP_DOMAIN_ID, &opt_arch);
  2784. if (err != 0) {
  2785. GGML_LOG_ERROR("ggml-hex: failed to query HTP version (err %d) defaulting to v73\n", err);
  2786. opt_arch = 73;
  2787. }
  2788. }
  2789. if(opt_arch < 75) {
  2790. opt_ndev = 1;
  2791. GGML_LOG_WARN("ggml-hex: forcing ndev to 1 for SoCs archs lower than v75.\n");
  2792. }
  2793. GGML_LOG_INFO("ggml-hex: Hexagon Arch version v%d\n", opt_arch);
  2794. // Create devices / sessions
  2795. for (size_t i = 0; i < opt_ndev; i++) {
  2796. devices[i].iface = ggml_backend_hexagon_device_i;
  2797. devices[i].reg = reg;
  2798. try {
  2799. devices[i].context = new ggml_hexagon_session(i, &devices[i]);
  2800. } catch (std::exception const &exc) {
  2801. GGML_LOG_ERROR("ggml-hex: failed to create device/session %zu\n", i);
  2802. devices[i].context = nullptr;
  2803. }
  2804. }
  2805. }
  2806. ggml_hexagon_registry::~ggml_hexagon_registry() {
  2807. GGML_LOG_INFO("ggml-hex: releasing registry\n");
  2808. // Release devices / sessions
  2809. for (size_t i = 0; i < opt_ndev; i++) {
  2810. auto sess = static_cast<ggml_hexagon_session *>(devices[i].context);
  2811. delete sess;
  2812. }
  2813. }
  2814. static const char * ggml_backend_hexagon_reg_get_name(ggml_backend_reg_t reg) {
  2815. return "HTP";
  2816. GGML_UNUSED(reg);
  2817. }
  2818. static size_t ggml_backend_hexagon_reg_get_device_count(ggml_backend_reg_t reg) {
  2819. return opt_ndev;
  2820. GGML_UNUSED(reg);
  2821. }
  2822. static ggml_backend_dev_t ggml_backend_hexagon_reg_get_device(ggml_backend_reg_t reg, size_t index) {
  2823. auto hreg = static_cast<ggml_hexagon_registry *>(reg->context);
  2824. if (index >= opt_ndev || !hreg->devices[index].context) {
  2825. return nullptr;
  2826. }
  2827. return &hreg->devices[index];
  2828. }
  2829. static void * ggml_backend_hexagon_get_proc_address(ggml_backend_reg_t reg, const char * name) {
  2830. if (strcmp(name, "ggml_backend_dev_get_extra_bufts") == 0) {
  2831. ggml_backend_dev_get_extra_bufts_t fct = ggml_backend_hexagon_device_get_extra_buffers_type;
  2832. return (void *) fct;
  2833. }
  2834. return NULL;
  2835. }
  2836. static void ggml_hexagon_init(ggml_backend_reg * reg) {
  2837. // Basic sanity checks to make sure definitions match
  2838. static_assert((unsigned int) HTP_TYPE_Q4_0 == (unsigned int) GGML_TYPE_Q4_0,
  2839. "please update hexagon_type to match ggml_type");
  2840. static_assert((unsigned int) HTP_TYPE_Q8_0 == (unsigned int) GGML_TYPE_Q8_0,
  2841. "please update hexagon_type to match ggml_type");
  2842. static_assert((unsigned int) HTP_TYPE_MXFP4 == (unsigned int) GGML_TYPE_MXFP4,
  2843. "please update hexagon_type to match ggml_type");
  2844. const char * str_verbose = getenv("GGML_HEXAGON_VERBOSE");
  2845. const char * str_hostbuf = getenv("GGML_HEXAGON_HOSTBUF");
  2846. opt_verbose = str_verbose ? atoi(str_verbose) : 0;
  2847. opt_profile = getenv("GGML_HEXAGON_PROFILE") != nullptr;
  2848. opt_etm = getenv("GGML_HEXAGON_ETM") != nullptr;
  2849. opt_experimental = getenv("GGML_HEXAGON_EXPERIMENTAL") != nullptr;
  2850. const char * str_opmask = getenv("GGML_HEXAGON_OPMASK");
  2851. if (str_opmask != nullptr) {
  2852. opt_opmask = strtoul(str_opmask, NULL, 0);
  2853. }
  2854. opt_opsync = getenv("GGML_HEXAGON_OPSYNC") != nullptr;
  2855. const char * str_ndev = getenv("GGML_HEXAGON_NDEV");
  2856. if (str_ndev) {
  2857. opt_ndev = strtoul(str_ndev, NULL, 0);
  2858. if (opt_ndev > GGML_HEXAGON_MAX_SESSIONS) {
  2859. opt_ndev = GGML_HEXAGON_MAX_SESSIONS;
  2860. }
  2861. }
  2862. const char * str_nhvx = getenv("GGML_HEXAGON_NHVX");
  2863. if (str_nhvx) {
  2864. opt_nhvx = strtoul(str_nhvx, NULL, 0);
  2865. }
  2866. const char * str_arch = getenv("GGML_HEXAGON_ARCH");
  2867. if (str_arch) {
  2868. if (str_arch[0] == 'v') {
  2869. str_arch++;
  2870. }
  2871. opt_arch = strtoul(str_arch, NULL, 0);
  2872. }
  2873. opt_hostbuf = str_hostbuf ? atoi(str_hostbuf) : 1;
  2874. reg->context = new ggml_hexagon_registry(reg);
  2875. HEX_VERBOSE("ggml-hex: size-of-general-req %zu size-of-general-rsp %zu\n", sizeof(struct htp_general_req),
  2876. sizeof(struct htp_general_rsp));
  2877. }
  2878. static const struct ggml_backend_reg_i ggml_backend_hexagon_reg_i = {
  2879. /* .get_name = */ ggml_backend_hexagon_reg_get_name,
  2880. /* .get_device_count = */ ggml_backend_hexagon_reg_get_device_count,
  2881. /* .get_device = */ ggml_backend_hexagon_reg_get_device,
  2882. /* .get_proc_address = */ ggml_backend_hexagon_get_proc_address,
  2883. };
  2884. ggml_backend_reg_t ggml_backend_hexagon_reg(void) {
  2885. static bool initialized = false;
  2886. static ggml_backend_reg reg = { /* .api_version = */ GGML_BACKEND_API_VERSION,
  2887. /* .iface = */ ggml_backend_hexagon_reg_i,
  2888. /* .context = */ NULL };
  2889. {
  2890. static std::mutex mutex;
  2891. std::lock_guard<std::mutex> lock(mutex);
  2892. if (!initialized) {
  2893. ggml_hexagon_init(&reg);
  2894. }
  2895. initialized = true;
  2896. }
  2897. return &reg;
  2898. }
  2899. GGML_BACKEND_DL_IMPL(ggml_backend_hexagon_reg)