ggml-cann.cpp 74 KB

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