ggml-cann.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  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. /* .memset_tensor = */ NULL,
  934. /* .set_tensor = */ ggml_backend_cann_buffer_set_tensor,
  935. /* .get_tensor = */ ggml_backend_cann_buffer_get_tensor,
  936. /* .cpy_tensor = */ ggml_backend_cann_buffer_cpy_tensor,
  937. /* .clear = */ ggml_backend_cann_buffer_clear,
  938. /* .reset = */ NULL,
  939. };
  940. // cann buffer type
  941. /**
  942. * @brief Structure representing context information for a specific backend
  943. * buffer type.
  944. */
  945. struct ggml_backend_cann_buffer_type_context {
  946. int32_t
  947. device; /**< Device identifier associated with the buffer context. */
  948. std::string name; /**< Name associated with the buffer context. */
  949. };
  950. /**
  951. * @brief Retrieves the name associated with a CANN buffer type.
  952. *
  953. * This function returns the descriptive name associated with the specified
  954. * CANN buffer type context.
  955. *
  956. * @param buft Pointer to the buffer type context.
  957. * @return Const pointer to the C-style string containing the name.
  958. */
  959. GGML_CALL static const char* ggml_backend_cann_buffer_type_name(
  960. ggml_backend_buffer_type_t buft) {
  961. return "CANN";
  962. GGML_UNUSED(buft);
  963. }
  964. /**
  965. * @brief Allocates a new CANN buffer of the specified type and size.
  966. *
  967. * This function allocates a new CANN buffer on the specified device with the
  968. * given size.
  969. *
  970. * @param buft Pointer to the buffer type context.
  971. * @param size Size in bytes of the buffer to allocate.
  972. * @return Pointer to the allocated buffer, or nullptr if allocation fails.
  973. */
  974. GGML_CALL static ggml_backend_buffer_t
  975. ggml_backend_cann_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft,
  976. size_t size) {
  977. ggml_backend_cann_buffer_type_context* buft_ctx =
  978. (ggml_backend_cann_buffer_type_context*)buft->context;
  979. ggml_cann_set_device(buft_ctx->device);
  980. size = std::max(size, (size_t)1);
  981. void* dev_ptr;
  982. aclError err = aclrtMalloc(&dev_ptr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  983. if (err != ACL_SUCCESS) {
  984. GGML_CANN_LOG_ERROR(
  985. "%s: allocating %.2f MiB on device %d: aclrtMalloc failed: %s\n",
  986. __func__, size / 1024.0 / 1024.0, buft_ctx->device,
  987. aclGetRecentErrMsg());
  988. return nullptr;
  989. }
  990. ggml_backend_cann_buffer_context* ctx =
  991. new ggml_backend_cann_buffer_context(buft_ctx->device, dev_ptr);
  992. return ggml_backend_buffer_init(buft, ggml_backend_cann_buffer_interface,
  993. ctx, size);
  994. }
  995. /**
  996. * @brief Retrieves the memory alignment requirement for CANN buffers of this
  997. * type.
  998. *
  999. * This function returns the alignment requirement in bytes for memory allocated
  1000. * by the CANN buffer type.
  1001. *
  1002. * @param buft Pointer to the buffer type context (unused in this
  1003. * implementation).
  1004. * @return The alignment requirement in bytes (fixed at 128 bytes for CANN
  1005. * buffers).
  1006. */
  1007. GGML_CALL static size_t ggml_backend_cann_buffer_type_get_alignment(
  1008. ggml_backend_buffer_type_t buft) {
  1009. return 128;
  1010. GGML_UNUSED(buft);
  1011. }
  1012. /**
  1013. * @brief Calculates the allocation size required for a tensor in a CANN buffer.
  1014. *
  1015. * Computes the total allocation size needed for storing the tensor's data in a
  1016. * CANN buffer, considering any necessary padding or adjustments for quantized
  1017. * types.
  1018. *
  1019. * @param buft Pointer to the buffer type context (unused in this
  1020. * implementation).
  1021. * @param tensor Pointer to the tensor for which the allocation size is
  1022. * calculated.
  1023. * @return The total allocation size in bytes required for the tensor in the
  1024. * CANN buffer.
  1025. */
  1026. GGML_CALL static size_t ggml_backend_cann_buffer_type_get_alloc_size(
  1027. ggml_backend_buffer_type_t buft, const ggml_tensor* tensor) {
  1028. size_t size = ggml_nbytes(tensor);
  1029. int64_t ne0 = tensor->ne[0];
  1030. // last line must bigger than 32, because every single op deal at
  1031. // least 32 bytes.
  1032. // TODO: quantized type?
  1033. // int64_t line_size = ne0 * ggml_element_size(tensor);
  1034. // int64_t line_size_align_32 = (line_size + 31) & ~31;
  1035. // size += (line_size_align_32 - line_size);
  1036. // TODO: not support quantized yet.
  1037. // TODO: consider un-continue tensor.
  1038. if (ggml_is_quantized(tensor->type)) {
  1039. if (ne0 % MATRIX_ROW_PADDING != 0) {
  1040. size += ggml_row_size(
  1041. tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
  1042. }
  1043. }
  1044. return size;
  1045. GGML_UNUSED(buft);
  1046. }
  1047. /**
  1048. * @brief Interface for managing CANN buffer types in the GGML backend.
  1049. *
  1050. * Provides function pointers for allocating, querying properties, and managing
  1051. * memory for CANN buffer types in the GGML backend.
  1052. */
  1053. static ggml_backend_buffer_type_i ggml_backend_cann_buffer_type_interface = {
  1054. /* .get_name = */ ggml_backend_cann_buffer_type_name,
  1055. /* .alloc_buffer = */ ggml_backend_cann_buffer_type_alloc_buffer,
  1056. /* .get_alignment = */ ggml_backend_cann_buffer_type_get_alignment,
  1057. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  1058. /* .get_alloc_size = */ ggml_backend_cann_buffer_type_get_alloc_size,
  1059. /* .is_host = */ NULL,
  1060. };
  1061. /**
  1062. * @brief Retrieves the CANN buffer type for a specified device.
  1063. *
  1064. * This function initializes and returns the buffer type interface associated
  1065. * with the given device. It ensures thread-safe access using a mutex.
  1066. *
  1067. * @param device The device index for which to retrieve the buffer type.
  1068. * @return A pointer to the buffer type interface for the specified device, or
  1069. * nullptr if the device index is out of range.
  1070. */
  1071. GGML_CALL ggml_backend_buffer_type_t
  1072. ggml_backend_cann_buffer_type(int32_t device) {
  1073. static std::mutex mutex;
  1074. std::lock_guard<std::mutex> lock(mutex);
  1075. if (device >= ggml_backend_cann_get_device_count()) {
  1076. return nullptr;
  1077. }
  1078. static ggml_backend_buffer_type
  1079. ggml_backend_cann_buffer_types[GGML_CANN_MAX_DEVICES];
  1080. static bool ggml_backend_cann_buffer_type_initialized = false;
  1081. if (!ggml_backend_cann_buffer_type_initialized) {
  1082. for (int32_t i = 0; i < GGML_CANN_MAX_DEVICES; i++) {
  1083. ggml_backend_cann_buffer_types[i] = {
  1084. /* .iface = */ ggml_backend_cann_buffer_type_interface,
  1085. /* .context = */
  1086. new ggml_backend_cann_buffer_type_context{
  1087. i, "CANN" + std::to_string(i)},
  1088. };
  1089. }
  1090. ggml_backend_cann_buffer_type_initialized = true;
  1091. }
  1092. return &ggml_backend_cann_buffer_types[device];
  1093. }
  1094. /**
  1095. * @brief Retrieves the name associated with a CANN host buffer type.
  1096. *
  1097. * This function returns the descriptive name associated with the specified
  1098. * CANN host buffer type context.
  1099. *
  1100. * @param buft Pointer to the host buffer type context.
  1101. * @return Const pointer to the C-style string containing the name.
  1102. */
  1103. GGML_CALL static const char * ggml_backend_cann_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  1104. return "CANN_Host";
  1105. GGML_UNUSED(buft);
  1106. }
  1107. /**
  1108. * @brief Retrieves the name associated with a CANN host buffer.
  1109. *
  1110. * This function returns the descriptive name associated with the specified
  1111. * CANN host buffer context.
  1112. *
  1113. * @param buft Pointer to the host buffer context.
  1114. * @return Const pointer to the C-style string containing the name.
  1115. */
  1116. GGML_CALL static const char * ggml_backend_cann_host_buffer_name(ggml_backend_buffer_t buffer) {
  1117. return "CANN_Host";
  1118. GGML_UNUSED(buffer);
  1119. }
  1120. /**
  1121. * @brief Free resources associated with a CANN host buffer.
  1122. *
  1123. * This function frees the resources associated with a CANN host buffer, including
  1124. * its context.
  1125. *
  1126. * @param buffer The CANN host buffer to free.
  1127. */
  1128. GGML_CALL static void ggml_backend_cann_host_buffer_free(ggml_backend_buffer_t buffer) {
  1129. ACL_CHECK(aclrtFreeHost(buffer->context));
  1130. }
  1131. /**
  1132. * @brief Allocates a new CANN host buffer of the specified size.
  1133. *
  1134. * This function allocates a new CANN host buffer with the given size.
  1135. * @param size Size in bytes of the host buffer to allocate.
  1136. * @return Pointer to the allocated host buffer, or nullptr if allocation fails.
  1137. */
  1138. static void * ggml_cann_host_malloc(size_t size) {
  1139. if (getenv("GGML_CANN_NO_PINNED") != nullptr) {
  1140. return nullptr;
  1141. }
  1142. void * hostPtr = nullptr;
  1143. aclError err = aclrtMallocHost((void **) &hostPtr, size);
  1144. if (err != ACL_SUCCESS) {
  1145. GGML_CANN_LOG_WARN("%s: failed to allocate %.2f MiB of pinned memory: %s\n", __func__,
  1146. size / 1024.0 / 1024.0, aclGetRecentErrMsg());
  1147. return nullptr;
  1148. }
  1149. return hostPtr;
  1150. }
  1151. /**
  1152. * @brief Allocates a new CANN host buffer of the specified type and size.
  1153. *
  1154. * @param buft Pointer to the host buffer type context.
  1155. * @param size Size in bytes of the host buffer to allocate.
  1156. * @return Pointer to the allocated host buffer, or CPU buffer pointer if allocation fails.
  1157. */
  1158. GGML_CALL static ggml_backend_buffer_t ggml_backend_cann_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  1159. void * hostPtr = ggml_cann_host_malloc(size);
  1160. if (hostPtr == nullptr) {
  1161. // fallback to cpu buffer
  1162. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  1163. }
  1164. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(hostPtr, size);
  1165. buffer->buft = buft;
  1166. buffer->iface.get_name = ggml_backend_cann_host_buffer_name;
  1167. buffer->iface.free_buffer = ggml_backend_cann_host_buffer_free;
  1168. return buffer;
  1169. }
  1170. /**
  1171. * @brief Interface for managing CANN host buffer types in the GGML backend.
  1172. *
  1173. * Provides function pointers for allocating, querying properties, and managing
  1174. * memory for CANN buffer types in the GGML backend.
  1175. */
  1176. GGML_CALL ggml_backend_buffer_type_t ggml_backend_cann_host_buffer_type() {
  1177. static struct ggml_backend_buffer_type ggml_backend_cann_buffer_type_host = {
  1178. /* .iface = */ {
  1179. /* .get_name = */ ggml_backend_cann_host_buffer_type_name,
  1180. /* .alloc_buffer = */ ggml_backend_cann_host_buffer_type_alloc_buffer,
  1181. /* .get_alignment = */ ggml_backend_cpu_buffer_type()->iface.get_alignment,
  1182. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  1183. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  1184. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  1185. },
  1186. /* .context = */ nullptr,
  1187. };
  1188. return &ggml_backend_cann_buffer_type_host;
  1189. }
  1190. /**
  1191. * @brief Computes the forward operation for a given tensor using CANN
  1192. * operations.
  1193. *
  1194. * This function selects the appropriate CANN operation based on the type of
  1195. * operation specified in the tensor and performs the computation.
  1196. *
  1197. * @param ctx The CANN context containing necessary resources and
  1198. * configurations.
  1199. * @param dst The destination tensor where the result of the computation will be
  1200. * stored.
  1201. * @return true if the computation was successful; false otherwise.
  1202. */
  1203. static bool ggml_cann_compute_forward(ggml_backend_cann_context& ctx,
  1204. struct ggml_tensor* dst) {
  1205. switch (dst->op) {
  1206. case GGML_OP_REPEAT:
  1207. ggml_cann_repeat(ctx, dst);
  1208. break;
  1209. case GGML_OP_GET_ROWS:
  1210. ggml_cann_get_rows(ctx, dst);
  1211. break;
  1212. case GGML_OP_DUP:
  1213. ggml_cann_dup(ctx, dst);
  1214. break;
  1215. case GGML_OP_ADD:
  1216. ggml_cann_add(ctx, dst);
  1217. break;
  1218. case GGML_OP_ACC:
  1219. ggml_cann_acc(ctx, dst);
  1220. break;
  1221. case GGML_OP_MUL:
  1222. ggml_cann_mul_div<aclnnMulGetWorkspaceSize, aclnnMul>(ctx, dst);
  1223. break;
  1224. case GGML_OP_DIV:
  1225. ggml_cann_mul_div<aclnnDivGetWorkspaceSize, aclnnDiv>(ctx, dst);
  1226. break;
  1227. case GGML_OP_UNARY:
  1228. switch (ggml_get_unary_op(dst)) {
  1229. case GGML_UNARY_OP_GELU:
  1230. ggml_cann_activation<aclnnGeluGetWorkspaceSize, aclnnGelu>(
  1231. ctx, dst);
  1232. break;
  1233. case GGML_UNARY_OP_SILU:
  1234. ggml_cann_activation<aclnnSiluGetWorkspaceSize, aclnnSilu>(
  1235. ctx, dst);
  1236. break;
  1237. // TODO: Use faster gelu??
  1238. case GGML_UNARY_OP_GELU_QUICK:
  1239. ggml_cann_activation<aclnnGeluGetWorkspaceSize, aclnnGelu>(
  1240. ctx, dst);
  1241. break;
  1242. case GGML_UNARY_OP_TANH:
  1243. ggml_cann_activation<aclnnTanhGetWorkspaceSize, aclnnTanh>(
  1244. ctx, dst);
  1245. break;
  1246. case GGML_UNARY_OP_RELU:
  1247. ggml_cann_activation<aclnnReluGetWorkspaceSize, aclnnRelu>(
  1248. ctx, dst);
  1249. break;
  1250. case GGML_UNARY_OP_HARDSIGMOID:
  1251. ggml_cann_activation<aclnnHardsigmoidGetWorkspaceSize,
  1252. aclnnHardsigmoid>(ctx, dst);
  1253. break;
  1254. case GGML_UNARY_OP_HARDSWISH:
  1255. ggml_cann_activation<aclnnHardswishGetWorkspaceSize,
  1256. aclnnHardswish>(ctx, dst);
  1257. break;
  1258. default:
  1259. return false;
  1260. }
  1261. break;
  1262. case GGML_OP_NORM:
  1263. ggml_cann_norm(ctx, dst);
  1264. break;
  1265. case GGML_OP_GROUP_NORM:
  1266. ggml_cann_group_norm(ctx, dst);
  1267. break;
  1268. case GGML_OP_CONCAT:
  1269. ggml_cann_concat(ctx, dst);
  1270. break;
  1271. case GGML_OP_UPSCALE:
  1272. ggml_cann_upsample_nearest2d(ctx, dst);
  1273. break;
  1274. case GGML_OP_PAD:
  1275. ggml_cann_pad(ctx, dst);
  1276. break;
  1277. case GGML_OP_ARANGE:
  1278. ggml_cann_arange(ctx, dst);
  1279. break;
  1280. case GGML_OP_TIMESTEP_EMBEDDING:
  1281. ggml_cann_timestep_embedding(ctx, dst);
  1282. break;
  1283. case GGML_OP_LEAKY_RELU:
  1284. ggml_cann_leaky_relu(ctx, dst);
  1285. break;
  1286. case GGML_OP_RMS_NORM:
  1287. ggml_cann_rms_norm(ctx, dst);
  1288. break;
  1289. case GGML_OP_MUL_MAT:
  1290. ggml_cann_mul_mat(ctx, dst);
  1291. break;
  1292. case GGML_OP_MUL_MAT_ID:
  1293. return false;
  1294. case GGML_OP_SCALE:
  1295. ggml_cann_scale(ctx, dst);
  1296. break;
  1297. case GGML_OP_SQR:
  1298. ggml_cann_sqr(ctx, dst);
  1299. break;
  1300. case GGML_OP_CLAMP:
  1301. ggml_cann_clamp(ctx, dst);
  1302. break;
  1303. case GGML_OP_CPY:
  1304. ggml_cann_cpy(ctx, dst);
  1305. break;
  1306. case GGML_OP_CONT:
  1307. ggml_cann_dup(ctx, dst);
  1308. break;
  1309. case GGML_OP_NONE:
  1310. case GGML_OP_RESHAPE:
  1311. case GGML_OP_VIEW:
  1312. case GGML_OP_PERMUTE:
  1313. case GGML_OP_TRANSPOSE:
  1314. break;
  1315. case GGML_OP_DIAG_MASK_INF:
  1316. ggml_cann_diag_mask(ctx, dst, -INFINITY);
  1317. break;
  1318. case GGML_OP_SOFT_MAX:
  1319. ggml_cann_softmax(ctx, dst);
  1320. break;
  1321. case GGML_OP_ROPE:
  1322. ggml_cann_rope(ctx, dst);
  1323. break;
  1324. case GGML_OP_IM2COL:
  1325. ggml_cann_im2col(ctx, dst);
  1326. break;
  1327. case GGML_OP_POOL_2D:
  1328. ggml_cann_pool2d(ctx, dst);
  1329. break;
  1330. case GGML_OP_SUM_ROWS:
  1331. ggml_cann_sum_rows(ctx, dst);
  1332. break;
  1333. case GGML_OP_ARGSORT:
  1334. ggml_cann_argsort(ctx, dst);
  1335. break;
  1336. default:
  1337. return false;
  1338. }
  1339. return true;
  1340. }
  1341. // backend
  1342. /**
  1343. * @brief Retrieves the name associated with the CANN backend.
  1344. *
  1345. * This function returns the name assigned to the CANN backend, which is stored
  1346. * in the context of the provided backend structure.
  1347. *
  1348. * @param backend Pointer to the CANN backend structure.
  1349. * @return A pointer to a constant string representing the backend name.
  1350. */
  1351. GGML_CALL static const char* ggml_backend_cann_name(ggml_backend_t backend) {
  1352. ggml_backend_cann_context* cann_ctx =
  1353. (ggml_backend_cann_context*)backend->context;
  1354. return cann_ctx->name.c_str();
  1355. }
  1356. /**
  1357. * @brief Frees resources associated with the CANN backend.
  1358. *
  1359. * This function releases resources associated with the CANN backend context
  1360. * and resets the device associated with the backend to its initial state.
  1361. *
  1362. * @param backend Pointer to the CANN backend structure to be freed.
  1363. */
  1364. GGML_CALL static void ggml_backend_cann_free(ggml_backend_t backend) {
  1365. ggml_backend_cann_context* cann_ctx =
  1366. (ggml_backend_cann_context*)backend->context;
  1367. ACL_CHECK(aclrtSynchronizeDevice());
  1368. ACL_CHECK(aclrtResetDevice(cann_ctx->device));
  1369. // finalize when last backend freed.
  1370. if (cann_ctx->device == ggml_backend_cann_get_device_count() - 1) {
  1371. ACL_CHECK(aclFinalize());
  1372. }
  1373. delete cann_ctx;
  1374. delete backend;
  1375. }
  1376. /**
  1377. * @brief Retrieves the default buffer type associated with the CANN backend.
  1378. *
  1379. * This function returns the buffer type specific to the device associated
  1380. * with the CANN backend. It is used to allocate buffers for computations
  1381. * performed by the backend.
  1382. *
  1383. * @param backend Pointer to the CANN backend structure.
  1384. * @return Pointer to the buffer type structure for the CANN backend.
  1385. */
  1386. GGML_CALL static ggml_backend_buffer_type_t
  1387. ggml_backend_cann_get_default_buffer_type(ggml_backend_t backend) {
  1388. ggml_backend_cann_context* cann_ctx =
  1389. (ggml_backend_cann_context*)backend->context;
  1390. return ggml_backend_cann_buffer_type(cann_ctx->device);
  1391. }
  1392. /**
  1393. * @brief Sets tensor data asynchronously in the CANN backend.
  1394. *
  1395. * This function asynchronously sets tensor data in the CANN backend. Depending
  1396. * on the tensor type, it may perform data transformations before copying data
  1397. * to the device.
  1398. *
  1399. * @param backend Pointer to the CANN backend structure.
  1400. * @param tensor Pointer to the tensor structure to set data for.
  1401. * @param data Pointer to the host data to copy to the tensor.
  1402. * @param offset Offset in bytes within the host data.
  1403. * @param size Size of the data to copy in bytes.
  1404. */
  1405. GGML_CALL static void ggml_backend_cann_set_tensor_async(ggml_backend_t backend,
  1406. ggml_tensor *tensor,
  1407. const void *data,
  1408. size_t offset,
  1409. size_t size) {
  1410. ggml_backend_cann_context *cann_ctx =
  1411. (ggml_backend_cann_context *)backend->context;
  1412. if (!need_transform(tensor->type)) {
  1413. ACL_CHECK(aclrtMemcpyAsync((char *)tensor->data + offset, size, data,
  1414. size, ACL_MEMCPY_HOST_TO_DEVICE,
  1415. cann_ctx->stream()));
  1416. } else {
  1417. void *transform_buffer = malloc(size);
  1418. ggml_backend_cann_transform(tensor, data, transform_buffer);
  1419. #ifndef NDEBUG
  1420. void *check_buffer = malloc(size);
  1421. ggml_backend_cann_transform_back(tensor, transform_buffer,
  1422. check_buffer);
  1423. GGML_ASSERT(memcmp(data, check_buffer, size));
  1424. free(check_buffer);
  1425. #endif
  1426. ACL_CHECK(aclrtMemcpyAsync(
  1427. (char *)tensor->data + offset, size, transform_buffer, size,
  1428. ACL_MEMCPY_HOST_TO_DEVICE, cann_ctx->stream()));
  1429. ACL_CHECK(aclrtSynchronizeStream(cann_ctx->stream()));
  1430. free(transform_buffer);
  1431. }
  1432. }
  1433. GGML_CALL static void ggml_backend_cann_get_tensor_async(
  1434. ggml_backend_t backend, const ggml_tensor *tensor, void *data,
  1435. size_t offset, size_t size) {
  1436. ggml_backend_cann_context *cann_ctx =
  1437. (ggml_backend_cann_context *)backend->context;
  1438. ggml_backend_buffer_t buf =
  1439. tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  1440. GGML_ASSERT(buf->buft == ggml_backend_cann_buffer_type(cann_ctx->device) &&
  1441. "unsupported buffer type");
  1442. if (!need_transform(tensor->type)) {
  1443. ACL_CHECK(aclrtMemcpyAsync(data, size, (char *)tensor->data + offset,
  1444. size, ACL_MEMCPY_DEVICE_TO_HOST,
  1445. cann_ctx->stream()));
  1446. } else {
  1447. void *transform_buffer = malloc(size);
  1448. ACL_CHECK(aclrtMemcpyAsync(
  1449. transform_buffer, size, (char *)tensor->data + offset, size,
  1450. ACL_MEMCPY_DEVICE_TO_HOST, cann_ctx->stream()));
  1451. ACL_CHECK(aclrtSynchronizeStream(cann_ctx->stream()));
  1452. ggml_backend_cann_transform_back(tensor, transform_buffer, data);
  1453. free(transform_buffer);
  1454. }
  1455. }
  1456. /**
  1457. * @brief Asynchronously copies tensor data between CANN backends.
  1458. *
  1459. * This function copies tensor data asynchronously between two CANN backends. It
  1460. * checks if both tensors reside in CANN buffers and whether the devices support
  1461. * peer-to-peer access for direct copying. If not, it returns false.
  1462. *
  1463. * @param backend_src Pointer to the source CANN backend structure.
  1464. * @param backend_dst Pointer to the destination CANN backend structure.
  1465. * @param src Pointer to the source tensor to copy data from.
  1466. * @param dst Pointer to the destination tensor to copy data to.
  1467. * @return true if the copy operation succeeds, false otherwise.
  1468. */
  1469. GGML_CALL static bool ggml_backend_cann_cpy_tensor_async(
  1470. ggml_backend_t backend_src, ggml_backend_t backend_dst,
  1471. const ggml_tensor* src, ggml_tensor* dst) {
  1472. GGML_ASSERT(ggml_backend_is_cann(backend_src) ||
  1473. ggml_backend_is_cann(backend_dst));
  1474. if (!ggml_backend_buffer_is_cann(src->buffer) ||
  1475. !ggml_backend_buffer_is_cann(dst->buffer)) {
  1476. return false;
  1477. }
  1478. ggml_backend_buffer_t buf_src =
  1479. src->view_src ? src->view_src->buffer : src->buffer;
  1480. ggml_backend_buffer_t buf_dst =
  1481. dst->view_src ? dst->view_src->buffer : dst->buffer;
  1482. ggml_backend_cann_context* cann_ctx_src =
  1483. (ggml_backend_cann_context*)backend_src->context;
  1484. ggml_backend_cann_context* cann_ctx_dst =
  1485. (ggml_backend_cann_context*)backend_dst->context;
  1486. size_t copy_size = ggml_nbytes(dst);
  1487. if (backend_src != backend_dst) {
  1488. ggml_backend_cann_buffer_context* buf_ctx_src =
  1489. (ggml_backend_cann_buffer_context*)buf_src->context;
  1490. ggml_backend_cann_buffer_context* buf_ctx_dst =
  1491. (ggml_backend_cann_buffer_context*)buf_dst->context;
  1492. GGML_ASSERT(cann_ctx_src->device == buf_ctx_src->device);
  1493. GGML_ASSERT(cann_ctx_dst->device == buf_ctx_dst->device);
  1494. int32_t canAccessPeer = 0;
  1495. ACL_CHECK(aclrtDeviceCanAccessPeer(&canAccessPeer, cann_ctx_src->device,
  1496. cann_ctx_dst->device));
  1497. if (!canAccessPeer) {
  1498. return false;
  1499. }
  1500. // need open both directions for memcpyasync between devices.
  1501. ggml_cann_set_device(cann_ctx_dst->device);
  1502. ACL_CHECK(aclrtDeviceEnablePeerAccess(cann_ctx_src->device, 0));
  1503. ggml_cann_set_device(cann_ctx_src->device);
  1504. ACL_CHECK(aclrtDeviceEnablePeerAccess(cann_ctx_dst->device, 0));
  1505. ACL_CHECK(aclrtMemcpyAsync(dst->data, copy_size, src->data, copy_size,
  1506. ACL_MEMCPY_DEVICE_TO_DEVICE,
  1507. cann_ctx_src->stream()));
  1508. //TODO: workaround for Event didn`t work here.
  1509. aclrtSynchronizeStream(cann_ctx_src->stream());
  1510. } else {
  1511. // src and dst are on the same backend
  1512. ACL_CHECK(aclrtMemcpyAsync(dst->data, copy_size, src->data, copy_size,
  1513. ACL_MEMCPY_DEVICE_TO_DEVICE,
  1514. cann_ctx_dst->stream()));
  1515. }
  1516. return true;
  1517. }
  1518. /**
  1519. * @brief Synchronizes a CANN backend.
  1520. *
  1521. * This function synchronizes the specified CANN backend by waiting for all
  1522. * operations in its associated stream to complete.
  1523. *
  1524. * @param backend Pointer to the CANN backend structure to synchronize.
  1525. */
  1526. GGML_CALL static void ggml_backend_cann_synchronize(ggml_backend_t backend) {
  1527. ggml_backend_cann_context* cann_ctx =
  1528. (ggml_backend_cann_context*)backend->context;
  1529. ggml_cann_set_device(cann_ctx->device);
  1530. ACL_CHECK(aclrtSynchronizeStream(cann_ctx->stream()));
  1531. }
  1532. /**
  1533. * @brief Computes a computational graph using a CANN backend.
  1534. *
  1535. * This function computes the operations defined in the computational graph
  1536. * using the specified CANN backend.
  1537. *
  1538. * @param backend Pointer to the CANN backend structure to use for computation.
  1539. * @param cgraph Pointer to the computational graph structure containing nodes
  1540. * representing operations to be computed.
  1541. * @return enum ggml_status Returns GGML_STATUS_SUCCESS if computation
  1542. * completes successfully, otherwise an appropriate error status.
  1543. */
  1544. GGML_CALL static enum ggml_status ggml_backend_cann_graph_compute(
  1545. ggml_backend_t backend, ggml_cgraph* cgraph) {
  1546. ggml_backend_cann_context* cann_ctx =
  1547. (ggml_backend_cann_context*)backend->context;
  1548. ggml_cann_set_device(cann_ctx->device);
  1549. for (int i = 0; i < cgraph->n_nodes; i++) {
  1550. ggml_tensor* node = cgraph->nodes[i];
  1551. if (ggml_is_empty(node) || node->op == GGML_OP_NONE) {
  1552. continue;
  1553. }
  1554. bool ok = ggml_cann_compute_forward(*cann_ctx, node);
  1555. if (!ok) {
  1556. GGML_CANN_LOG_ERROR("%s: error: op not supported %s (%s)\n", __func__,
  1557. node->name, ggml_op_name(node->op));
  1558. }
  1559. GGML_ASSERT(ok);
  1560. }
  1561. return GGML_STATUS_SUCCESS;
  1562. }
  1563. /**
  1564. * @brief Checks if the CANN backend supports a specific operation.
  1565. *
  1566. * This function checks whether the specified operation is supported by the
  1567. * CANN backend.
  1568. *
  1569. * @param backend Pointer to the CANN backend structure to check support for
  1570. * the operation.
  1571. * @param op Pointer to the tensor representing the operation to check.
  1572. * @return bool Returns true if the operation is supported by the backend,
  1573. * otherwise false.
  1574. */
  1575. GGML_CALL static bool ggml_backend_cann_supports_op(ggml_backend_t backend,
  1576. const ggml_tensor* op) {
  1577. switch (op->op) {
  1578. case GGML_OP_UNARY:
  1579. switch (ggml_get_unary_op(op)) {
  1580. case GGML_UNARY_OP_GELU:
  1581. case GGML_UNARY_OP_SILU:
  1582. case GGML_UNARY_OP_RELU:
  1583. case GGML_UNARY_OP_HARDSIGMOID:
  1584. case GGML_UNARY_OP_HARDSWISH:
  1585. case GGML_UNARY_OP_GELU_QUICK:
  1586. case GGML_UNARY_OP_TANH:
  1587. return true;
  1588. default:
  1589. return false;
  1590. }
  1591. case GGML_OP_MUL_MAT: {
  1592. switch (op->src[0]->type) {
  1593. case GGML_TYPE_F16:
  1594. case GGML_TYPE_F32:
  1595. case GGML_TYPE_Q8_0:
  1596. // TODO: fix me
  1597. // Current groupsize should not be greater than k-1 in
  1598. // aclnnWeightQuantBatchMatmulV2GetWorkspaceSize().
  1599. case GGML_TYPE_Q4_0:
  1600. return true;
  1601. default:
  1602. return false;
  1603. }
  1604. }
  1605. case GGML_OP_MUL_MAT_ID:
  1606. return false;
  1607. // embedding
  1608. case GGML_OP_GET_ROWS: {
  1609. switch (op->src[0]->type) {
  1610. case GGML_TYPE_F32:
  1611. case GGML_TYPE_F16:
  1612. case GGML_TYPE_Q4_0:
  1613. case GGML_TYPE_Q8_0:
  1614. return true;
  1615. default:
  1616. return false;
  1617. }
  1618. } break;
  1619. case GGML_OP_CPY: {
  1620. switch (op->type) {
  1621. case GGML_TYPE_F32:
  1622. case GGML_TYPE_F16:
  1623. case GGML_TYPE_Q8_0:
  1624. case GGML_TYPE_Q4_0:
  1625. return true;
  1626. default:
  1627. return false;
  1628. }
  1629. }
  1630. case GGML_OP_DUP:
  1631. case GGML_OP_REPEAT:
  1632. case GGML_OP_CONCAT:
  1633. case GGML_OP_NONE:
  1634. case GGML_OP_RESHAPE:
  1635. case GGML_OP_VIEW:
  1636. case GGML_OP_PERMUTE:
  1637. case GGML_OP_TRANSPOSE:
  1638. case GGML_OP_NORM:
  1639. case GGML_OP_ADD:
  1640. case GGML_OP_MUL:
  1641. case GGML_OP_DIV:
  1642. case GGML_OP_RMS_NORM:
  1643. case GGML_OP_SCALE:
  1644. case GGML_OP_SQR:
  1645. case GGML_OP_CLAMP:
  1646. case GGML_OP_CONT:
  1647. case GGML_OP_DIAG_MASK_INF:
  1648. case GGML_OP_SOFT_MAX:
  1649. case GGML_OP_ROPE:
  1650. case GGML_OP_IM2COL:
  1651. case GGML_OP_POOL_2D:
  1652. case GGML_OP_SUM_ROWS:
  1653. case GGML_OP_ARGSORT:
  1654. case GGML_OP_ACC:
  1655. case GGML_OP_GROUP_NORM:
  1656. case GGML_OP_UPSCALE:
  1657. case GGML_OP_PAD:
  1658. case GGML_OP_ARANGE:
  1659. case GGML_OP_TIMESTEP_EMBEDDING:
  1660. case GGML_OP_LEAKY_RELU:
  1661. return true;
  1662. default:
  1663. return false;
  1664. }
  1665. GGML_UNUSED(backend);
  1666. }
  1667. /**
  1668. * @brief Checks if the backend buffer type is associated with the CANN backend.
  1669. *
  1670. * This function checks whether the provided backend buffer type is associated
  1671. * with the CANN backend based on the comparison of its name retrieval function
  1672. * pointer.
  1673. *
  1674. * @param buft Pointer to the backend buffer type to check.
  1675. * @return bool Returns true if the buffer type is associated with the CANN
  1676. * backend, otherwise false.
  1677. */
  1678. static bool ggml_backend_buft_is_cann(ggml_backend_buffer_type_t buft) {
  1679. return buft->iface.get_name == ggml_backend_cann_buffer_type_name;
  1680. }
  1681. /**
  1682. * @brief Checks if the CANN backend supports a specific backend buffer type.
  1683. *
  1684. * This function determines whether the CANN backend supports the given backend
  1685. * buffer type by comparing the device context of the backend and buffer type.
  1686. * It returns true if the devices are same between the backend context and
  1687. * buffer type context.
  1688. *
  1689. * @param backend Pointer to the CANN backend.
  1690. * @param buft Pointer to the backend buffer type to check.
  1691. * @return bool Returns true if the CANN backend supports the buffer type,
  1692. * otherwise false.
  1693. */
  1694. GGML_CALL static bool ggml_backend_cann_supports_buft(
  1695. ggml_backend_t backend, ggml_backend_buffer_type_t buft) {
  1696. if (ggml_backend_buft_is_cann(buft)) {
  1697. ggml_backend_cann_context * cann_ctx =
  1698. (ggml_backend_cann_context *)backend->context;
  1699. ggml_backend_cann_buffer_type_context * buft_ctx =
  1700. (ggml_backend_cann_buffer_type_context *)buft->context;
  1701. return buft_ctx->device == cann_ctx->device;
  1702. }
  1703. return false;
  1704. }
  1705. /**
  1706. * @brief Determines if a tensor operation should be offloaded to the CANN
  1707. * backend.
  1708. *
  1709. * This function checks if a given tensor operation should be offloaded to the
  1710. * CANN backend based on the operation type and the size of the tensor. It
  1711. * returns true if the second dimension (ne[1]) of the tensor is greater than or
  1712. * equal to the minimum batch size and the operation is not GGML_OP_GET_ROWS.
  1713. *
  1714. * @param backend Pointer to the CANN backend.
  1715. * @param op Pointer to the tensor operation to check.
  1716. * @return bool Returns true if the operation should be offloaded, otherwise
  1717. * false.
  1718. */
  1719. GGML_CALL static bool ggml_backend_cann_offload_op(ggml_backend_t backend,
  1720. const ggml_tensor* op) {
  1721. const int min_batch_size = 32;
  1722. GGML_UNUSED(backend);
  1723. return op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS;
  1724. }
  1725. /**
  1726. * @brief Creates a new event for the CANN backend.
  1727. *
  1728. * This function initializes a new event for the CANN backend by setting the
  1729. * device and creating an ACL runtime event. The created event is then wrapped
  1730. * in a ggml_backend_event structure and returned.
  1731. *
  1732. * @param backend Pointer to the CANN backend.
  1733. * @return ggml_backend_event_t Returns a pointer to the new event structure.
  1734. */
  1735. static ggml_backend_event_t ggml_backend_cann_event_new(
  1736. ggml_backend_t backend) {
  1737. ggml_backend_cann_context* cann_ctx =
  1738. (ggml_backend_cann_context*)backend->context;
  1739. ggml_cann_set_device(cann_ctx->device);
  1740. aclrtEvent event;
  1741. ACL_CHECK(aclrtCreateEvent(&event));
  1742. return new ggml_backend_event{
  1743. /* .backend = */ backend,
  1744. /* .context = */ event,
  1745. };
  1746. }
  1747. /**
  1748. * @brief Frees a CANN backend event.
  1749. *
  1750. * This function destroys the ACL runtime event associated with the given CANN
  1751. * backend event and then deletes the event structure itself.
  1752. *
  1753. * @param event Pointer to the event structure to be freed.
  1754. */
  1755. static void ggml_backend_cann_event_free(ggml_backend_event_t event) {
  1756. ACL_CHECK(aclrtDestroyEvent((aclrtEvent)event->context));
  1757. delete event;
  1758. }
  1759. /**
  1760. * @brief Records an event on the CANN backend stream.
  1761. *
  1762. * This function records the given event on the ACL runtime stream associated
  1763. * with the backend context.
  1764. *
  1765. * @param event Pointer to the event structure to be recorded.
  1766. */
  1767. static void ggml_backend_cann_event_record(ggml_backend_event_t event) {
  1768. ggml_backend_cann_context* cann_ctx =
  1769. (ggml_backend_cann_context*)event->backend->context;
  1770. ACL_CHECK(aclrtRecordEvent((aclrtEvent)event->context, cann_ctx->stream()));
  1771. }
  1772. /**
  1773. * @brief Waits for a recorded event to complete on the CANN backend stream.
  1774. *
  1775. * This function makes the given backend wait for the event to complete on its
  1776. * ACL runtime stream.
  1777. *
  1778. * @param backend Pointer to the backend structure.
  1779. * @param event Pointer to the event structure that the backend needs to wait
  1780. * for.
  1781. */
  1782. static void ggml_backend_cann_event_wait(ggml_backend_t backend,
  1783. ggml_backend_event_t event) {
  1784. ggml_backend_cann_context* cann_ctx =
  1785. (ggml_backend_cann_context*)backend->context;
  1786. if (ggml_backend_is_cann(event->backend)) {
  1787. ACL_CHECK(aclrtStreamWaitEvent(cann_ctx->stream(),
  1788. (aclrtEvent)event->context));
  1789. } else {
  1790. GGML_ABORT("fatal error");
  1791. }
  1792. }
  1793. /**
  1794. * @brief Synchronizes the given event on the CANN backend.
  1795. *
  1796. * This function waits for the specified event to complete on the ACL runtime.
  1797. *
  1798. * @param event Pointer to the event structure to be synchronized.
  1799. */
  1800. static void ggml_backend_cann_event_synchronize(ggml_backend_event_t event) {
  1801. ACL_CHECK(aclrtSynchronizeEvent((aclrtEvent)event->context));
  1802. }
  1803. /**
  1804. * @brief Structure defining the interface for the CANN backend.
  1805. *
  1806. * This structure contains function pointers for various operations
  1807. * supported by the CANN backend, including name retrieval, memory
  1808. * management, tensor operations, synchronization, and event handling.
  1809. */
  1810. static ggml_backend_i ggml_backend_cann_interface = {
  1811. /* .get_name = */ ggml_backend_cann_name,
  1812. /* .free = */ ggml_backend_cann_free,
  1813. /* .get_default_buffer_type = */ ggml_backend_cann_get_default_buffer_type,
  1814. /* .set_tensor_async = */ ggml_backend_cann_set_tensor_async,
  1815. /* .get_tensor_async = */ ggml_backend_cann_get_tensor_async,
  1816. /* .cpy_tensor_async = */ ggml_backend_cann_cpy_tensor_async,
  1817. /* .synchronize = */ ggml_backend_cann_synchronize,
  1818. /* .graph_plan_create = */ NULL,
  1819. /* .graph_plan_free = */ NULL,
  1820. /* .graph_plan_update = */ NULL,
  1821. /* .graph_plan_compute = */ NULL,
  1822. /* .graph_compute = */ ggml_backend_cann_graph_compute,
  1823. /* .supports_op = */ ggml_backend_cann_supports_op,
  1824. /* .supports_buft = */ ggml_backend_cann_supports_buft,
  1825. /* .offload_op = */ ggml_backend_cann_offload_op,
  1826. /* .event_new = */ ggml_backend_cann_event_new,
  1827. /* .event_free = */ ggml_backend_cann_event_free,
  1828. /* .event_record = */ ggml_backend_cann_event_record,
  1829. /* .event_wait = */ ggml_backend_cann_event_wait,
  1830. /* .event_synchronize = */ ggml_backend_cann_event_synchronize,
  1831. };
  1832. /**
  1833. * @brief Return the hardcoded GUID for the CANN backend.
  1834. *
  1835. * This function returns a static GUID which uniquely identifies the CANN
  1836. * backend.
  1837. *
  1838. * @return A pointer to the static GUID.
  1839. */
  1840. static ggml_guid_t ggml_backend_cann_guid() {
  1841. static ggml_guid guid = {0xa1, 0x94, 0xaf, 0xac, 0xbd, 0x4f, 0x47, 0x34,
  1842. 0xbe, 0x1a, 0x9e, 0x71, 0x1f, 0x9e, 0xed, 0x64};
  1843. return &guid;
  1844. }
  1845. GGML_CALL ggml_backend_t ggml_backend_cann_init(int32_t device) {
  1846. aclInit(nullptr);
  1847. if (device < 0 || device >= ggml_backend_cann_get_device_count()) {
  1848. GGML_CANN_LOG_ERROR("%s: error: invalid device %d\n", __func__, device);
  1849. return nullptr;
  1850. }
  1851. ggml_backend_cann_context* ctx = new ggml_backend_cann_context(device);
  1852. if (ctx == nullptr) {
  1853. GGML_CANN_LOG_ERROR("%s: error: failed to allocate context\n", __func__);
  1854. return nullptr;
  1855. }
  1856. ggml_cann_set_device(ctx->device);
  1857. ggml_backend_t cann_backend =
  1858. new ggml_backend{/* .guid = */ ggml_backend_cann_guid(),
  1859. /* .interface = */ ggml_backend_cann_interface,
  1860. /* .context = */ ctx};
  1861. return cann_backend;
  1862. }
  1863. GGML_CALL bool ggml_backend_is_cann(ggml_backend_t backend) {
  1864. return backend != NULL &&
  1865. ggml_guid_matches(backend->guid, ggml_backend_cann_guid());
  1866. }
  1867. GGML_CALL int32_t ggml_backend_cann_get_device_count() {
  1868. return ggml_cann_info().device_count;
  1869. }
  1870. GGML_CALL void ggml_backend_cann_get_device_description(
  1871. int32_t device, char* description, size_t description_size) {
  1872. ggml_cann_set_device(device);
  1873. const char* soc_name = aclrtGetSocName();
  1874. snprintf(description, description_size, "%s", soc_name);
  1875. }
  1876. GGML_CALL void ggml_backend_cann_get_device_memory(int32_t device, size_t* free,
  1877. size_t* total) {
  1878. ggml_cann_set_device(device);
  1879. ACL_CHECK(aclrtGetMemInfo(ACL_HBM_MEM, free, total));
  1880. }
  1881. // backend registry
  1882. /**
  1883. * @brief Initializes a CANN backend based on the provided parameters.
  1884. *
  1885. * This function initializes a CANN backend using the device index and then
  1886. * initializes the backend using `ggml_backend_cann_init`.
  1887. *
  1888. * @param params Parameters for initialization (unused in this implementation).
  1889. * @param user_data User data containing the device index to initialize the
  1890. * backend.
  1891. * @return ggml_backend_t The initialized CANN backend.
  1892. */
  1893. GGML_CALL static ggml_backend_t ggml_backend_reg_cann_init(const char* params,
  1894. void* user_data) {
  1895. ggml_backend_t cann_backend =
  1896. ggml_backend_cann_init((int)(intptr_t)user_data);
  1897. return cann_backend;
  1898. GGML_UNUSED(params);
  1899. }
  1900. extern "C" GGML_CALL int ggml_backend_cann_reg_devices();
  1901. /**
  1902. * @brief Registers CANN (Ascend) devices as backend options.
  1903. *
  1904. * This function initializes ACL, retrieves the number of available CANN
  1905. * devices, and registers each device as a backend option using
  1906. * `ggml_backend_register`. Each device is given a unique name based on
  1907. * `GGML_CANN_NAME` followed by its index.
  1908. *
  1909. * @return int The number of CANN devices registered.
  1910. */
  1911. GGML_CALL int ggml_backend_cann_reg_devices() {
  1912. uint32_t device_count = ggml_backend_cann_get_device_count();
  1913. // initialization
  1914. for (uint32_t i = 0; i < device_count; i++) {
  1915. char name[128];
  1916. snprintf(name, sizeof(name), "CANN%d", i);
  1917. ggml_backend_register(name, ggml_backend_reg_cann_init,
  1918. ggml_backend_cann_buffer_type(i),
  1919. (void*)(intptr_t)i);
  1920. }
  1921. return device_count;
  1922. }