ggml-cann.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  1. /*
  2. * Copyright (c) 2023-2024 The ggml authors
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to
  6. * deal in the Software without restriction, including without limitation the
  7. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. * sell copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. * IN THE SOFTWARE.
  21. */
  22. #include "ggml-cann.h"
  23. #include <acl/acl.h>
  24. #include <stdarg.h>
  25. #include <cmath>
  26. #include <cstdio>
  27. #include <cstring>
  28. #include <mutex>
  29. #include "ggml-impl.h"
  30. #include "ggml-backend-impl.h"
  31. #include "ggml-cann/aclnn_ops.h"
  32. #include "ggml-cann/common.h"
  33. #define GGML_COMMON_DECL_C
  34. #include "ggml-common.h"
  35. /**
  36. * @brief Default logging callback for GGML.
  37. *
  38. * This function is the default logging callback that logs messages to stderr.
  39. *
  40. * @param level The log level.
  41. * @param msg The log message.
  42. * @param user_data User data passed to the callback.
  43. */
  44. static void ggml_cann_default_log_callback(enum ggml_log_level level,
  45. const char* msg, void* user_data) {
  46. GGML_UNUSED(level);
  47. GGML_UNUSED(user_data);
  48. fprintf(stderr, "%s", msg);
  49. }
  50. ggml_log_callback ggml_cann_log_callback = ggml_cann_default_log_callback;
  51. void* ggml_cann_log_user_data = NULL;
  52. GGML_API void ggml_backend_cann_log_set_callback(ggml_log_callback log_callback,
  53. void* user_data) {
  54. ggml_cann_log_callback = log_callback;
  55. ggml_cann_log_user_data = user_data;
  56. }
  57. #define GGML_CANN_LOG_INFO(...) ggml_cann_log(GGML_LOG_LEVEL_INFO, __VA_ARGS__)
  58. #define GGML_CANN_LOG_WARN(...) ggml_cann_log(GGML_LOG_LEVEL_WARN, __VA_ARGS__)
  59. #define GGML_CANN_LOG_ERROR(...) \
  60. ggml_cann_log(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  61. GGML_ATTRIBUTE_FORMAT(2, 3)
  62. /**
  63. * @brief Log a message using the current logging callback.
  64. *
  65. * This function formats a log message and passes it to the current logging
  66. * callback.
  67. *
  68. * @param level The log level.
  69. * @param format The format string for the log message.
  70. * @param ... The arguments for the format string.
  71. */
  72. static void ggml_cann_log(enum ggml_log_level level, const char* format, ...) {
  73. if (ggml_cann_log_callback != NULL) {
  74. va_list args;
  75. va_start(args, format);
  76. char buffer[128];
  77. int len = vsnprintf(buffer, 128, format, args);
  78. if (len < 128) {
  79. ggml_cann_log_callback(level, buffer, ggml_cann_log_user_data);
  80. } else {
  81. // vsnprintf adds a null terminator
  82. std::vector<char> buffer2(len + 1);
  83. va_end(args);
  84. va_start(args, format);
  85. vsnprintf(&buffer2[0], buffer2.size(), format, args);
  86. ggml_cann_log_callback(level, buffer2.data(),
  87. ggml_cann_log_user_data);
  88. }
  89. va_end(args);
  90. }
  91. }
  92. /**
  93. * @brief Handles CANN errors by printing an error message and aborting.
  94. *
  95. * @param stmt The statement that caused the error.
  96. * @param func The function in which the error occurred.
  97. * @param file The file in which the error occurred.
  98. * @param line The line number where the error occurred.
  99. * @param msg The error message.
  100. */
  101. [[noreturn]] void ggml_cann_error(const char* stmt, const char* func,
  102. const char* file, int line, const char* msg) {
  103. int32_t id = -1;
  104. aclrtGetDevice(&id);
  105. GGML_CANN_LOG_ERROR("CANN error: %s\n", msg);
  106. GGML_CANN_LOG_ERROR(" current device: %d, in function %s at %s:%d\n", id, func,
  107. file, line);
  108. GGML_CANN_LOG_ERROR(" %s\n", stmt);
  109. // abort with GGML_ASSERT to get a stack trace
  110. GGML_ABORT("CANN error");
  111. }
  112. /**
  113. * @brief Sets the device to be used by CANN.
  114. *
  115. * @param device The device ID to set.
  116. */
  117. void ggml_cann_set_device(const int32_t device) {
  118. // TODO: uncomment these lines after empty context has fixed.
  119. // int current_device;
  120. // ACL_CHECK(aclrtGetDevice(&current_device));
  121. // if (device == current_device) {
  122. // return;
  123. // }
  124. ACL_CHECK(aclrtSetDevice(device));
  125. }
  126. /**
  127. * @brief Retrieves the current device ID.
  128. *
  129. * @return The current device ID.
  130. */
  131. int32_t ggml_cann_get_device() {
  132. int32_t id;
  133. ACL_CHECK(aclrtGetDevice(&id));
  134. return id;
  135. }
  136. /**
  137. * @brief Initialize the CANN device information.
  138. *
  139. * This function initializes the CANN device information by obtaining the
  140. * device count and setting the memory allocation granularity for each device.
  141. *
  142. * @return A structure containing the device information.
  143. */
  144. static ggml_cann_device_info ggml_cann_init() {
  145. ggml_cann_device_info info = {};
  146. aclError err = aclrtGetDeviceCount((uint32_t*)&info.device_count);
  147. if (err != ACL_SUCCESS) {
  148. GGML_CANN_LOG_ERROR("%s: failed to initialize CANN: %s\n",
  149. __func__, aclGetRecentErrMsg());
  150. return info;
  151. }
  152. GGML_ASSERT(info.device_count <= GGML_CANN_MAX_DEVICES);
  153. for (int id = 0; id < info.device_count; ++id) {
  154. aclrtPhysicalMemProp prop = {};
  155. prop.handleType = ACL_MEM_HANDLE_TYPE_NONE;
  156. prop.allocationType = ACL_MEM_ALLOCATION_TYPE_PINNED;
  157. prop.memAttr = ACL_HBM_MEM_HUGE;
  158. prop.location.type = ACL_MEM_LOCATION_TYPE_DEVICE;
  159. prop.location.id = id;
  160. prop.reserve = 0;
  161. ACL_CHECK(aclrtMemGetAllocationGranularity(
  162. &prop, ACL_RT_MEM_ALLOC_GRANULARITY_RECOMMENDED,
  163. &info.devices[id].vmm_granularity));
  164. }
  165. // TODO: add more device info later.
  166. return info;
  167. }
  168. /**
  169. * @brief Retrieve the CANN device information.
  170. *
  171. * This function returns a reference to a structure containing the CANN device
  172. * information. The device information is initialized once and reused on
  173. * subsequent calls.
  174. *
  175. * @return A reference to the structure containing the device information.
  176. */
  177. const ggml_cann_device_info& ggml_cann_info() {
  178. static ggml_cann_device_info info = ggml_cann_init();
  179. return info;
  180. }
  181. //#define DEBUG_CANN_MALLOC
  182. /**
  183. * @brief A pool of CANN buffers(legacy).
  184. *
  185. * This class manages a pool of CANN buffers for a specific device.
  186. */
  187. struct ggml_cann_pool_leg : public ggml_cann_pool {
  188. /**
  189. * @brief The maximum number of buffers in the pool.
  190. */
  191. static const int MAX_BUFFERS = 256;
  192. /**
  193. * @brief The device ID associated with this buffer pool.
  194. */
  195. int device;
  196. /**
  197. * @brief Structure representing a CANN buffer.
  198. */
  199. struct ggml_cann_buffer {
  200. void* ptr = nullptr; ///< Pointer to the buffer memory.
  201. size_t size = 0; ///< Size of the buffer.
  202. };
  203. /**
  204. * @brief Array of CANN buffers in the pool.
  205. */
  206. ggml_cann_buffer buffer_pool[MAX_BUFFERS] = {};
  207. /**
  208. * @brief Total size of all buffers in the pool.
  209. */
  210. size_t pool_size = 0;
  211. /**
  212. * @brief Constructor to initialize the buffer pool for a specific device.
  213. *
  214. * @param device The device ID to associate with this buffer pool.
  215. */
  216. explicit ggml_cann_pool_leg(int device) : device(device) {}
  217. /**
  218. * @brief Destructor to free all buffers in the pool.
  219. */
  220. ~ggml_cann_pool_leg() {
  221. ggml_cann_set_device(device);
  222. for (int i = 0; i < MAX_BUFFERS; ++i) {
  223. ggml_cann_buffer& b = buffer_pool[i];
  224. if (b.ptr != nullptr) {
  225. ACL_CHECK(aclrtFree(b.ptr));
  226. pool_size -= b.size;
  227. }
  228. }
  229. GGML_ASSERT(pool_size == 0);
  230. }
  231. /**
  232. * @brief Allocate a buffer of the given size.
  233. *
  234. * @param size The size of the buffer to allocate.
  235. * @param actual_size A pointer to a variable to receive the actual size of
  236. * the allocated buffer.
  237. * @return A pointer to the allocated buffer.
  238. */
  239. void* alloc(size_t size, size_t* actual_size) override {
  240. #ifdef DEBUG_CANN_MALLOC
  241. int nnz = 0;
  242. size_t max_size = 0;
  243. #endif
  244. size_t best_diff = 1ull << 36;
  245. int ibest = -1;
  246. for (int i = 0; i < MAX_BUFFERS; ++i) {
  247. ggml_cann_buffer& b = buffer_pool[i];
  248. if (b.ptr != nullptr) {
  249. #ifdef DEBUG_CANN_MALLOC
  250. ++nnz;
  251. if (b.size > max_size) max_size = b.size;
  252. #endif
  253. if (b.size >= size) {
  254. size_t diff = b.size - size;
  255. if (diff < best_diff) {
  256. best_diff = diff;
  257. ibest = i;
  258. if (!best_diff) {
  259. void* ptr = b.ptr;
  260. *actual_size = b.size;
  261. b.ptr = nullptr;
  262. b.size = 0;
  263. return ptr;
  264. }
  265. }
  266. }
  267. }
  268. }
  269. if (ibest >= 0) {
  270. ggml_cann_buffer& b = buffer_pool[ibest];
  271. void* ptr = b.ptr;
  272. *actual_size = b.size;
  273. b.ptr = nullptr;
  274. b.size = 0;
  275. return ptr;
  276. }
  277. void* ptr;
  278. size_t look_ahead_size = (size_t)(1.05 * size);
  279. look_ahead_size = 256 * ((look_ahead_size + 255) / 256);
  280. ggml_cann_set_device(device);
  281. ACL_CHECK(
  282. aclrtMalloc(&ptr, look_ahead_size, ACL_MEM_MALLOC_HUGE_FIRST));
  283. *actual_size = look_ahead_size;
  284. pool_size += look_ahead_size;
  285. #ifdef DEBUG_CANN_MALLOC
  286. GGML_CANN_LOG_INFO(
  287. "%s[%d]: %d buffers, max_size = %u MB, pool_size = %u MB, "
  288. "requested %u MB\n",
  289. __func__, device, nnz, (uint32_t)(max_size / 1024 / 1024),
  290. (uint32_t)(pool_size / 1024 / 1024),
  291. (uint32_t)(size / 1024 / 1024));
  292. #endif
  293. return ptr;
  294. }
  295. /**
  296. * @brief Free a buffer and return it to the pool.
  297. *
  298. * @param ptr Pointer to the buffer to free.
  299. * @param size Size of the buffer to free.
  300. */
  301. void free(void* ptr, size_t size) override {
  302. for (int i = 0; i < MAX_BUFFERS; ++i) {
  303. ggml_cann_buffer& b = buffer_pool[i];
  304. if (b.ptr == nullptr) {
  305. b.ptr = ptr;
  306. b.size = size;
  307. return;
  308. }
  309. }
  310. // memory should always buffered. these memory may still needed by
  311. // tasks in stream.
  312. // TODO, fix me.
  313. GGML_ABORT("Cann buffer pool full, increase MAX_CANN_BUFFERS\n");
  314. }
  315. };
  316. /**
  317. * @brief A pool of CANN buffers with virtual memory.
  318. *
  319. * This class manages a pool of CANN buffers with virtual memory for a specific
  320. * device.
  321. */
  322. struct ggml_cann_pool_vmm : public ggml_cann_pool {
  323. /**
  324. * @brief The maximum size of the virtual memory pool (32 GB).
  325. */
  326. static const size_t CANN_POOL_VMM_MAX_SIZE = 1ull << 35; // 32 GB
  327. /**
  328. * @brief The device ID associated with this buffer pool.
  329. */
  330. int device;
  331. /**
  332. * @brief Pointer to the start of the virtual memory pool.
  333. */
  334. void* pool_addr = 0;
  335. /**
  336. * @brief Amount of virtual memory used in the pool.
  337. */
  338. size_t pool_used = 0;
  339. /**
  340. * @brief Total size of the virtual memory pool.
  341. */
  342. size_t pool_size = 0;
  343. /**
  344. * @brief Allocation granularity for the virtual memory pool.
  345. */
  346. size_t granularity;
  347. /**
  348. * @brief Handles for the physical memory allocated.
  349. */
  350. std::vector<aclrtDrvMemHandle> handles;
  351. /**
  352. * @brief Offsets for the mapped memory regions.
  353. */
  354. std::vector<void*> map_offsets;
  355. /**
  356. * @brief Constructor to initialize the buffer pool with virtual memory for
  357. * a specific device.
  358. *
  359. * @param device The device ID to associate with this buffer pool.
  360. */
  361. explicit ggml_cann_pool_vmm(int device)
  362. : device(device),
  363. granularity(ggml_cann_info().devices[device].vmm_granularity) {}
  364. /**
  365. * @brief Destructor to free all buffers in the virtual memory pool.
  366. */
  367. ~ggml_cann_pool_vmm() {
  368. if (pool_addr != 0) {
  369. for (auto& offset : map_offsets) {
  370. ACL_CHECK(aclrtUnmapMem(offset));
  371. }
  372. for (auto& handle : handles) {
  373. ACL_CHECK(aclrtFreePhysical(handle));
  374. }
  375. ACL_CHECK(aclrtReleaseMemAddress(pool_addr));
  376. }
  377. }
  378. /**
  379. * @brief Allocate a buffer of the given size in the virtual memory pool.
  380. *
  381. * @param size The size of the buffer to allocate.
  382. * @param actual_size A pointer to a variable to receive the actual size of
  383. * the allocated buffer.
  384. * @return A pointer to the allocated buffer.
  385. */
  386. void* alloc(size_t size, size_t* actual_size) override {
  387. // round up the allocation size to the alignment to ensure that all
  388. // allocations are aligned for all data types
  389. const size_t alignment = 128;
  390. size = alignment * ((size + alignment - 1) / alignment);
  391. size_t avail = pool_size - pool_used;
  392. if (size > avail) {
  393. // round up to the next multiple of the granularity
  394. size_t reserve_size = size - avail;
  395. reserve_size =
  396. granularity * ((reserve_size + granularity - 1) / granularity);
  397. GGML_ASSERT(pool_size + reserve_size <= CANN_POOL_VMM_MAX_SIZE);
  398. // allocate more physical memory
  399. aclrtPhysicalMemProp prop = {};
  400. prop.handleType = ACL_MEM_HANDLE_TYPE_NONE;
  401. prop.allocationType = ACL_MEM_ALLOCATION_TYPE_PINNED;
  402. prop.memAttr = ACL_HBM_MEM_HUGE;
  403. prop.location.type = ACL_MEM_LOCATION_TYPE_DEVICE;
  404. prop.location.id = device;
  405. prop.reserve = 0;
  406. aclrtDrvMemHandle handle;
  407. ACL_CHECK(aclrtMallocPhysical(&handle, reserve_size, &prop, 0));
  408. // reserve virtual address space (if not already reserved)
  409. if (pool_addr == 0) {
  410. ACL_CHECK(aclrtReserveMemAddress(
  411. &pool_addr, CANN_POOL_VMM_MAX_SIZE, 0, NULL, 1));
  412. }
  413. // map at the end of the pool
  414. ACL_CHECK(aclrtMapMem((char*)pool_addr + pool_size, reserve_size, 0,
  415. handle, 0));
  416. handles.push_back(handle);
  417. map_offsets.push_back((char*)pool_addr + pool_size);
  418. // add to the pool
  419. pool_size += reserve_size;
  420. // GGML_CANN_LOG_INFO("cann pool[%d]: size increased to %llu MB (
  421. // reserved %llu MB)\n",
  422. // device, (unsigned long long) (pool_size/1024/1024),
  423. // (unsigned long long) (reserve_size/1024/1024));
  424. }
  425. GGML_ASSERT(pool_addr != 0);
  426. void* ptr = (void*)((char*)pool_addr + pool_used);
  427. *actual_size = size;
  428. pool_used += size;
  429. #ifdef DEBUG_CANN_MALLOC
  430. GGML_CANN_LOG_INFO("cann pool[%d]: allocated %llu bytes at %llx\n", device,
  431. (unsigned long long)size, (unsigned long long)ptr);
  432. #endif
  433. return ptr;
  434. }
  435. /**
  436. * @brief Free a buffer and return it to the virtual memory pool.
  437. *
  438. * @param ptr Pointer to the buffer to free.
  439. * @param size Size of the buffer to free.
  440. */
  441. void free(void* ptr, size_t size) override {
  442. #ifdef DEBUG_CANN_MALLOC
  443. GGML_CANN_LOG_INFO("cann pool[%d]: freed %llu bytes at %llx\n", device,
  444. (unsigned long long)size, (unsigned long long)ptr);
  445. #endif
  446. pool_used -= size;
  447. // all deallocations must be in reverse order of the allocations
  448. GGML_ASSERT(ptr == (void*)((char*)pool_addr + pool_used));
  449. }
  450. };
  451. /**
  452. * @brief Create a new CANN pool for a specific device.
  453. *
  454. * Factory method to create a new CANN pool object based on the device type.
  455. *
  456. * @param device The device ID for which to create the pool.
  457. * @return A unique pointer to the created CANN pool.
  458. */
  459. std::unique_ptr<ggml_cann_pool> ggml_backend_cann_context::new_pool_for_device(
  460. int device) {
  461. // return std::unique_ptr<ggml_cann_pool>(new ggml_cann_pool_leg(device));
  462. return std::unique_ptr<ggml_cann_pool>(new ggml_cann_pool_vmm(device));
  463. }
  464. // cann buffer
  465. /**
  466. * @brief Context for managing a CANN buffer associated with a specific device.
  467. *
  468. * This structure holds information about a CANN buffer, including the device
  469. * ID, device pointer, and a name derived from GGML_CANN_NAME and the device ID.
  470. */
  471. struct ggml_backend_cann_buffer_context {
  472. int32_t device; ///< The device ID associated with this buffer context.
  473. void* dev_ptr =
  474. nullptr; ///< Pointer to the device memory allocated for the buffer.
  475. /**
  476. * @brief Constructor to initialize the CANN buffer context.
  477. *
  478. * @param device The device ID associated with this buffer context.
  479. * @param dev_ptr Pointer to the device memory allocated for the buffer.
  480. */
  481. ggml_backend_cann_buffer_context(int32_t device, void* dev_ptr)
  482. : device(device),
  483. dev_ptr(dev_ptr) {}
  484. /**
  485. * @brief Destructor to free the device memory allocated for the buffer.
  486. */
  487. ~ggml_backend_cann_buffer_context() { ACL_CHECK(aclrtFree(dev_ptr)); }
  488. };
  489. /**
  490. * @brief Retrieve the name associated with a CANN buffer.
  491. *
  492. * This function returns the name of a CANN buffer, which is stored in the
  493. * context of the buffer.
  494. *
  495. * @param buffer The CANN buffer whose name is to be retrieved.
  496. * @return A pointer to a C-string containing the name of the buffer.
  497. */
  498. GGML_CALL static const char* ggml_backend_cann_buffer_get_name(
  499. ggml_backend_buffer_t buffer) {
  500. return "CANN";
  501. GGML_UNUSED(buffer);
  502. }
  503. /**
  504. * @brief Check if a buffer is a CANN buffer.
  505. *
  506. * This function checks if a given buffer is a CANN buffer by comparing its
  507. * `get_name` function pointer to `ggml_backend_cann_buffer_get_name`.
  508. *
  509. * @param buffer The buffer to check.
  510. * @return true if the buffer is a CANN buffer, false otherwise.
  511. */
  512. GGML_CALL static bool ggml_backend_buffer_is_cann(
  513. ggml_backend_buffer_t buffer) {
  514. return buffer->iface.get_name == ggml_backend_cann_buffer_get_name;
  515. }
  516. /**
  517. * @brief Free resources associated with a CANN buffer.
  518. *
  519. * This function frees the resources associated with a CANN buffer, including
  520. * its context.
  521. *
  522. * @param buffer The CANN buffer to free.
  523. */
  524. GGML_CALL static void ggml_backend_cann_buffer_free_buffer(
  525. ggml_backend_buffer_t buffer) {
  526. ggml_backend_cann_buffer_context* ctx =
  527. (ggml_backend_cann_buffer_context*)buffer->context;
  528. delete ctx;
  529. }
  530. /**
  531. * @brief Retrieve the base pointer of a CANN buffer.
  532. *
  533. * This function returns the base pointer of a CANN buffer, which points to the
  534. * device memory allocated for the buffer.
  535. *
  536. * @param buffer The CANN buffer whose base pointer is to be retrieved.
  537. * @return A pointer to the base of the device memory allocated for the buffer.
  538. */
  539. GGML_CALL static void* ggml_backend_cann_buffer_get_base(
  540. ggml_backend_buffer_t buffer) {
  541. ggml_backend_cann_buffer_context* ctx =
  542. (ggml_backend_cann_buffer_context*)buffer->context;
  543. return ctx->dev_ptr;
  544. }
  545. /**
  546. * @brief Transform quantized Q4.0 tensor data into a format suitable for CANN
  547. * processing.
  548. *
  549. * This function transforms quantized Q4.0 tensor data into a format suitable
  550. * for CANN processing. It extracts quantization values and scales from the
  551. * source data and prepares them in a format expected by CANN operations.
  552. *
  553. * @param tensor Pointer to the tensor information.
  554. * @param src Pointer to the source data in Q4.0 format.
  555. * @param dst Pointer to the destination buffer where transformed data will be
  556. * stored.
  557. */
  558. GGML_CALL static void ggml_backend_cann_transform_q4_0(ggml_tensor* tensor,
  559. const void* src,
  560. void* dst) {
  561. int64_t n_elems = ggml_nelements(tensor);
  562. int64_t groups = n_elems / QK4_0;
  563. size_t quant_bytes = n_elems * sizeof(uint8_t) / 2;
  564. uint8_t* quant_offset = (uint8_t*)dst;
  565. uint16_t* scale_offset = (uint16_t*)((char*)dst + quant_bytes);
  566. for (int i = 0; i < groups; i++) {
  567. const block_q4_0* group =
  568. (const block_q4_0*)((const char*)src + i * sizeof(block_q4_0));
  569. *scale_offset = group->d;
  570. scale_offset++;
  571. // 0-15
  572. for (int j = 0; j < QK4_0 / 2; j += 2) {
  573. (*quant_offset) = (group->qs[j] & 0x0F);
  574. (*quant_offset) |= ((group->qs[j + 1] << 4));
  575. quant_offset++;
  576. }
  577. // 16-31
  578. for (int j = 0; j < QK4_0 / 2; j += 2) {
  579. (*quant_offset) = (group->qs[j] >> 4);
  580. (*quant_offset) |= (group->qs[j + 1] & 0xF0);
  581. quant_offset++;
  582. }
  583. }
  584. // put (uint4b_t -8) into int4b_t
  585. for (quant_offset = (uint8_t*)dst;
  586. quant_offset < (uint8_t*)dst + quant_bytes; quant_offset++) {
  587. (*quant_offset) ^= 0x88;
  588. }
  589. }
  590. /**
  591. * @brief Transform CANN processed data back into quantized Q4.0 format.
  592. *
  593. * This function transforms CANN processed data back into quantized Q4.0 format.
  594. * It reverses the transformation performed by
  595. * ggml_backend_cann_transform_q4_0(), converting the data back into its
  596. * original quantized form.
  597. *
  598. * @param tensor Pointer to the tensor information.
  599. * @param src Pointer to the source buffer containing transformed data.
  600. * @param dst Pointer to the destination buffer where the Q4.0 formatted data
  601. * will be stored.
  602. */
  603. GGML_CALL static void ggml_backend_cann_transform_back_q4_0(
  604. const ggml_tensor* tensor, void* src, void* dst) {
  605. int64_t n_elems = ggml_nelements(tensor);
  606. int64_t groups = n_elems / QK4_0;
  607. size_t quant_bytes = n_elems * sizeof(uint8_t) / 2;
  608. uint8_t* quant_offset = (uint8_t*)src;
  609. uint16_t* scale_offset = (uint16_t*)((char*)src + quant_bytes);
  610. for (; quant_offset < (uint8_t*)src + quant_bytes; quant_offset++) {
  611. (*quant_offset) ^= 0x88;
  612. }
  613. quant_offset = (uint8_t*)src;
  614. for (int i = 0; i < groups; i++) {
  615. block_q4_0* group = (block_q4_0*)((char*)dst + i * sizeof(block_q4_0));
  616. group->d = *scale_offset;
  617. scale_offset++;
  618. // 0-15
  619. for (int j = 0; j < QK4_0 / 2; j += 2) {
  620. group->qs[j] = ((*quant_offset) & 0x0F);
  621. group->qs[j + 1] = ((*quant_offset) >> 4);
  622. quant_offset++;
  623. }
  624. // 16-31
  625. for (int j = 0; j < QK4_0 / 2; j += 2) {
  626. group->qs[j] |= ((*quant_offset) << 4);
  627. group->qs[j + 1] |= ((*quant_offset) & 0xF0);
  628. quant_offset++;
  629. }
  630. }
  631. }
  632. /**
  633. * @brief Transform quantized Q8.0 tensor data into a format suitable for CANN
  634. * processing.
  635. *
  636. * This function transforms quantized Q8.0 tensor data into a format suitable
  637. * for CANN processing. It extracts quantization values and scales from the
  638. * source data and prepares them in a format expected by CANN operations.
  639. *
  640. * @param tensor Pointer to the tensor information.
  641. * @param src Pointer to the source data in Q8.0 format.
  642. * @param dst Pointer to the destination buffer where transformed data will be
  643. * stored.
  644. */
  645. GGML_CALL static void ggml_backend_cann_transform_q8_0(ggml_tensor* tensor,
  646. const void* src,
  647. void* dst) {
  648. int64_t n_elems = ggml_nelements(tensor);
  649. int64_t groups = n_elems / QK8_0;
  650. size_t quant_bytes = n_elems * sizeof(uint8_t);
  651. uint8_t* quant_offset = (uint8_t*)dst;
  652. uint16_t* scale_offset = (uint16_t*)((char*)dst + quant_bytes);
  653. for (int i = 0; i < groups; i++) {
  654. const block_q8_0* group =
  655. (const block_q8_0*)((const char*)src + i * sizeof(block_q8_0));
  656. *scale_offset = group->d;
  657. scale_offset++;
  658. size_t group_quant_size = QK8_0 * sizeof(uint8_t);
  659. memcpy(quant_offset, group->qs, group_quant_size);
  660. quant_offset += group_quant_size;
  661. }
  662. }
  663. /**
  664. * @brief Transform CANN processed data back into quantized Q8.0 format.
  665. *
  666. * This function transforms CANN processed data back into quantized Q8.0 format.
  667. * It reverses the transformation performed by
  668. * ggml_backend_cann_transform_q8_0(), converting the data back into its
  669. * original quantized form.
  670. *
  671. * @param tensor Pointer to the tensor information.
  672. * @param src Pointer to the source buffer containing transformed data.
  673. * @param dst Pointer to the destination buffer where the Q8.0 formatted data
  674. * will be stored.
  675. */
  676. GGML_CALL static void ggml_backend_cann_transform_back_q8_0(
  677. const ggml_tensor* tensor, const void* src, void* dst) {
  678. int64_t n_elems = ggml_nelements(tensor);
  679. int64_t groups = n_elems / QK8_0;
  680. size_t quant_bytes = n_elems * sizeof(uint8_t);
  681. const uint8_t* quant_offset = (const uint8_t*)src;
  682. const uint16_t* scale_offset =
  683. (const uint16_t*)((const char*)src + quant_bytes);
  684. for (int i = 0; i < groups; i++) {
  685. block_q8_0* group = (block_q8_0*)((char*)dst + i * sizeof(block_q8_0));
  686. group->d = *scale_offset;
  687. scale_offset++;
  688. size_t group_quant_size = QK8_0 * sizeof(uint8_t);
  689. memcpy(group->qs, quant_offset, group_quant_size);
  690. quant_offset += group_quant_size;
  691. }
  692. }
  693. /**
  694. * @brief Transform tensor data based on its type for CANN processing.
  695. *
  696. * This function transforms tensor data based on its quantization type for CANN
  697. * processing. It dispatches the transformation based on the tensor's type to
  698. * specialized functions handling Q4.0 and Q8.0 formats.
  699. *
  700. * @param tensor Pointer to the tensor information.
  701. * @param src Pointer to the source data to be transformed.
  702. * @param dst Pointer to the destination buffer where transformed data will be
  703. * stored.
  704. */
  705. GGML_CALL static void ggml_backend_cann_transform(ggml_tensor* tensor,
  706. const void* src, void* dst) {
  707. switch (tensor->type) {
  708. case GGML_TYPE_Q4_0:
  709. ggml_backend_cann_transform_q4_0(tensor, src, dst);
  710. break;
  711. case GGML_TYPE_Q8_0:
  712. ggml_backend_cann_transform_q8_0(tensor, src, dst);
  713. break;
  714. default:
  715. break;
  716. }
  717. }
  718. /**
  719. * @brief Transform CANN processed data back into tensor data based on its type.
  720. *
  721. * This function transforms CANN processed data back into tensor data based on
  722. * its quantization type for Q4.0 and Q8.0 formats. It dispatches the
  723. * transformation based on the tensor's type to specialized functions.
  724. *
  725. * @param tensor Pointer to the tensor information.
  726. * @param src Pointer to the source data containing CANN processed data.
  727. * @param dst Pointer to the destination buffer where transformed tensor data
  728. * will be stored.
  729. */
  730. GGML_CALL static void ggml_backend_cann_transform_back(
  731. const ggml_tensor* tensor, void* src, void* dst) {
  732. switch (tensor->type) {
  733. case GGML_TYPE_Q4_0:
  734. ggml_backend_cann_transform_back_q4_0(tensor, src, dst);
  735. break;
  736. case GGML_TYPE_Q8_0:
  737. ggml_backend_cann_transform_back_q8_0(tensor, src, dst);
  738. break;
  739. default:
  740. break;
  741. }
  742. }
  743. /**
  744. * @brief Check if transformation is needed for a given tensor type.
  745. *
  746. * This function checks if transformation is needed for a given tensor type
  747. * to prepare data for CANN processing.
  748. *
  749. * @param type The tensor type to check.
  750. * @return true if transformation is needed, false otherwise.
  751. */
  752. GGML_CALL static bool need_transform(ggml_type type) {
  753. switch (type) {
  754. case GGML_TYPE_Q4_0:
  755. case GGML_TYPE_Q8_0:
  756. return true;
  757. default:
  758. return false;
  759. }
  760. }
  761. /**
  762. * @brief Initialize a tensor using data from a CANN buffer.
  763. *
  764. * This function initializes a tensor using data from a CANN buffer.
  765. * It handles special cases such as views and quantization.
  766. *
  767. * @param buffer The CANN buffer from which to initialize the tensor.
  768. * @param tensor Pointer to the tensor to be initialized.
  769. */
  770. GGML_CALL static void ggml_backend_cann_buffer_init_tensor(
  771. ggml_backend_buffer_t buffer, ggml_tensor* tensor) {
  772. if (tensor->view_src != NULL && tensor->view_offs == 0) {
  773. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  774. return;
  775. }
  776. // TODO: can backend doesn't support quantized yet. Just leave the code
  777. // here.
  778. if (ggml_is_quantized(tensor->type)) {
  779. // Initialize padding to 0 to avoid possible NaN values
  780. size_t original_size = ggml_nbytes(tensor);
  781. size_t padded_size =
  782. ggml_backend_buft_get_alloc_size(buffer->buft, tensor);
  783. if (padded_size > original_size && tensor->view_src == nullptr) {
  784. size_t memset_size = padded_size - original_size;
  785. ACL_CHECK(aclrtMemset((char*)tensor->data + original_size,
  786. memset_size, 0, memset_size));
  787. }
  788. }
  789. }
  790. // TODO: need handle tensor which has paddings.
  791. /**
  792. * @brief Set tensor data in a CANN buffer.
  793. *
  794. * This function sets tensor data in a CANN buffer, handling transformations
  795. * if needed based on the tensor's type.
  796. *
  797. * @param buffer The CANN buffer where the tensor data will be set.
  798. * @param tensor Pointer to the tensor whose data will be set.
  799. * @param data Pointer to the source data to be copied into the tensor.
  800. * @param offset Offset in the source data from where to start copying.
  801. * @param size Size of the data to be copied, in bytes.
  802. */
  803. GGML_CALL static void ggml_backend_cann_buffer_set_tensor(
  804. ggml_backend_buffer_t buffer, ggml_tensor *tensor, const void *data,
  805. size_t offset, size_t size) {
  806. ggml_backend_cann_buffer_context *ctx =
  807. (ggml_backend_cann_buffer_context *)buffer->context;
  808. ggml_cann_set_device(ctx->device);
  809. // TODO: refer to cann(#6017), it use thread's default stream.
  810. // For acl, synchronous functions use this default stream.
  811. // Why aclrtSynchronizeDevice?
  812. if (!need_transform(tensor->type)) {
  813. ACL_CHECK(aclrtMemcpy((char *)tensor->data + offset, size, data, size,
  814. ACL_MEMCPY_HOST_TO_DEVICE));
  815. } else {
  816. void *transform_buffer = malloc(size);
  817. ggml_backend_cann_transform(tensor, data, transform_buffer);
  818. #ifndef NDEBUG
  819. void *check_buffer = malloc(size);
  820. ggml_backend_cann_transform_back(tensor, transform_buffer,
  821. check_buffer);
  822. GGML_ASSERT(memcmp(data, check_buffer, size) == 0);
  823. free(check_buffer);
  824. #endif
  825. ACL_CHECK(aclrtMemcpy((char *)tensor->data + offset, size,
  826. transform_buffer, size,
  827. ACL_MEMCPY_HOST_TO_DEVICE));
  828. free(transform_buffer);
  829. }
  830. }
  831. /**
  832. * @brief Get tensor data from a CANN buffer.
  833. *
  834. * This function retrieves tensor data from a CANN buffer, handling
  835. * transformations if needed based on the tensor's type.
  836. *
  837. * @param buffer The CANN buffer from which to retrieve tensor data.
  838. * @param tensor Pointer to the tensor whose data will be retrieved.
  839. * @param data Pointer to the destination buffer where the tensor data will be
  840. * copied.
  841. * @param offset Offset in the destination buffer where to start copying.
  842. * @param size Size of the data to be copied, in bytes.
  843. */
  844. GGML_CALL static void ggml_backend_cann_buffer_get_tensor(
  845. ggml_backend_buffer_t buffer, const ggml_tensor* tensor, void* data,
  846. size_t offset, size_t size) {
  847. ggml_backend_cann_buffer_context* ctx =
  848. (ggml_backend_cann_buffer_context*)buffer->context;
  849. ggml_cann_set_device(ctx->device);
  850. if (!need_transform(tensor->type)) {
  851. ACL_CHECK(aclrtMemcpy(data, size, (char*)tensor->data + offset, size,
  852. ACL_MEMCPY_DEVICE_TO_HOST));
  853. } else {
  854. void* transform_buffer = malloc(size);
  855. ACL_CHECK(aclrtMemcpy(transform_buffer, size,
  856. (char*)tensor->data + offset, size,
  857. ACL_MEMCPY_DEVICE_TO_HOST));
  858. ggml_backend_cann_transform_back(tensor, transform_buffer, data);
  859. free(transform_buffer);
  860. }
  861. }
  862. /**
  863. * @brief Copy tensor data between CANN buffers if possible.
  864. *
  865. * This function copies tensor data between CANN buffers if the source and
  866. * destination buffers are CANN buffers and they meet the necessary conditions
  867. * (same device or devices can access each other).
  868. *
  869. * @param buffer The destination CANN buffer where the tensor data will be
  870. * copied.
  871. * @param src Pointer to the source tensor whose data will be copied.
  872. * @param dst Pointer to the destination tensor where the data will be copied.
  873. * @return true if the copy operation succeeded, false otherwise.
  874. */
  875. GGML_CALL static bool ggml_backend_cann_buffer_cpy_tensor(
  876. ggml_backend_buffer_t buffer, const ggml_tensor* src, ggml_tensor* dst) {
  877. if (ggml_backend_buffer_is_cann(src->buffer)) {
  878. ggml_backend_cann_buffer_context* src_ctx =
  879. (ggml_backend_cann_buffer_context*)src->buffer->context;
  880. ggml_backend_cann_buffer_context* dst_ctx =
  881. (ggml_backend_cann_buffer_context*)buffer->context;
  882. size_t memcpy_size = ggml_nbytes(src);
  883. // Same device.
  884. if (src_ctx->device == dst_ctx->device) {
  885. ACL_CHECK(aclrtMemcpy((char*)dst->data, memcpy_size,
  886. (const char*)src->data, memcpy_size,
  887. ACL_MEMCPY_DEVICE_TO_DEVICE));
  888. return true;
  889. } else {
  890. // Different device but can access by peer.
  891. int32_t canAccessPeer = 0;
  892. ACL_CHECK(aclrtDeviceCanAccessPeer(&canAccessPeer, src_ctx->device,
  893. dst_ctx->device));
  894. if (canAccessPeer) {
  895. ggml_cann_set_device(src_ctx->device);
  896. ACL_CHECK(aclrtDeviceEnablePeerAccess(dst_ctx->device, 0));
  897. ACL_CHECK(aclrtMemcpy((char*)dst->data, memcpy_size,
  898. (const char*)src->data, memcpy_size,
  899. ACL_MEMCPY_DEVICE_TO_DEVICE));
  900. return true;
  901. }
  902. }
  903. }
  904. return false;
  905. }
  906. /**
  907. * @brief Clear a CANN buffer by setting all its memory to a specified value.
  908. *
  909. * This function clears a CANN buffer by setting all its memory to a specified
  910. * value.
  911. *
  912. * @param buffer The CANN buffer to be cleared.
  913. * @param value The value to which each byte in the buffer will be set.
  914. */
  915. GGML_CALL static void ggml_backend_cann_buffer_clear(
  916. ggml_backend_buffer_t buffer, uint8_t value) {
  917. ggml_backend_cann_buffer_context* ctx =
  918. (ggml_backend_cann_buffer_context*)buffer->context;
  919. ggml_cann_set_device(ctx->device);
  920. ACL_CHECK(aclrtMemset(ctx->dev_ptr, buffer->size, value, buffer->size));
  921. }
  922. /**
  923. * @brief Interface for a CANN buffer in the backend.
  924. *
  925. * This structure defines function pointers to operations that can be performed
  926. * on a CANN buffer within the backend.
  927. */
  928. static ggml_backend_buffer_i ggml_backend_cann_buffer_interface = {
  929. /* .get_name = */ ggml_backend_cann_buffer_get_name,
  930. /* .free_buffer = */ ggml_backend_cann_buffer_free_buffer,
  931. /* .get_base = */ ggml_backend_cann_buffer_get_base,
  932. /* .init_tensor = */ ggml_backend_cann_buffer_init_tensor,
  933. /* .set_tensor = */ ggml_backend_cann_buffer_set_tensor,
  934. /* .get_tensor = */ ggml_backend_cann_buffer_get_tensor,
  935. /* .cpy_tensor = */ ggml_backend_cann_buffer_cpy_tensor,
  936. /* .clear = */ ggml_backend_cann_buffer_clear,
  937. /* .reset = */ NULL,
  938. };
  939. // cann buffer type
  940. /**
  941. * @brief Structure representing context information for a specific backend
  942. * buffer type.
  943. */
  944. struct ggml_backend_cann_buffer_type_context {
  945. int32_t
  946. device; /**< Device identifier associated with the buffer context. */
  947. std::string name; /**< Name associated with the buffer context. */
  948. };
  949. /**
  950. * @brief Retrieves the name associated with a CANN buffer type.
  951. *
  952. * This function returns the descriptive name associated with the specified
  953. * CANN buffer type context.
  954. *
  955. * @param buft Pointer to the buffer type context.
  956. * @return Const pointer to the C-style string containing the name.
  957. */
  958. GGML_CALL static const char* ggml_backend_cann_buffer_type_name(
  959. ggml_backend_buffer_type_t buft) {
  960. return "CANN";
  961. GGML_UNUSED(buft);
  962. }
  963. /**
  964. * @brief Allocates a new CANN buffer of the specified type and size.
  965. *
  966. * This function allocates a new CANN buffer on the specified device with the
  967. * given size.
  968. *
  969. * @param buft Pointer to the buffer type context.
  970. * @param size Size in bytes of the buffer to allocate.
  971. * @return Pointer to the allocated buffer, or nullptr if allocation fails.
  972. */
  973. GGML_CALL static ggml_backend_buffer_t
  974. ggml_backend_cann_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft,
  975. size_t size) {
  976. ggml_backend_cann_buffer_type_context* buft_ctx =
  977. (ggml_backend_cann_buffer_type_context*)buft->context;
  978. ggml_cann_set_device(buft_ctx->device);
  979. size = std::max(size, (size_t)1);
  980. void* dev_ptr;
  981. aclError err = aclrtMalloc(&dev_ptr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  982. if (err != ACL_SUCCESS) {
  983. GGML_CANN_LOG_ERROR(
  984. "%s: allocating %.2f MiB on device %d: aclrtMalloc failed: %s\n",
  985. __func__, size / 1024.0 / 1024.0, buft_ctx->device,
  986. aclGetRecentErrMsg());
  987. return nullptr;
  988. }
  989. ggml_backend_cann_buffer_context* ctx =
  990. new ggml_backend_cann_buffer_context(buft_ctx->device, dev_ptr);
  991. return ggml_backend_buffer_init(buft, ggml_backend_cann_buffer_interface,
  992. ctx, size);
  993. }
  994. /**
  995. * @brief Retrieves the memory alignment requirement for CANN buffers of this
  996. * type.
  997. *
  998. * This function returns the alignment requirement in bytes for memory allocated
  999. * by the CANN buffer type.
  1000. *
  1001. * @param buft Pointer to the buffer type context (unused in this
  1002. * implementation).
  1003. * @return The alignment requirement in bytes (fixed at 128 bytes for CANN
  1004. * buffers).
  1005. */
  1006. GGML_CALL static size_t ggml_backend_cann_buffer_type_get_alignment(
  1007. ggml_backend_buffer_type_t buft) {
  1008. return 128;
  1009. GGML_UNUSED(buft);
  1010. }
  1011. /**
  1012. * @brief Calculates the allocation size required for a tensor in a CANN buffer.
  1013. *
  1014. * Computes the total allocation size needed for storing the tensor's data in a
  1015. * CANN buffer, considering any necessary padding or adjustments for quantized
  1016. * types.
  1017. *
  1018. * @param buft Pointer to the buffer type context (unused in this
  1019. * implementation).
  1020. * @param tensor Pointer to the tensor for which the allocation size is
  1021. * calculated.
  1022. * @return The total allocation size in bytes required for the tensor in the
  1023. * CANN buffer.
  1024. */
  1025. GGML_CALL static size_t ggml_backend_cann_buffer_type_get_alloc_size(
  1026. ggml_backend_buffer_type_t buft, const ggml_tensor* tensor) {
  1027. size_t size = ggml_nbytes(tensor);
  1028. int64_t ne0 = tensor->ne[0];
  1029. // last line must bigger than 32, because every single op deal at
  1030. // least 32 bytes.
  1031. // TODO: quantized type?
  1032. // int64_t line_size = ne0 * ggml_element_size(tensor);
  1033. // int64_t line_size_align_32 = (line_size + 31) & ~31;
  1034. // size += (line_size_align_32 - line_size);
  1035. // TODO: not support quantized yet.
  1036. // TODO: consider un-continue tensor.
  1037. if (ggml_is_quantized(tensor->type)) {
  1038. if (ne0 % MATRIX_ROW_PADDING != 0) {
  1039. size += ggml_row_size(
  1040. tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
  1041. }
  1042. }
  1043. return size;
  1044. GGML_UNUSED(buft);
  1045. }
  1046. /**
  1047. * @brief Interface for managing CANN buffer types in the GGML backend.
  1048. *
  1049. * Provides function pointers for allocating, querying properties, and managing
  1050. * memory for CANN buffer types in the GGML backend.
  1051. */
  1052. static ggml_backend_buffer_type_i ggml_backend_cann_buffer_type_interface = {
  1053. /* .get_name = */ ggml_backend_cann_buffer_type_name,
  1054. /* .alloc_buffer = */ ggml_backend_cann_buffer_type_alloc_buffer,
  1055. /* .get_alignment = */ ggml_backend_cann_buffer_type_get_alignment,
  1056. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  1057. /* .get_alloc_size = */ ggml_backend_cann_buffer_type_get_alloc_size,
  1058. /* .is_host = */ NULL,
  1059. };
  1060. /**
  1061. * @brief Retrieves the CANN buffer type for a specified device.
  1062. *
  1063. * This function initializes and returns the buffer type interface associated
  1064. * with the given device. It ensures thread-safe access using a mutex.
  1065. *
  1066. * @param device The device index for which to retrieve the buffer type.
  1067. * @return A pointer to the buffer type interface for the specified device, or
  1068. * nullptr if the device index is out of range.
  1069. */
  1070. GGML_CALL ggml_backend_buffer_type_t
  1071. ggml_backend_cann_buffer_type(int32_t device) {
  1072. static std::mutex mutex;
  1073. std::lock_guard<std::mutex> lock(mutex);
  1074. if (device >= ggml_backend_cann_get_device_count()) {
  1075. return nullptr;
  1076. }
  1077. static ggml_backend_buffer_type
  1078. ggml_backend_cann_buffer_types[GGML_CANN_MAX_DEVICES];
  1079. static bool ggml_backend_cann_buffer_type_initialized = false;
  1080. if (!ggml_backend_cann_buffer_type_initialized) {
  1081. for (int32_t i = 0; i < GGML_CANN_MAX_DEVICES; i++) {
  1082. ggml_backend_cann_buffer_types[i] = {
  1083. /* .iface = */ ggml_backend_cann_buffer_type_interface,
  1084. /* .context = */
  1085. new ggml_backend_cann_buffer_type_context{
  1086. i, "CANN" + std::to_string(i)},
  1087. };
  1088. }
  1089. ggml_backend_cann_buffer_type_initialized = true;
  1090. }
  1091. return &ggml_backend_cann_buffer_types[device];
  1092. }
  1093. /**
  1094. * @brief Computes the forward operation for a given tensor using CANN
  1095. * operations.
  1096. *
  1097. * This function selects the appropriate CANN operation based on the type of
  1098. * operation specified in the tensor and performs the computation.
  1099. *
  1100. * @param ctx The CANN context containing necessary resources and
  1101. * configurations.
  1102. * @param dst The destination tensor where the result of the computation will be
  1103. * stored.
  1104. * @return true if the computation was successful; false otherwise.
  1105. */
  1106. static bool ggml_cann_compute_forward(ggml_backend_cann_context& ctx,
  1107. struct ggml_tensor* dst) {
  1108. switch (dst->op) {
  1109. case GGML_OP_REPEAT:
  1110. ggml_cann_repeat(ctx, dst);
  1111. break;
  1112. case GGML_OP_GET_ROWS:
  1113. ggml_cann_get_rows(ctx, dst);
  1114. break;
  1115. case GGML_OP_DUP:
  1116. ggml_cann_dup(ctx, dst);
  1117. break;
  1118. case GGML_OP_ADD:
  1119. ggml_cann_add(ctx, dst);
  1120. break;
  1121. case GGML_OP_ACC:
  1122. ggml_cann_acc(ctx, dst);
  1123. break;
  1124. case GGML_OP_MUL:
  1125. ggml_cann_mul_div<aclnnMulGetWorkspaceSize, aclnnMul>(ctx, dst);
  1126. break;
  1127. case GGML_OP_DIV:
  1128. ggml_cann_mul_div<aclnnDivGetWorkspaceSize, aclnnDiv>(ctx, dst);
  1129. break;
  1130. case GGML_OP_UNARY:
  1131. switch (ggml_get_unary_op(dst)) {
  1132. case GGML_UNARY_OP_GELU:
  1133. ggml_cann_activation<aclnnGeluGetWorkspaceSize, aclnnGelu>(
  1134. ctx, dst);
  1135. break;
  1136. case GGML_UNARY_OP_SILU:
  1137. ggml_cann_activation<aclnnSiluGetWorkspaceSize, aclnnSilu>(
  1138. ctx, dst);
  1139. break;
  1140. // TODO: Use faster gelu??
  1141. case GGML_UNARY_OP_GELU_QUICK:
  1142. ggml_cann_activation<aclnnGeluGetWorkspaceSize, aclnnGelu>(
  1143. ctx, dst);
  1144. break;
  1145. case GGML_UNARY_OP_TANH:
  1146. ggml_cann_activation<aclnnTanhGetWorkspaceSize, aclnnTanh>(
  1147. ctx, dst);
  1148. break;
  1149. case GGML_UNARY_OP_RELU:
  1150. ggml_cann_activation<aclnnReluGetWorkspaceSize, aclnnRelu>(
  1151. ctx, dst);
  1152. break;
  1153. case GGML_UNARY_OP_HARDSIGMOID:
  1154. ggml_cann_activation<aclnnHardsigmoidGetWorkspaceSize,
  1155. aclnnHardsigmoid>(ctx, dst);
  1156. break;
  1157. case GGML_UNARY_OP_HARDSWISH:
  1158. ggml_cann_activation<aclnnHardswishGetWorkspaceSize,
  1159. aclnnHardswish>(ctx, dst);
  1160. break;
  1161. default:
  1162. return false;
  1163. }
  1164. break;
  1165. case GGML_OP_NORM:
  1166. ggml_cann_norm(ctx, dst);
  1167. break;
  1168. case GGML_OP_GROUP_NORM:
  1169. ggml_cann_group_norm(ctx, dst);
  1170. break;
  1171. case GGML_OP_CONCAT:
  1172. ggml_cann_concat(ctx, dst);
  1173. break;
  1174. case GGML_OP_UPSCALE:
  1175. ggml_cann_upsample_nearest2d(ctx, dst);
  1176. break;
  1177. case GGML_OP_PAD:
  1178. ggml_cann_pad(ctx, dst);
  1179. break;
  1180. case GGML_OP_ARANGE:
  1181. ggml_cann_arange(ctx, dst);
  1182. break;
  1183. case GGML_OP_TIMESTEP_EMBEDDING:
  1184. ggml_cann_timestep_embedding(ctx, dst);
  1185. break;
  1186. case GGML_OP_LEAKY_RELU:
  1187. ggml_cann_leaky_relu(ctx, dst);
  1188. break;
  1189. case GGML_OP_RMS_NORM:
  1190. ggml_cann_rms_norm(ctx, dst);
  1191. break;
  1192. case GGML_OP_MUL_MAT:
  1193. ggml_cann_mul_mat(ctx, dst);
  1194. break;
  1195. case GGML_OP_MUL_MAT_ID:
  1196. return false;
  1197. case GGML_OP_SCALE:
  1198. ggml_cann_scale(ctx, dst);
  1199. break;
  1200. case GGML_OP_SQR:
  1201. ggml_cann_sqr(ctx, dst);
  1202. break;
  1203. case GGML_OP_CLAMP:
  1204. ggml_cann_clamp(ctx, dst);
  1205. break;
  1206. case GGML_OP_CPY:
  1207. ggml_cann_cpy(ctx, dst);
  1208. break;
  1209. case GGML_OP_CONT:
  1210. ggml_cann_dup(ctx, dst);
  1211. break;
  1212. case GGML_OP_NONE:
  1213. case GGML_OP_RESHAPE:
  1214. case GGML_OP_VIEW:
  1215. case GGML_OP_PERMUTE:
  1216. case GGML_OP_TRANSPOSE:
  1217. break;
  1218. case GGML_OP_DIAG_MASK_INF:
  1219. ggml_cann_diag_mask(ctx, dst, -INFINITY);
  1220. break;
  1221. case GGML_OP_SOFT_MAX:
  1222. ggml_cann_softmax(ctx, dst);
  1223. break;
  1224. case GGML_OP_ROPE:
  1225. ggml_cann_rope(ctx, dst);
  1226. break;
  1227. case GGML_OP_IM2COL:
  1228. ggml_cann_im2col(ctx, dst);
  1229. break;
  1230. case GGML_OP_POOL_2D:
  1231. ggml_cann_pool2d(ctx, dst);
  1232. break;
  1233. case GGML_OP_SUM_ROWS:
  1234. ggml_cann_sum_rows(ctx, dst);
  1235. break;
  1236. case GGML_OP_ARGSORT:
  1237. ggml_cann_argsort(ctx, dst);
  1238. break;
  1239. default:
  1240. return false;
  1241. }
  1242. return true;
  1243. }
  1244. // backend
  1245. /**
  1246. * @brief Retrieves the name associated with the CANN backend.
  1247. *
  1248. * This function returns the name assigned to the CANN backend, which is stored
  1249. * in the context of the provided backend structure.
  1250. *
  1251. * @param backend Pointer to the CANN backend structure.
  1252. * @return A pointer to a constant string representing the backend name.
  1253. */
  1254. GGML_CALL static const char* ggml_backend_cann_name(ggml_backend_t backend) {
  1255. ggml_backend_cann_context* cann_ctx =
  1256. (ggml_backend_cann_context*)backend->context;
  1257. return cann_ctx->name.c_str();
  1258. }
  1259. /**
  1260. * @brief Frees resources associated with the CANN backend.
  1261. *
  1262. * This function releases resources associated with the CANN backend context
  1263. * and resets the device associated with the backend to its initial state.
  1264. *
  1265. * @param backend Pointer to the CANN backend structure to be freed.
  1266. */
  1267. GGML_CALL static void ggml_backend_cann_free(ggml_backend_t backend) {
  1268. ggml_backend_cann_context* cann_ctx =
  1269. (ggml_backend_cann_context*)backend->context;
  1270. ACL_CHECK(aclrtSynchronizeDevice());
  1271. ACL_CHECK(aclrtResetDevice(cann_ctx->device));
  1272. // finalize when last backend freed.
  1273. if (cann_ctx->device == ggml_backend_cann_get_device_count() - 1) {
  1274. ACL_CHECK(aclFinalize());
  1275. }
  1276. delete cann_ctx;
  1277. delete backend;
  1278. }
  1279. /**
  1280. * @brief Retrieves the default buffer type associated with the CANN backend.
  1281. *
  1282. * This function returns the buffer type specific to the device associated
  1283. * with the CANN backend. It is used to allocate buffers for computations
  1284. * performed by the backend.
  1285. *
  1286. * @param backend Pointer to the CANN backend structure.
  1287. * @return Pointer to the buffer type structure for the CANN backend.
  1288. */
  1289. GGML_CALL static ggml_backend_buffer_type_t
  1290. ggml_backend_cann_get_default_buffer_type(ggml_backend_t backend) {
  1291. ggml_backend_cann_context* cann_ctx =
  1292. (ggml_backend_cann_context*)backend->context;
  1293. return ggml_backend_cann_buffer_type(cann_ctx->device);
  1294. }
  1295. /**
  1296. * @brief Sets tensor data asynchronously in the CANN backend.
  1297. *
  1298. * This function asynchronously sets tensor data in the CANN backend. Depending
  1299. * on the tensor type, it may perform data transformations before copying data
  1300. * to the device.
  1301. *
  1302. * @param backend Pointer to the CANN backend structure.
  1303. * @param tensor Pointer to the tensor structure to set data for.
  1304. * @param data Pointer to the host data to copy to the tensor.
  1305. * @param offset Offset in bytes within the host data.
  1306. * @param size Size of the data to copy in bytes.
  1307. */
  1308. GGML_CALL static void ggml_backend_cann_set_tensor_async(ggml_backend_t backend,
  1309. ggml_tensor *tensor,
  1310. const void *data,
  1311. size_t offset,
  1312. size_t size) {
  1313. ggml_backend_cann_context *cann_ctx =
  1314. (ggml_backend_cann_context *)backend->context;
  1315. if (!need_transform(tensor->type)) {
  1316. ACL_CHECK(aclrtMemcpyAsync((char *)tensor->data + offset, size, data,
  1317. size, ACL_MEMCPY_HOST_TO_DEVICE,
  1318. cann_ctx->stream()));
  1319. } else {
  1320. void *transform_buffer = malloc(size);
  1321. ggml_backend_cann_transform(tensor, data, transform_buffer);
  1322. #ifndef NDEBUG
  1323. void *check_buffer = malloc(size);
  1324. ggml_backend_cann_transform_back(tensor, transform_buffer,
  1325. check_buffer);
  1326. GGML_ASSERT(memcmp(data, check_buffer, size));
  1327. free(check_buffer);
  1328. #endif
  1329. ACL_CHECK(aclrtMemcpyAsync(
  1330. (char *)tensor->data + offset, size, transform_buffer, size,
  1331. ACL_MEMCPY_HOST_TO_DEVICE, cann_ctx->stream()));
  1332. ACL_CHECK(aclrtSynchronizeStream(cann_ctx->stream()));
  1333. free(transform_buffer);
  1334. }
  1335. }
  1336. GGML_CALL static void ggml_backend_cann_get_tensor_async(
  1337. ggml_backend_t backend, const ggml_tensor *tensor, void *data,
  1338. size_t offset, size_t size) {
  1339. ggml_backend_cann_context *cann_ctx =
  1340. (ggml_backend_cann_context *)backend->context;
  1341. ggml_backend_buffer_t buf =
  1342. tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  1343. GGML_ASSERT(buf->buft == ggml_backend_cann_buffer_type(cann_ctx->device) &&
  1344. "unsupported buffer type");
  1345. if (!need_transform(tensor->type)) {
  1346. ACL_CHECK(aclrtMemcpyAsync(data, size, (char *)tensor->data + offset,
  1347. size, ACL_MEMCPY_DEVICE_TO_HOST,
  1348. cann_ctx->stream()));
  1349. } else {
  1350. void *transform_buffer = malloc(size);
  1351. ACL_CHECK(aclrtMemcpyAsync(
  1352. transform_buffer, size, (char *)tensor->data + offset, size,
  1353. ACL_MEMCPY_DEVICE_TO_HOST, cann_ctx->stream()));
  1354. ACL_CHECK(aclrtSynchronizeStream(cann_ctx->stream()));
  1355. ggml_backend_cann_transform_back(tensor, transform_buffer, data);
  1356. free(transform_buffer);
  1357. }
  1358. }
  1359. /**
  1360. * @brief Asynchronously copies tensor data between CANN backends.
  1361. *
  1362. * This function copies tensor data asynchronously between two CANN backends. It
  1363. * checks if both tensors reside in CANN buffers and whether the devices support
  1364. * peer-to-peer access for direct copying. If not, it returns false.
  1365. *
  1366. * @param backend_src Pointer to the source CANN backend structure.
  1367. * @param backend_dst Pointer to the destination CANN backend structure.
  1368. * @param src Pointer to the source tensor to copy data from.
  1369. * @param dst Pointer to the destination tensor to copy data to.
  1370. * @return true if the copy operation succeeds, false otherwise.
  1371. */
  1372. GGML_CALL static bool ggml_backend_cann_cpy_tensor_async(
  1373. ggml_backend_t backend_src, ggml_backend_t backend_dst,
  1374. const ggml_tensor* src, ggml_tensor* dst) {
  1375. GGML_ASSERT(ggml_backend_is_cann(backend_src) ||
  1376. ggml_backend_is_cann(backend_dst));
  1377. if (!ggml_backend_buffer_is_cann(src->buffer) ||
  1378. !ggml_backend_buffer_is_cann(dst->buffer)) {
  1379. return false;
  1380. }
  1381. ggml_backend_buffer_t buf_src =
  1382. src->view_src ? src->view_src->buffer : src->buffer;
  1383. ggml_backend_buffer_t buf_dst =
  1384. dst->view_src ? dst->view_src->buffer : dst->buffer;
  1385. ggml_backend_cann_context* cann_ctx_src =
  1386. (ggml_backend_cann_context*)backend_src->context;
  1387. ggml_backend_cann_context* cann_ctx_dst =
  1388. (ggml_backend_cann_context*)backend_dst->context;
  1389. size_t copy_size = ggml_nbytes(dst);
  1390. if (backend_src != backend_dst) {
  1391. ggml_backend_cann_buffer_context* buf_ctx_src =
  1392. (ggml_backend_cann_buffer_context*)buf_src->context;
  1393. ggml_backend_cann_buffer_context* buf_ctx_dst =
  1394. (ggml_backend_cann_buffer_context*)buf_dst->context;
  1395. GGML_ASSERT(cann_ctx_src->device == buf_ctx_src->device);
  1396. GGML_ASSERT(cann_ctx_dst->device == buf_ctx_dst->device);
  1397. int32_t canAccessPeer = 0;
  1398. ACL_CHECK(aclrtDeviceCanAccessPeer(&canAccessPeer, cann_ctx_src->device,
  1399. cann_ctx_dst->device));
  1400. if (!canAccessPeer) {
  1401. return false;
  1402. }
  1403. // need open both directions for memcpyasync between devices.
  1404. ggml_cann_set_device(cann_ctx_dst->device);
  1405. ACL_CHECK(aclrtDeviceEnablePeerAccess(cann_ctx_src->device, 0));
  1406. ggml_cann_set_device(cann_ctx_src->device);
  1407. ACL_CHECK(aclrtDeviceEnablePeerAccess(cann_ctx_dst->device, 0));
  1408. ACL_CHECK(aclrtMemcpyAsync(dst->data, copy_size, src->data, copy_size,
  1409. ACL_MEMCPY_DEVICE_TO_DEVICE,
  1410. cann_ctx_src->stream()));
  1411. //TODO: workaround for Event didn`t work here.
  1412. aclrtSynchronizeStream(cann_ctx_src->stream());
  1413. } else {
  1414. // src and dst are on the same backend
  1415. ACL_CHECK(aclrtMemcpyAsync(dst->data, copy_size, src->data, copy_size,
  1416. ACL_MEMCPY_DEVICE_TO_DEVICE,
  1417. cann_ctx_dst->stream()));
  1418. }
  1419. return true;
  1420. }
  1421. /**
  1422. * @brief Synchronizes a CANN backend.
  1423. *
  1424. * This function synchronizes the specified CANN backend by waiting for all
  1425. * operations in its associated stream to complete.
  1426. *
  1427. * @param backend Pointer to the CANN backend structure to synchronize.
  1428. */
  1429. GGML_CALL static void ggml_backend_cann_synchronize(ggml_backend_t backend) {
  1430. ggml_backend_cann_context* cann_ctx =
  1431. (ggml_backend_cann_context*)backend->context;
  1432. ggml_cann_set_device(cann_ctx->device);
  1433. ACL_CHECK(aclrtSynchronizeStream(cann_ctx->stream()));
  1434. }
  1435. /**
  1436. * @brief Computes a computational graph using a CANN backend.
  1437. *
  1438. * This function computes the operations defined in the computational graph
  1439. * using the specified CANN backend.
  1440. *
  1441. * @param backend Pointer to the CANN backend structure to use for computation.
  1442. * @param cgraph Pointer to the computational graph structure containing nodes
  1443. * representing operations to be computed.
  1444. * @return enum ggml_status Returns GGML_STATUS_SUCCESS if computation
  1445. * completes successfully, otherwise an appropriate error status.
  1446. */
  1447. GGML_CALL static enum ggml_status ggml_backend_cann_graph_compute(
  1448. ggml_backend_t backend, ggml_cgraph* cgraph) {
  1449. ggml_backend_cann_context* cann_ctx =
  1450. (ggml_backend_cann_context*)backend->context;
  1451. ggml_cann_set_device(cann_ctx->device);
  1452. for (int i = 0; i < cgraph->n_nodes; i++) {
  1453. ggml_tensor* node = cgraph->nodes[i];
  1454. if (ggml_is_empty(node) || node->op == GGML_OP_NONE) {
  1455. continue;
  1456. }
  1457. bool ok = ggml_cann_compute_forward(*cann_ctx, node);
  1458. if (!ok) {
  1459. GGML_CANN_LOG_ERROR("%s: error: op not supported %s (%s)\n", __func__,
  1460. node->name, ggml_op_name(node->op));
  1461. }
  1462. GGML_ASSERT(ok);
  1463. }
  1464. return GGML_STATUS_SUCCESS;
  1465. }
  1466. /**
  1467. * @brief Checks if the CANN backend supports a specific operation.
  1468. *
  1469. * This function checks whether the specified operation is supported by the
  1470. * CANN backend.
  1471. *
  1472. * @param backend Pointer to the CANN backend structure to check support for
  1473. * the operation.
  1474. * @param op Pointer to the tensor representing the operation to check.
  1475. * @return bool Returns true if the operation is supported by the backend,
  1476. * otherwise false.
  1477. */
  1478. GGML_CALL static bool ggml_backend_cann_supports_op(ggml_backend_t backend,
  1479. const ggml_tensor* op) {
  1480. switch (op->op) {
  1481. case GGML_OP_UNARY:
  1482. switch (ggml_get_unary_op(op)) {
  1483. case GGML_UNARY_OP_GELU:
  1484. case GGML_UNARY_OP_SILU:
  1485. case GGML_UNARY_OP_RELU:
  1486. case GGML_UNARY_OP_HARDSIGMOID:
  1487. case GGML_UNARY_OP_HARDSWISH:
  1488. case GGML_UNARY_OP_GELU_QUICK:
  1489. case GGML_UNARY_OP_TANH:
  1490. return true;
  1491. default:
  1492. return false;
  1493. }
  1494. case GGML_OP_MUL_MAT: {
  1495. switch (op->src[0]->type) {
  1496. case GGML_TYPE_F16:
  1497. case GGML_TYPE_F32:
  1498. case GGML_TYPE_Q8_0:
  1499. // TODO: fix me
  1500. // Current groupsize should not be greater than k-1 in
  1501. // aclnnWeightQuantBatchMatmulV2GetWorkspaceSize().
  1502. case GGML_TYPE_Q4_0:
  1503. return true;
  1504. default:
  1505. return false;
  1506. }
  1507. }
  1508. case GGML_OP_MUL_MAT_ID:
  1509. return false;
  1510. // embedding
  1511. case GGML_OP_GET_ROWS: {
  1512. switch (op->src[0]->type) {
  1513. case GGML_TYPE_F32:
  1514. case GGML_TYPE_F16:
  1515. case GGML_TYPE_Q4_0:
  1516. case GGML_TYPE_Q8_0:
  1517. return true;
  1518. default:
  1519. return false;
  1520. }
  1521. } break;
  1522. case GGML_OP_CPY: {
  1523. switch (op->type) {
  1524. case GGML_TYPE_F32:
  1525. case GGML_TYPE_F16:
  1526. case GGML_TYPE_Q8_0:
  1527. case GGML_TYPE_Q4_0:
  1528. return true;
  1529. default:
  1530. return false;
  1531. }
  1532. }
  1533. case GGML_OP_DUP:
  1534. case GGML_OP_REPEAT:
  1535. case GGML_OP_CONCAT:
  1536. case GGML_OP_NONE:
  1537. case GGML_OP_RESHAPE:
  1538. case GGML_OP_VIEW:
  1539. case GGML_OP_PERMUTE:
  1540. case GGML_OP_TRANSPOSE:
  1541. case GGML_OP_NORM:
  1542. case GGML_OP_ADD:
  1543. case GGML_OP_MUL:
  1544. case GGML_OP_DIV:
  1545. case GGML_OP_RMS_NORM:
  1546. case GGML_OP_SCALE:
  1547. case GGML_OP_SQR:
  1548. case GGML_OP_CLAMP:
  1549. case GGML_OP_CONT:
  1550. case GGML_OP_DIAG_MASK_INF:
  1551. case GGML_OP_SOFT_MAX:
  1552. case GGML_OP_ROPE:
  1553. case GGML_OP_IM2COL:
  1554. case GGML_OP_POOL_2D:
  1555. case GGML_OP_SUM_ROWS:
  1556. case GGML_OP_ARGSORT:
  1557. case GGML_OP_ACC:
  1558. case GGML_OP_GROUP_NORM:
  1559. case GGML_OP_UPSCALE:
  1560. case GGML_OP_PAD:
  1561. case GGML_OP_ARANGE:
  1562. case GGML_OP_TIMESTEP_EMBEDDING:
  1563. case GGML_OP_LEAKY_RELU:
  1564. return true;
  1565. default:
  1566. return false;
  1567. }
  1568. GGML_UNUSED(backend);
  1569. }
  1570. /**
  1571. * @brief Checks if the backend buffer type is associated with the CANN backend.
  1572. *
  1573. * This function checks whether the provided backend buffer type is associated
  1574. * with the CANN backend based on the comparison of its name retrieval function
  1575. * pointer.
  1576. *
  1577. * @param buft Pointer to the backend buffer type to check.
  1578. * @return bool Returns true if the buffer type is associated with the CANN
  1579. * backend, otherwise false.
  1580. */
  1581. static bool ggml_backend_buft_is_cann(ggml_backend_buffer_type_t buft) {
  1582. return buft->iface.get_name == ggml_backend_cann_buffer_type_name;
  1583. }
  1584. /**
  1585. * @brief Checks if the CANN backend supports a specific backend buffer type.
  1586. *
  1587. * This function determines whether the CANN backend supports the given backend
  1588. * buffer type by comparing the device context of the backend and buffer type.
  1589. * It returns true if the devices are same between the backend context and
  1590. * buffer type context.
  1591. *
  1592. * @param backend Pointer to the CANN backend.
  1593. * @param buft Pointer to the backend buffer type to check.
  1594. * @return bool Returns true if the CANN backend supports the buffer type,
  1595. * otherwise false.
  1596. */
  1597. GGML_CALL static bool ggml_backend_cann_supports_buft(
  1598. ggml_backend_t backend, ggml_backend_buffer_type_t buft) {
  1599. if (ggml_backend_buft_is_cann(buft)) {
  1600. ggml_backend_cann_context * cann_ctx =
  1601. (ggml_backend_cann_context *)backend->context;
  1602. ggml_backend_cann_buffer_type_context * buft_ctx =
  1603. (ggml_backend_cann_buffer_type_context *)buft->context;
  1604. return buft_ctx->device == cann_ctx->device;
  1605. }
  1606. return false;
  1607. }
  1608. /**
  1609. * @brief Determines if a tensor operation should be offloaded to the CANN
  1610. * backend.
  1611. *
  1612. * This function checks if a given tensor operation should be offloaded to the
  1613. * CANN backend based on the operation type and the size of the tensor. It
  1614. * returns true if the second dimension (ne[1]) of the tensor is greater than or
  1615. * equal to the minimum batch size and the operation is not GGML_OP_GET_ROWS.
  1616. *
  1617. * @param backend Pointer to the CANN backend.
  1618. * @param op Pointer to the tensor operation to check.
  1619. * @return bool Returns true if the operation should be offloaded, otherwise
  1620. * false.
  1621. */
  1622. GGML_CALL static bool ggml_backend_cann_offload_op(ggml_backend_t backend,
  1623. const ggml_tensor* op) {
  1624. const int min_batch_size = 32;
  1625. GGML_UNUSED(backend);
  1626. return op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS;
  1627. }
  1628. /**
  1629. * @brief Creates a new event for the CANN backend.
  1630. *
  1631. * This function initializes a new event for the CANN backend by setting the
  1632. * device and creating an ACL runtime event. The created event is then wrapped
  1633. * in a ggml_backend_event structure and returned.
  1634. *
  1635. * @param backend Pointer to the CANN backend.
  1636. * @return ggml_backend_event_t Returns a pointer to the new event structure.
  1637. */
  1638. static ggml_backend_event_t ggml_backend_cann_event_new(
  1639. ggml_backend_t backend) {
  1640. ggml_backend_cann_context* cann_ctx =
  1641. (ggml_backend_cann_context*)backend->context;
  1642. ggml_cann_set_device(cann_ctx->device);
  1643. aclrtEvent event;
  1644. ACL_CHECK(aclrtCreateEvent(&event));
  1645. return new ggml_backend_event{
  1646. /* .backend = */ backend,
  1647. /* .context = */ event,
  1648. };
  1649. }
  1650. /**
  1651. * @brief Frees a CANN backend event.
  1652. *
  1653. * This function destroys the ACL runtime event associated with the given CANN
  1654. * backend event and then deletes the event structure itself.
  1655. *
  1656. * @param event Pointer to the event structure to be freed.
  1657. */
  1658. static void ggml_backend_cann_event_free(ggml_backend_event_t event) {
  1659. ACL_CHECK(aclrtDestroyEvent((aclrtEvent)event->context));
  1660. delete event;
  1661. }
  1662. /**
  1663. * @brief Records an event on the CANN backend stream.
  1664. *
  1665. * This function records the given event on the ACL runtime stream associated
  1666. * with the backend context.
  1667. *
  1668. * @param event Pointer to the event structure to be recorded.
  1669. */
  1670. static void ggml_backend_cann_event_record(ggml_backend_event_t event) {
  1671. ggml_backend_cann_context* cann_ctx =
  1672. (ggml_backend_cann_context*)event->backend->context;
  1673. ACL_CHECK(aclrtRecordEvent((aclrtEvent)event->context, cann_ctx->stream()));
  1674. }
  1675. /**
  1676. * @brief Waits for a recorded event to complete on the CANN backend stream.
  1677. *
  1678. * This function makes the given backend wait for the event to complete on its
  1679. * ACL runtime stream.
  1680. *
  1681. * @param backend Pointer to the backend structure.
  1682. * @param event Pointer to the event structure that the backend needs to wait
  1683. * for.
  1684. */
  1685. static void ggml_backend_cann_event_wait(ggml_backend_t backend,
  1686. ggml_backend_event_t event) {
  1687. ggml_backend_cann_context* cann_ctx =
  1688. (ggml_backend_cann_context*)backend->context;
  1689. if (ggml_backend_is_cann(event->backend)) {
  1690. ACL_CHECK(aclrtStreamWaitEvent(cann_ctx->stream(),
  1691. (aclrtEvent)event->context));
  1692. } else {
  1693. GGML_ABORT("fatal error");
  1694. }
  1695. }
  1696. /**
  1697. * @brief Synchronizes the given event on the CANN backend.
  1698. *
  1699. * This function waits for the specified event to complete on the ACL runtime.
  1700. *
  1701. * @param event Pointer to the event structure to be synchronized.
  1702. */
  1703. static void ggml_backend_cann_event_synchronize(ggml_backend_event_t event) {
  1704. ACL_CHECK(aclrtSynchronizeEvent((aclrtEvent)event->context));
  1705. }
  1706. /**
  1707. * @brief Structure defining the interface for the CANN backend.
  1708. *
  1709. * This structure contains function pointers for various operations
  1710. * supported by the CANN backend, including name retrieval, memory
  1711. * management, tensor operations, synchronization, and event handling.
  1712. */
  1713. static ggml_backend_i ggml_backend_cann_interface = {
  1714. /* .get_name = */ ggml_backend_cann_name,
  1715. /* .free = */ ggml_backend_cann_free,
  1716. /* .get_default_buffer_type = */ ggml_backend_cann_get_default_buffer_type,
  1717. /* .set_tensor_async = */ ggml_backend_cann_set_tensor_async,
  1718. /* .get_tensor_async = */ ggml_backend_cann_get_tensor_async,
  1719. /* .cpy_tensor_async = */ ggml_backend_cann_cpy_tensor_async,
  1720. /* .synchronize = */ ggml_backend_cann_synchronize,
  1721. /* .graph_plan_create = */ NULL,
  1722. /* .graph_plan_free = */ NULL,
  1723. /* .graph_plan_update = */ NULL,
  1724. /* .graph_plan_compute = */ NULL,
  1725. /* .graph_compute = */ ggml_backend_cann_graph_compute,
  1726. /* .supports_op = */ ggml_backend_cann_supports_op,
  1727. /* .supports_buft = */ ggml_backend_cann_supports_buft,
  1728. /* .offload_op = */ ggml_backend_cann_offload_op,
  1729. /* .event_new = */ ggml_backend_cann_event_new,
  1730. /* .event_free = */ ggml_backend_cann_event_free,
  1731. /* .event_record = */ ggml_backend_cann_event_record,
  1732. /* .event_wait = */ ggml_backend_cann_event_wait,
  1733. /* .event_synchronize = */ ggml_backend_cann_event_synchronize,
  1734. };
  1735. /**
  1736. * @brief Return the hardcoded GUID for the CANN backend.
  1737. *
  1738. * This function returns a static GUID which uniquely identifies the CANN
  1739. * backend.
  1740. *
  1741. * @return A pointer to the static GUID.
  1742. */
  1743. static ggml_guid_t ggml_backend_cann_guid() {
  1744. static ggml_guid guid = {0xa1, 0x94, 0xaf, 0xac, 0xbd, 0x4f, 0x47, 0x34,
  1745. 0xbe, 0x1a, 0x9e, 0x71, 0x1f, 0x9e, 0xed, 0x64};
  1746. return &guid;
  1747. }
  1748. GGML_CALL ggml_backend_t ggml_backend_cann_init(int32_t device) {
  1749. aclInit(nullptr);
  1750. if (device < 0 || device >= ggml_backend_cann_get_device_count()) {
  1751. GGML_CANN_LOG_ERROR("%s: error: invalid device %d\n", __func__, device);
  1752. return nullptr;
  1753. }
  1754. ggml_backend_cann_context* ctx = new ggml_backend_cann_context(device);
  1755. if (ctx == nullptr) {
  1756. GGML_CANN_LOG_ERROR("%s: error: failed to allocate context\n", __func__);
  1757. return nullptr;
  1758. }
  1759. ggml_cann_set_device(ctx->device);
  1760. ggml_backend_t cann_backend =
  1761. new ggml_backend{/* .guid = */ ggml_backend_cann_guid(),
  1762. /* .interface = */ ggml_backend_cann_interface,
  1763. /* .context = */ ctx};
  1764. return cann_backend;
  1765. }
  1766. GGML_CALL bool ggml_backend_is_cann(ggml_backend_t backend) {
  1767. return backend != NULL &&
  1768. ggml_guid_matches(backend->guid, ggml_backend_cann_guid());
  1769. }
  1770. GGML_CALL int32_t ggml_backend_cann_get_device_count() {
  1771. return ggml_cann_info().device_count;
  1772. }
  1773. GGML_CALL void ggml_backend_cann_get_device_description(
  1774. int32_t device, char* description, size_t description_size) {
  1775. ggml_cann_set_device(device);
  1776. const char* soc_name = aclrtGetSocName();
  1777. snprintf(description, description_size, "%s", soc_name);
  1778. }
  1779. GGML_CALL void ggml_backend_cann_get_device_memory(int32_t device, size_t* free,
  1780. size_t* total) {
  1781. ggml_cann_set_device(device);
  1782. ACL_CHECK(aclrtGetMemInfo(ACL_HBM_MEM, free, total));
  1783. }
  1784. // backend registry
  1785. /**
  1786. * @brief Initializes a CANN backend based on the provided parameters.
  1787. *
  1788. * This function initializes a CANN backend using the device index and then
  1789. * initializes the backend using `ggml_backend_cann_init`.
  1790. *
  1791. * @param params Parameters for initialization (unused in this implementation).
  1792. * @param user_data User data containing the device index to initialize the
  1793. * backend.
  1794. * @return ggml_backend_t The initialized CANN backend.
  1795. */
  1796. GGML_CALL static ggml_backend_t ggml_backend_reg_cann_init(const char* params,
  1797. void* user_data) {
  1798. ggml_backend_t cann_backend =
  1799. ggml_backend_cann_init((int)(intptr_t)user_data);
  1800. return cann_backend;
  1801. GGML_UNUSED(params);
  1802. }
  1803. extern "C" GGML_CALL int ggml_backend_cann_reg_devices();
  1804. /**
  1805. * @brief Registers CANN (Ascend) devices as backend options.
  1806. *
  1807. * This function initializes ACL, retrieves the number of available CANN
  1808. * devices, and registers each device as a backend option using
  1809. * `ggml_backend_register`. Each device is given a unique name based on
  1810. * `GGML_CANN_NAME` followed by its index.
  1811. *
  1812. * @return int The number of CANN devices registered.
  1813. */
  1814. GGML_CALL int ggml_backend_cann_reg_devices() {
  1815. uint32_t device_count = ggml_backend_cann_get_device_count();
  1816. // initialization
  1817. for (uint32_t i = 0; i < device_count; i++) {
  1818. char name[128];
  1819. snprintf(name, sizeof(name), "CANN%d", i);
  1820. ggml_backend_register(name, ggml_backend_reg_cann_init,
  1821. ggml_backend_cann_buffer_type(i),
  1822. (void*)(intptr_t)i);
  1823. }
  1824. return device_count;
  1825. }