1
0

ggml-kompute.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  1. #include "ggml.h"
  2. #include "ggml-backend.h"
  3. #include "ggml-backend-impl.h"
  4. #include "ggml-kompute.h"
  5. // These are generated at build time by cmake custom command
  6. #include "shaderop_scale.h"
  7. #include "shaderop_scale_8.h"
  8. #include "shaderop_add.h"
  9. #include "shaderop_addrow.h"
  10. #include "shaderop_mul.h"
  11. #include "shaderop_silu.h"
  12. #include "shaderop_relu.h"
  13. #include "shaderop_gelu.h"
  14. #include "shaderop_softmax.h"
  15. #include "shaderop_norm.h"
  16. #include "shaderop_rmsnorm.h"
  17. #include "shaderop_diagmask.h"
  18. #include "shaderop_mul_mat_f16.h"
  19. #include "shaderop_mul_mat_q8_0.h"
  20. #include "shaderop_mul_mat_q4_0.h"
  21. #include "shaderop_mul_mat_q4_1.h"
  22. #include "shaderop_mul_mat_q6_k.h"
  23. #include "shaderop_mul_mat_mat_f32.h"
  24. #include "shaderop_getrows_f16.h"
  25. #include "shaderop_getrows_q4_0.h"
  26. #include "shaderop_getrows_q4_1.h"
  27. #include "shaderop_getrows_q6_k.h"
  28. #include "shaderop_rope_f16.h"
  29. #include "shaderop_rope_f32.h"
  30. #include "shaderop_cpy_f16_f16.h"
  31. #include "shaderop_cpy_f16_f32.h"
  32. #include "shaderop_cpy_f32_f16.h"
  33. #include "shaderop_cpy_f32_f32.h"
  34. #include <algorithm>
  35. #include <array>
  36. #include <cassert>
  37. #include <cstdint>
  38. #include <cstdio>
  39. #include <cstring>
  40. #include <iostream>
  41. #include <memory>
  42. #include <stdexcept>
  43. #include <string>
  44. #include <unordered_map>
  45. #include <utility>
  46. #include <vector>
  47. #include <kompute/Kompute.hpp>
  48. #include <vulkan/vulkan.hpp>
  49. #ifdef __linux__
  50. #include <cstdlib> // for setenv
  51. #endif
  52. #define QK4_0 32
  53. #define QR4_0 2
  54. #define QK4_1 32
  55. #define QK_NL 16
  56. typedef ggml_fp16_t half;
  57. static std::string ggml_kompute_format_name(int device) {
  58. return "Kompute" + std::to_string(device);
  59. }
  60. struct ggml_kompute_context {
  61. int device;
  62. std::string name;
  63. std::shared_ptr<vk::DescriptorPool> pool;
  64. ggml_kompute_context(int device)
  65. : device(device), name(ggml_kompute_format_name(device)) {}
  66. };
  67. // FIXME: It would be good to consolidate the kompute manager and the kompute context into one object
  68. // and consolidate the init functions and simplify object lifetime management. As it currently stands,
  69. // we *have* to have the kompute manager no matter what for device discovery, but the kompute context
  70. // is only created when a device is set and vulkan is explicitly turned on.
  71. static ggml_kompute_context *s_kompute_context = nullptr;
  72. class kompute_manager {
  73. kp::Manager *s_mgr = nullptr;
  74. public:
  75. kp::Manager *operator()() {
  76. if (s_mgr && !s_mgr->hasInstance()) {
  77. destroy();
  78. }
  79. if (!s_mgr) {
  80. s_mgr = new kp::Manager;
  81. }
  82. return s_mgr;
  83. }
  84. void destroy() {
  85. delete s_mgr;
  86. s_mgr = nullptr;
  87. }
  88. };
  89. static kompute_manager komputeManager;
  90. struct ggml_vk_memory {
  91. void *data = nullptr;
  92. size_t size = 0;
  93. vk::DeviceMemory *primaryMemory = nullptr;
  94. vk::Buffer *primaryBuffer = nullptr;
  95. vk::DeviceMemory *stagingMemory = nullptr;
  96. vk::Buffer *stagingBuffer = nullptr;
  97. };
  98. #ifdef __linux__
  99. __attribute__((constructor))
  100. static void enable_sam() {
  101. setenv("RADV_PERFTEST", "sam", false);
  102. }
  103. #endif
  104. static bool ggml_vk_checkPhysicalDeviceFeatures(vk::PhysicalDevice physical_device) {
  105. vk::PhysicalDeviceFeatures availableFeatures;
  106. physical_device.getFeatures(&availableFeatures);
  107. if (!availableFeatures.shaderInt16)
  108. return false;
  109. vk::PhysicalDeviceVulkan11Features availableFeatures11;
  110. vk::PhysicalDeviceVulkan12Features availableFeatures12;
  111. availableFeatures11.pNext = &availableFeatures12;
  112. availableFeatures12.pNext = nullptr;
  113. vk::PhysicalDeviceFeatures2 features2;
  114. features2.pNext = &availableFeatures11;
  115. physical_device.getFeatures2(&features2);
  116. if (!availableFeatures11.uniformAndStorageBuffer16BitAccess ||
  117. !availableFeatures11.storageBuffer16BitAccess) {
  118. return false;
  119. }
  120. if (!availableFeatures12.storageBuffer8BitAccess ||
  121. !availableFeatures12.uniformAndStorageBuffer8BitAccess ||
  122. !availableFeatures12.shaderFloat16 ||
  123. !availableFeatures12.shaderInt8) {
  124. return false;
  125. }
  126. return true;
  127. }
  128. static const char * ggml_vk_getVendorName(uint32_t vendorID) {
  129. switch (vendorID) {
  130. case 0x10DE:
  131. return "nvidia";
  132. case 0x1002:
  133. return "amd";
  134. case 0x8086:
  135. return "intel";
  136. default:
  137. return "unknown";
  138. }
  139. }
  140. static std::vector<ggml_vk_device> ggml_vk_available_devices_internal(size_t memoryRequired) {
  141. std::vector<ggml_vk_device> results;
  142. if (!komputeManager()->hasVulkan() || !komputeManager()->hasInstance())
  143. return results;
  144. std::vector<vk::PhysicalDevice> physical_devices;
  145. try {
  146. physical_devices = komputeManager()->listDevices();
  147. } catch (vk::SystemError & err) {
  148. std::cerr << __func__ << ": ignoring Vulkan exception: " << err.what() << "\n";
  149. return results;
  150. }
  151. uint32_t deviceCount = physical_devices.size();
  152. if (deviceCount == 0)
  153. return results;
  154. std::unordered_map<std::string, size_t> count_by_name;
  155. for (uint32_t i = 0; i < deviceCount; i++) {
  156. const auto & physical_device = physical_devices[i];
  157. VkPhysicalDeviceProperties dev_props = physical_device.getProperties();
  158. VkPhysicalDeviceMemoryProperties memoryProperties = physical_device.getMemoryProperties();
  159. const uint32_t major = VK_VERSION_MAJOR(dev_props.apiVersion);
  160. const uint32_t minor = VK_VERSION_MINOR(dev_props.apiVersion);
  161. if (major < 1 || minor < 2)
  162. continue;
  163. if (!ggml_vk_checkPhysicalDeviceFeatures(physical_device))
  164. continue;
  165. size_t heapSize = 0;
  166. for (uint32_t j = 0; j < memoryProperties.memoryHeapCount; ++j) {
  167. VkMemoryHeap heap = memoryProperties.memoryHeaps[j];
  168. if (heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
  169. heapSize = heap.size;
  170. break;
  171. }
  172. }
  173. if (heapSize < memoryRequired)
  174. continue;
  175. auto ext_props = physical_device.enumerateDeviceExtensionProperties();
  176. bool has_maintenance4 = false;
  177. // Check if maintenance4 is supported
  178. for (const auto & properties : ext_props) {
  179. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  180. has_maintenance4 = true;
  181. }
  182. }
  183. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  184. vk::PhysicalDeviceProperties2 dev_props2;
  185. vk::PhysicalDeviceMaintenance3Properties dev_props3;
  186. vk::PhysicalDeviceMaintenance4Properties dev_props4;
  187. dev_props2.pNext = &dev_props3;
  188. dev_props3.pNext = &subgroup_props;
  189. if (has_maintenance4) {
  190. subgroup_props.pNext = &dev_props4;
  191. }
  192. physical_device.getProperties2(&dev_props2);
  193. if (subgroup_props.subgroupSize < 32)
  194. continue;
  195. ggml_vk_device d;
  196. d.index = i;
  197. d.type = dev_props.deviceType;
  198. d.heapSize = heapSize;
  199. d.vendor = strdup(ggml_vk_getVendorName(dev_props.vendorID));
  200. d.subgroupSize = subgroup_props.subgroupSize;
  201. d.bufferAlignment = dev_props.limits.minStorageBufferOffsetAlignment;
  202. if (has_maintenance4) {
  203. d.maxAlloc = std::min(dev_props3.maxMemoryAllocationSize, dev_props4.maxBufferSize);
  204. } else {
  205. d.maxAlloc = dev_props3.maxMemoryAllocationSize;
  206. }
  207. std::string name(dev_props.deviceName);
  208. size_t n_idx = ++count_by_name[name];
  209. if (n_idx > 1) {
  210. name += " (" + std::to_string(n_idx) + ")";
  211. }
  212. d.name = strdup(name.c_str());
  213. results.push_back(d);
  214. }
  215. std::stable_sort(results.begin(), results.end(),
  216. [](const ggml_vk_device& lhs, const ggml_vk_device& rhs) -> bool {
  217. if (lhs.type != rhs.type) {
  218. if (lhs.type == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) return true;
  219. if (rhs.type == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) return false;
  220. if (lhs.type == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) return true;
  221. if (rhs.type == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) return false;
  222. }
  223. return lhs.heapSize < rhs.heapSize;
  224. }
  225. );
  226. return results;
  227. }
  228. // public API returns a C-style array
  229. ggml_vk_device * ggml_vk_available_devices(size_t memoryRequired, size_t * count) {
  230. auto devices = ggml_vk_available_devices_internal(memoryRequired);
  231. *count = devices.size();
  232. if (devices.empty()) {
  233. return nullptr;
  234. }
  235. size_t nbytes = sizeof (ggml_vk_device) * (devices.size());
  236. auto * arr = static_cast<ggml_vk_device *>(malloc(nbytes));
  237. memcpy(arr, devices.data(), nbytes);
  238. return arr;
  239. }
  240. static void ggml_vk_filterByVendor(std::vector<ggml_vk_device>& devices, const std::string& targetVendor) {
  241. devices.erase(
  242. std::remove_if(devices.begin(), devices.end(),
  243. [&targetVendor](const ggml_vk_device& device) {
  244. return device.vendor != targetVendor;
  245. }),
  246. devices.end()
  247. );
  248. }
  249. static void ggml_vk_filterByName(std::vector<ggml_vk_device>& devices, const std::string& targetName) {
  250. devices.erase(
  251. std::remove_if(devices.begin(), devices.end(),
  252. [&targetName](const ggml_vk_device& device) {
  253. return device.name != targetName;
  254. }),
  255. devices.end()
  256. );
  257. }
  258. static bool ggml_vk_get_device(ggml_vk_device * device, size_t memoryRequired, const std::string & name) {
  259. if (name.empty())
  260. return false;
  261. auto devices = ggml_vk_available_devices_internal(memoryRequired);
  262. if (name == "amd" || name == "nvidia" || name == "intel") {
  263. ggml_vk_filterByVendor(devices, name);
  264. } else if (name != "gpu") {
  265. ggml_vk_filterByName(devices, name);
  266. }
  267. if (devices.empty())
  268. return false;
  269. *device = devices.front();
  270. return true;
  271. }
  272. bool ggml_vk_get_device(ggml_vk_device * device, size_t memoryRequired, const char * name) {
  273. return ggml_vk_get_device(device, memoryRequired, std::string(name));
  274. }
  275. bool ggml_vk_has_vulkan() {
  276. return komputeManager()->hasVulkan();
  277. }
  278. bool ggml_vk_has_device() {
  279. return komputeManager()->hasDevice();
  280. }
  281. ggml_vk_device ggml_vk_current_device() {
  282. if (!komputeManager()->hasDevice())
  283. return ggml_vk_device();
  284. auto devices = ggml_vk_available_devices_internal(0);
  285. ggml_vk_filterByName(devices, komputeManager()->physicalDevice()->getProperties().deviceName.data());
  286. GGML_ASSERT(!devices.empty());
  287. return devices.front();
  288. }
  289. static
  290. void ggml_vk_allocate_descriptor_pool(struct ggml_kompute_context * ctx, size_t size) {
  291. std::vector<vk::DescriptorPoolSize> descriptorPoolSizes = {
  292. vk::DescriptorPoolSize(
  293. vk::DescriptorType::eStorageBuffer,
  294. 3 * size // Descriptor count is number of possible tensors to pass into an algorithm
  295. )
  296. };
  297. vk::DescriptorPoolCreateInfo descriptorPoolInfo(
  298. vk::DescriptorPoolCreateFlags(),
  299. size, // Max sets
  300. static_cast<uint32_t>(descriptorPoolSizes.size()),
  301. descriptorPoolSizes.data());
  302. ctx->pool = std::make_shared<vk::DescriptorPool>();
  303. vk::Result r = komputeManager()->device()->createDescriptorPool(
  304. &descriptorPoolInfo, nullptr, ctx->pool.get());
  305. if (r != vk::Result::eSuccess)
  306. std::cerr << "Error allocating descriptor pool" << vk::to_string(r);
  307. }
  308. static
  309. void ggml_vk_free_descriptor_pool(struct ggml_kompute_context * ctx) {
  310. if (ctx->pool) {
  311. komputeManager()->device()->destroy(
  312. *ctx->pool,
  313. (vk::Optional<const vk::AllocationCallbacks>)nullptr);
  314. ctx->pool = nullptr;
  315. }
  316. }
  317. static
  318. vk::Buffer *ggml_vk_allocate_buffer(size_t size) {
  319. vk::BufferCreateInfo bufferCreateInfo;
  320. bufferCreateInfo.size = size;
  321. bufferCreateInfo.usage = vk::BufferUsageFlagBits::eStorageBuffer |
  322. vk::BufferUsageFlagBits::eTransferSrc |
  323. vk::BufferUsageFlagBits::eTransferDst;
  324. bufferCreateInfo.sharingMode = vk::SharingMode::eExclusive;
  325. vk::Buffer *vkBuffer = new vk::Buffer;
  326. vk::Result r = komputeManager()->device()->createBuffer(&bufferCreateInfo, nullptr, vkBuffer);
  327. if (r != vk::Result::eSuccess)
  328. std::cerr << "Error allocating buffer " << vk::to_string(r) << std::endl;
  329. return vkBuffer;
  330. }
  331. static
  332. vk::DeviceMemory *ggml_vk_allocate(size_t size, vk::MemoryPropertyFlags flags, vk::MemoryRequirements requirements, bool *isHostVisible) {
  333. uint32_t memoryTypeIndex = -1;
  334. bool memoryTypeIndexFound = false;
  335. vk::PhysicalDeviceMemoryProperties memoryProperties = komputeManager()->physicalDevice()->getMemoryProperties();
  336. for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) {
  337. const vk::MemoryType &memoryType = memoryProperties.memoryTypes[i];
  338. const vk::MemoryHeap &memoryHeap = memoryProperties.memoryHeaps[memoryType.heapIndex];
  339. if (memoryHeap.size < size) {
  340. continue;
  341. }
  342. if (requirements.memoryTypeBits & (1 << i)) {
  343. if (((memoryProperties.memoryTypes[i]).propertyFlags &
  344. flags) == flags) {
  345. memoryTypeIndex = i;
  346. memoryTypeIndexFound = true;
  347. if (isHostVisible && (memoryProperties.memoryTypes[i].propertyFlags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  348. *isHostVisible = true;
  349. }
  350. break;
  351. }
  352. }
  353. }
  354. if (!memoryTypeIndexFound) {
  355. throw std::runtime_error(
  356. "Memory type index for buffer creation not found");
  357. }
  358. vk::MemoryAllocateInfo allocInfo;
  359. allocInfo.allocationSize = size;
  360. allocInfo.memoryTypeIndex = memoryTypeIndex;
  361. vk::DeviceMemory *vkDeviceMemory = new vk::DeviceMemory;
  362. vk::Result r = komputeManager()->device()->allocateMemory(&allocInfo, nullptr, vkDeviceMemory);
  363. if (r != vk::Result::eSuccess) {
  364. std::cerr << "Error allocating memory " << vk::to_string(r) << std::endl;
  365. throw std::runtime_error("Error allocating vulkan memory.");
  366. }
  367. return vkDeviceMemory;
  368. }
  369. static size_t ggml_vk_aligned_offset(ggml_backend_buffer_t buffer, size_t offset) {
  370. size_t minStorageBufferOffsetAlignment = ggml_backend_buffer_get_alignment(buffer);
  371. // If offset is already aligned, return it directly
  372. if (offset % minStorageBufferOffsetAlignment == 0) {
  373. return offset;
  374. }
  375. // Otherwise, return the largest multiple of minStorageBufferOffsetAlignment less than offset
  376. return (offset / minStorageBufferOffsetAlignment) * minStorageBufferOffsetAlignment;
  377. }
  378. static ggml_vk_memory ggml_vk_allocate(size_t size) {
  379. ggml_vk_memory memory;
  380. bool isHostVisible = false;
  381. {
  382. memory.primaryBuffer = ggml_vk_allocate_buffer(size);
  383. vk::MemoryRequirements memoryRequirements = komputeManager()->device()->getBufferMemoryRequirements(*memory.primaryBuffer);
  384. vk::MemoryPropertyFlags memoryPropertyFlags = vk::MemoryPropertyFlagBits::eDeviceLocal;
  385. memory.primaryMemory = ggml_vk_allocate(size, memoryPropertyFlags, memoryRequirements, &isHostVisible);
  386. komputeManager()->device()->bindBufferMemory(*memory.primaryBuffer, *memory.primaryMemory, 0);
  387. if (isHostVisible) {
  388. vk::Result r = komputeManager()->device()->mapMemory(*memory.primaryMemory, 0, size, vk::MemoryMapFlags(), &memory.data);
  389. if (r != vk::Result::eSuccess)
  390. std::cerr << "Error mapping memory" << vk::to_string(r);
  391. }
  392. }
  393. if (!isHostVisible) {
  394. memory.stagingBuffer = ggml_vk_allocate_buffer(size);
  395. vk::MemoryRequirements memoryRequirements = komputeManager()->device()->getBufferMemoryRequirements(*memory.stagingBuffer);
  396. vk::MemoryPropertyFlags memoryPropertyFlags = vk::MemoryPropertyFlagBits::eHostVisible |
  397. vk::MemoryPropertyFlagBits::eHostCoherent |
  398. vk::MemoryPropertyFlagBits::eHostCached;
  399. memory.stagingMemory = ggml_vk_allocate(size, memoryPropertyFlags, memoryRequirements, &isHostVisible);
  400. komputeManager()->device()->bindBufferMemory(*memory.stagingBuffer, *memory.stagingMemory, 0);
  401. vk::Result r = komputeManager()->device()->mapMemory(*memory.stagingMemory, 0, size, vk::MemoryMapFlags(), &memory.data);
  402. if (r != vk::Result::eSuccess)
  403. std::cerr << "Error mapping memory" << vk::to_string(r);
  404. }
  405. memory.size = size;
  406. return memory;
  407. }
  408. static void ggml_vk_free_memory(ggml_vk_memory &memory)
  409. {
  410. komputeManager()->device()->destroy(
  411. *memory.primaryBuffer,
  412. (vk::Optional<const vk::AllocationCallbacks>)nullptr);
  413. if (memory.stagingBuffer) {
  414. komputeManager()->device()->destroy(
  415. *memory.stagingBuffer,
  416. (vk::Optional<const vk::AllocationCallbacks>)nullptr);
  417. }
  418. komputeManager()->device()->freeMemory(
  419. *memory.primaryMemory,
  420. (vk::Optional<const vk::AllocationCallbacks>)nullptr);
  421. if (memory.stagingMemory) {
  422. komputeManager()->device()->freeMemory(
  423. *memory.stagingMemory,
  424. (vk::Optional<const vk::AllocationCallbacks>)nullptr);
  425. }
  426. }
  427. static const char * ggml_backend_kompute_buffer_type_get_name(ggml_backend_buffer_type_t buft);
  428. static
  429. ggml_vk_memory * ggml_vk_find_tensor(const struct ggml_tensor * t, uint64_t & offset) {
  430. ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer;
  431. // compatibility with ggml-backend
  432. GGML_ASSERT(buffer && buffer->buft->iface.get_name == ggml_backend_kompute_buffer_type_get_name);
  433. ggml_vk_memory * buf_ctx = static_cast<ggml_vk_memory *>(buffer->context);
  434. const intptr_t ioffs = intptr_t(t->data) - intptr_t(buf_ctx->data);
  435. GGML_ASSERT(ioffs >= 0 && ioffs + int64_t(ggml_nbytes(t)) <= int64_t(buffer->size));
  436. offset = uint64_t(ioffs);
  437. return buf_ctx;
  438. }
  439. static
  440. const std::shared_ptr<kp::Tensor> ggml_vk_get_tensor(const struct ggml_tensor * t, uint32_t * alignedOffset = nullptr) {
  441. uint64_t originalOffset = 0;
  442. auto * res = ggml_vk_find_tensor(t, originalOffset);
  443. if (!res) {
  444. static std::shared_ptr<kp::Tensor> nullTensor = nullptr;
  445. return nullTensor;
  446. }
  447. // Create a tensor whose memory will be composed of our buffers at the correct offset
  448. const size_t nelements = ggml_nelements(t);
  449. size_t nbytes = ggml_nbytes(t);
  450. size_t vulkanOffset = ggml_vk_aligned_offset(t->buffer, originalOffset);
  451. if (alignedOffset) {
  452. *alignedOffset = originalOffset - vulkanOffset;
  453. nbytes += *alignedOffset;
  454. }
  455. return komputeManager()->tensor(
  456. t->data,
  457. nelements,
  458. nbytes, kp::Tensor::TensorDataTypes::eFloat,
  459. res->primaryMemory, res->primaryBuffer,
  460. res->stagingMemory, res->stagingBuffer,
  461. vulkanOffset);
  462. }
  463. static std::vector<uint32_t> getSpirvShader(const unsigned char* rawData, size_t size) {
  464. if (size % sizeof(uint32_t) != 0) {
  465. throw std::runtime_error("Invalid size: must be divisible by sizeof(uint32_t)");
  466. }
  467. const uint32_t* data_ptr = reinterpret_cast<const uint32_t*>(rawData);
  468. size_t count = size / sizeof(uint32_t);
  469. return std::vector<uint32_t>(data_ptr, data_ptr + count);
  470. }
  471. inline static
  472. uint32_t safe_divide(uint32_t a, uint32_t b) {
  473. if (b <= 1) {
  474. return a;
  475. }
  476. if ((a % b) != 0) {
  477. fprintf(stderr, "((%u %% %u) == %u) != 0\n", a, b, a % b);
  478. GGML_ASSERT(!"safe_divide result would've had remainder");
  479. }
  480. return a / b;
  481. }
  482. static void ggml_vk_add(
  483. kp::Sequence& seq,
  484. const std::shared_ptr<kp::Tensor>& inA,
  485. const std::shared_ptr<kp::Tensor>& inB,
  486. const std::shared_ptr<kp::Tensor>& out,
  487. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  488. int32_t ne00, int32_t ne01, int32_t ne02, int32_t ne03,
  489. int32_t nb00, int32_t nb01, int32_t nb02, int32_t nb03,
  490. int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
  491. int32_t nb10, int32_t nb11, int32_t nb12, int32_t nb13,
  492. int32_t ne0,
  493. int32_t nb0, int32_t nb1, int32_t nb2, int32_t nb3
  494. ) {
  495. const static auto spirv = getSpirvShader(kp::shader_data::op_add_comp_spv,
  496. kp::shader_data::op_add_comp_spv_len);
  497. struct PushConstants {
  498. uint32_t inAOff, inBOff, outOff;
  499. int32_t ne00;
  500. int32_t nb00, nb01, nb02, nb03;
  501. int32_t ne10, ne11, ne12, ne13;
  502. int32_t nb10, nb11, nb12, nb13;
  503. int32_t ne0;
  504. int32_t nb0, nb1, nb2, nb3;
  505. } const pushConsts {
  506. safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  507. ne00,
  508. nb00, nb01, nb02, nb03,
  509. ne10, ne11, ne12, ne13,
  510. nb10, nb11, nb12, nb13,
  511. ne0,
  512. nb0, nb1, nb2, nb3
  513. };
  514. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  515. if (!komputeManager()->hasAlgorithm(__func__)) {
  516. s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts});
  517. } else {
  518. s_algo = komputeManager()->getAlgorithm(__func__);
  519. s_algo->setTensors({inA, inB, out});
  520. s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
  521. s_algo->setPushConstants<PushConstants>({pushConsts});
  522. s_algo->updateDescriptors(s_kompute_context->pool.get());
  523. }
  524. seq.record<kp::OpAlgoDispatch>(s_algo);
  525. }
  526. static void ggml_vk_addrow(kp::Sequence& seq,
  527. const std::shared_ptr<kp::Tensor>& inA,
  528. const std::shared_ptr<kp::Tensor>& inB,
  529. const std::shared_ptr<kp::Tensor>& out,
  530. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  531. uint32_t size, uint32_t row = 0) {
  532. const static auto spirv = getSpirvShader(kp::shader_data::op_addrow_comp_spv,
  533. kp::shader_data::op_addrow_comp_spv_len);
  534. struct PushConstants {
  535. uint32_t inAOff, inBOff, outOff;
  536. uint32_t row;
  537. } const pushConsts {
  538. safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  539. row
  540. };
  541. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  542. if (!komputeManager()->hasAlgorithm(__func__))
  543. s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {size}, {}, {pushConsts});
  544. else {
  545. s_algo = komputeManager()->getAlgorithm(__func__);
  546. s_algo->setTensors({inA, inB, out});
  547. s_algo->setWorkgroup({size});
  548. s_algo->setPushConstants<PushConstants>({pushConsts});
  549. s_algo->updateDescriptors(s_kompute_context->pool.get());
  550. }
  551. seq.record<kp::OpAlgoDispatch>(s_algo);
  552. }
  553. static void ggml_vk_mul(
  554. kp::Sequence& seq,
  555. const std::shared_ptr<kp::Tensor>& inA,
  556. const std::shared_ptr<kp::Tensor>& inB,
  557. const std::shared_ptr<kp::Tensor>& out,
  558. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  559. int32_t ne00, int32_t ne01, int32_t ne02, int32_t ne03,
  560. int32_t nb00, int32_t nb01, int32_t nb02, int32_t nb03,
  561. int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
  562. int32_t nb10, int32_t nb11, int32_t nb12, int32_t nb13,
  563. int32_t ne0,
  564. int32_t nb0, int32_t nb1, int32_t nb2, int32_t nb3
  565. ) {
  566. const static auto spirv = getSpirvShader(kp::shader_data::op_mul_comp_spv,
  567. kp::shader_data::op_mul_comp_spv_len);
  568. struct PushConstants {
  569. uint32_t inAOff, inBOff, outOff;
  570. int32_t ne00;
  571. int32_t nb00, nb01, nb02, nb03;
  572. int32_t ne10, ne11, ne12, ne13;
  573. int32_t nb10, nb11, nb12, nb13;
  574. int32_t ne0;
  575. int32_t nb0, nb1, nb2, nb3;
  576. } const pushConsts {
  577. safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  578. ne00,
  579. nb00, nb01, nb02, nb03,
  580. ne10, ne11, ne12, ne13,
  581. nb10, nb11, nb12, nb13,
  582. ne0,
  583. nb0, nb1, nb2, nb3
  584. };
  585. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  586. if (!komputeManager()->hasAlgorithm(__func__)) {
  587. s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts});
  588. } else {
  589. s_algo = komputeManager()->getAlgorithm(__func__);
  590. s_algo->setTensors({inA, inB, out});
  591. s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
  592. s_algo->setPushConstants<PushConstants>({pushConsts});
  593. s_algo->updateDescriptors(s_kompute_context->pool.get());
  594. }
  595. seq.record<kp::OpAlgoDispatch>(s_algo);
  596. }
  597. static void ggml_vk_scale(kp::Sequence& seq,
  598. const std::shared_ptr<kp::Tensor>& in,
  599. const std::shared_ptr<kp::Tensor>& out,
  600. uint32_t inOff, uint32_t outOff,
  601. uint32_t size, float scale) {
  602. const static auto spirv_1 = getSpirvShader(
  603. kp::shader_data::op_scale_comp_spv, kp::shader_data::op_scale_comp_spv_len
  604. );
  605. const static auto spirv_8 = getSpirvShader(
  606. kp::shader_data::op_scale_8_comp_spv, kp::shader_data::op_scale_8_comp_spv_len
  607. );
  608. struct PushConstants {
  609. uint32_t inOff, outOff;
  610. float scale;
  611. } const pushConsts {
  612. safe_divide(inOff, 4), safe_divide(outOff, 4),
  613. scale
  614. };
  615. const auto * spirv = &spirv_1;
  616. std::string name(__func__);
  617. if (size % 8 == 0) {
  618. size /= 8;
  619. name += "_8";
  620. spirv = &spirv_8;
  621. }
  622. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  623. if (!komputeManager()->hasAlgorithm(name)) {
  624. s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, *spirv, {size}, {}, {pushConsts});
  625. } else {
  626. s_algo = komputeManager()->getAlgorithm(name);
  627. s_algo->setTensors({in, out});
  628. s_algo->setWorkgroup({size});
  629. s_algo->setPushConstants<PushConstants>({pushConsts});
  630. s_algo->updateDescriptors(s_kompute_context->pool.get());
  631. }
  632. seq.record<kp::OpAlgoDispatch>(s_algo);
  633. }
  634. static void ggml_vk_xxlu(
  635. const std::vector<uint32_t>& spirv, const char * suffix, kp::Sequence& seq,
  636. const std::shared_ptr<kp::Tensor>& in,
  637. const std::shared_ptr<kp::Tensor>& out,
  638. uint32_t inOff, uint32_t outOff,
  639. uint32_t size
  640. ) {
  641. struct PushConstants {
  642. uint32_t inOff, outOff;
  643. } const pushConsts {
  644. safe_divide(inOff, 4), safe_divide(outOff, 4),
  645. };
  646. auto name = std::string(__func__) + "_" + suffix;
  647. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  648. if (!komputeManager()->hasAlgorithm(name)) {
  649. s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, spirv, {size}, {}, {pushConsts});
  650. } else {
  651. s_algo = komputeManager()->getAlgorithm(name);
  652. s_algo->setTensors({in, out});
  653. s_algo->setWorkgroup({size});
  654. s_algo->setPushConstants<PushConstants>({pushConsts});
  655. s_algo->updateDescriptors(s_kompute_context->pool.get());
  656. }
  657. seq.record<kp::OpAlgoDispatch>(s_algo);
  658. }
  659. template <typename... Args>
  660. static void ggml_vk_silu(Args&&... args) {
  661. const static auto spirv = getSpirvShader(kp::shader_data::op_silu_comp_spv,
  662. kp::shader_data::op_silu_comp_spv_len);
  663. ggml_vk_xxlu(spirv, "silu", std::forward<Args>(args)...);
  664. }
  665. template <typename... Args>
  666. static void ggml_vk_relu(Args&&... args) {
  667. const static auto spirv = getSpirvShader(kp::shader_data::op_relu_comp_spv,
  668. kp::shader_data::op_relu_comp_spv_len);
  669. ggml_vk_xxlu(spirv, "relu", std::forward<Args>(args)...);
  670. }
  671. template <typename... Args>
  672. static void ggml_vk_gelu(Args&&... args) {
  673. const static auto spirv = getSpirvShader(kp::shader_data::op_gelu_comp_spv,
  674. kp::shader_data::op_gelu_comp_spv_len);
  675. ggml_vk_xxlu(spirv, "gelu", std::forward<Args>(args)...);
  676. }
  677. static void ggml_vk_soft_max(
  678. kp::Sequence& seq,
  679. const std::shared_ptr<kp::Tensor>& inA,
  680. const std::shared_ptr<kp::Tensor>& inB,
  681. const std::shared_ptr<kp::Tensor>& out,
  682. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  683. int32_t ne00, int32_t ne01, int32_t ne02, uint32_t ne03,
  684. float scale
  685. ) {
  686. const static auto spirv = getSpirvShader(kp::shader_data::op_softmax_comp_spv,
  687. kp::shader_data::op_softmax_comp_spv_len);
  688. struct PushConstants {
  689. uint32_t inAOff, inBOff, outOff;
  690. int32_t ne00, ne01, ne02;
  691. float scale;
  692. int32_t mask;
  693. } pushConsts {
  694. safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  695. ne00, ne01, ne02,
  696. scale,
  697. bool(inB)
  698. };
  699. auto & inB_ = inB ? inB : inA;
  700. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  701. if (!komputeManager()->hasAlgorithm(__func__)) {
  702. // FIXME: The softmax kernel needs to be fixed to use the subgroupsize which can vary by device
  703. const uint32_t local_x = 32;
  704. s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB_, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {local_x}, {pushConsts});
  705. } else {
  706. s_algo = komputeManager()->getAlgorithm(__func__);
  707. s_algo->setTensors({inA, inB_, out});
  708. s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
  709. s_algo->setPushConstants<PushConstants>({pushConsts});
  710. s_algo->updateDescriptors(s_kompute_context->pool.get());
  711. }
  712. seq.record<kp::OpAlgoDispatch>(s_algo);
  713. }
  714. static void ggml_vk_norm_(
  715. const std::vector<uint32_t>& spirv, const char * suffix, kp::Sequence& seq,
  716. const std::shared_ptr<kp::Tensor>& in,
  717. const std::shared_ptr<kp::Tensor>& out,
  718. uint32_t inOff, uint32_t outOff,
  719. int32_t ne00, int32_t nb01,
  720. int32_t nrows, float epsilon
  721. ) {
  722. GGML_ASSERT(nb01%sizeof(float) == 0);
  723. GGML_ASSERT(ne00%sizeof(float) == 0);
  724. struct PushConstants {
  725. uint32_t inOff, outOff;
  726. uint32_t ne00, nb01;
  727. float eps;
  728. } pushConsts {
  729. safe_divide(inOff, 4), safe_divide(outOff, 4),
  730. (uint32_t)ne00, (uint32_t)nb01, epsilon
  731. };
  732. auto name = std::string(__func__) + "_" + suffix;
  733. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  734. if (!komputeManager()->hasAlgorithm(name)) {
  735. s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, spirv, {(uint32_t)nrows}, {}, {pushConsts});
  736. } else {
  737. s_algo = komputeManager()->getAlgorithm(name);
  738. s_algo->setTensors({in, out});
  739. s_algo->setWorkgroup({(uint32_t)nrows});
  740. s_algo->setPushConstants<PushConstants>({pushConsts});
  741. s_algo->updateDescriptors(s_kompute_context->pool.get());
  742. }
  743. seq.record<kp::OpAlgoDispatch>(s_algo);
  744. }
  745. template <typename... Args>
  746. static void ggml_vk_norm(Args&&... args) {
  747. const static auto spirv = getSpirvShader(kp::shader_data::op_norm_comp_spv,
  748. kp::shader_data::op_norm_comp_spv_len);
  749. ggml_vk_norm_(spirv, "norm", std::forward<Args>(args)...);
  750. }
  751. template <typename... Args>
  752. static void ggml_vk_rms_norm(Args&&... args) {
  753. const static auto spirv = getSpirvShader(kp::shader_data::op_rmsnorm_comp_spv,
  754. kp::shader_data::op_rmsnorm_comp_spv_len);
  755. ggml_vk_norm_(spirv, "rms", std::forward<Args>(args)...);
  756. }
  757. static void ggml_vk_diag_mask_inf(kp::Sequence& seq,
  758. const std::shared_ptr<kp::Tensor>& in,
  759. const std::shared_ptr<kp::Tensor>& out,
  760. uint32_t inOff, uint32_t outOff,
  761. uint32_t n_past,
  762. int32_t ne00, int32_t ne01, int32_t ne02) {
  763. const static auto spirv = getSpirvShader(kp::shader_data::op_diagmask_comp_spv,
  764. kp::shader_data::op_diagmask_comp_spv_len);
  765. struct PushConstants {
  766. uint32_t inOff, outOff;
  767. uint32_t n_past;
  768. int32_t ne00, ne01;
  769. } pushConsts {
  770. safe_divide(inOff, 4), safe_divide(outOff, 4),
  771. n_past,
  772. ne00, ne01
  773. };
  774. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  775. if (!komputeManager()->hasAlgorithm(__func__))
  776. s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {in, out}, spirv, {unsigned(ne00), unsigned(ne01), unsigned(ne02)}, {}, {pushConsts});
  777. else {
  778. s_algo = komputeManager()->getAlgorithm(__func__);
  779. s_algo->setTensors({in, out});
  780. s_algo->setWorkgroup({unsigned(ne00), unsigned(ne01), unsigned(ne02)});
  781. s_algo->setPushConstants<PushConstants>({pushConsts});
  782. s_algo->updateDescriptors(s_kompute_context->pool.get());
  783. }
  784. seq.record<kp::OpAlgoDispatch>(s_algo);
  785. }
  786. static void ggml_vk_mul_mat_f16(
  787. kp::Sequence& seq,
  788. const std::shared_ptr<kp::Tensor>& inA,
  789. const std::shared_ptr<kp::Tensor>& inB,
  790. const std::shared_ptr<kp::Tensor>& out,
  791. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  792. int32_t ne00, int32_t ne01, int32_t ne02,
  793. uint32_t nb00, uint32_t nb01, uint32_t nb02,
  794. int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
  795. uint32_t nb10, uint32_t nb11, uint32_t nb12,
  796. int32_t ne0, int32_t ne1,
  797. uint32_t r2, uint32_t r3
  798. ) {
  799. const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_f16_comp_spv,
  800. kp::shader_data::op_mul_mat_f16_comp_spv_len);
  801. struct PushConstants {
  802. uint32_t inAOff, inBOff, outOff;
  803. int32_t ne00, ne01, ne02;
  804. uint32_t nb00, nb01, nb02;
  805. int32_t ne10, ne11, ne12;
  806. uint32_t nb10, nb11, nb12;
  807. int32_t ne0, ne1;
  808. uint32_t r2, r3;
  809. } pushConsts {
  810. safe_divide(inAOff, 2), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  811. ne00, ne01, ne02,
  812. nb00, nb01, nb02,
  813. ne10, ne11, ne12,
  814. nb10, nb11, nb12,
  815. ne0, ne1,
  816. r2, r3
  817. };
  818. const unsigned ny = unsigned((ne11 + 4 - 1)/4);
  819. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  820. if (!komputeManager()->hasAlgorithm(__func__)) {
  821. const uint32_t local_x = ggml_vk_current_device().subgroupSize * 2;
  822. s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned(ne01), ny, unsigned(ne12*ne13)}, {local_x}, {pushConsts});
  823. } else {
  824. s_algo = komputeManager()->getAlgorithm(__func__);
  825. s_algo->setTensors({inA, inB, out});
  826. s_algo->setWorkgroup({unsigned(ne01), ny, unsigned(ne12*ne13)});
  827. s_algo->setPushConstants<PushConstants>({pushConsts});
  828. s_algo->updateDescriptors(s_kompute_context->pool.get());
  829. }
  830. seq.record<kp::OpAlgoDispatch>(s_algo);
  831. }
  832. static void ggml_vk_mul_mat_mat_f32(kp::Sequence& seq,
  833. const std::shared_ptr<kp::Tensor>& inA,
  834. const std::shared_ptr<kp::Tensor>& inB,
  835. const std::shared_ptr<kp::Tensor>& out,
  836. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  837. int32_t ne00, int32_t ne01, int32_t ne02,
  838. uint32_t nb01, uint32_t nb02,
  839. int32_t ne11, int32_t ne12,
  840. uint32_t nb11, uint32_t nb12,
  841. uint32_t nb1, uint32_t nb2) {
  842. const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_mat_f32_comp_spv,
  843. kp::shader_data::op_mul_mat_mat_f32_comp_spv_len);
  844. struct PushConstants {
  845. uint32_t inAOff, inBOff, outOff;
  846. int32_t ne00, ne01, ne02, ne11, ne12;
  847. uint32_t nb01, nb02;
  848. uint32_t nb11, nb12;
  849. uint32_t nb1, nb2;
  850. } pushConsts {
  851. safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  852. ne00, ne01, ne02, ne11, ne12,
  853. nb01, nb02, nb11, nb12,
  854. nb1, nb2
  855. };
  856. const uint32_t local_x = ggml_vk_current_device().subgroupSize;
  857. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  858. if (!komputeManager()->hasAlgorithm(__func__)) {
  859. s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(),
  860. {inA, inB, out}, spirv,
  861. {unsigned(ne01),
  862. unsigned(ne11),
  863. unsigned(std::max(ne12, ne02))
  864. },
  865. {local_x},
  866. {pushConsts});
  867. } else {
  868. s_algo = komputeManager()->getAlgorithm(__func__);
  869. s_algo->setTensors({inA, inB, out});
  870. s_algo->setWorkgroup({unsigned(ne01),
  871. unsigned(ne11),
  872. unsigned(std::max(ne12, ne02)),
  873. });
  874. s_algo->setPushConstants<PushConstants>({pushConsts});
  875. s_algo->updateDescriptors(s_kompute_context->pool.get());
  876. }
  877. seq.record<kp::OpAlgoDispatch>(s_algo);
  878. }
  879. static void ggml_vk_mul_mat_impl(
  880. const std::vector<uint32_t>& spirv, const char * suffix, uint32_t block_size, kp::Sequence& seq,
  881. const std::shared_ptr<kp::Tensor>& inA,
  882. const std::shared_ptr<kp::Tensor>& inB,
  883. const std::shared_ptr<kp::Tensor>& out,
  884. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  885. int32_t ne00, int32_t ne01, int32_t ne02,
  886. int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
  887. int32_t ne0, int32_t ne1,
  888. uint32_t r2, uint32_t r3
  889. ) {
  890. struct PushConstants {
  891. uint32_t inAOff, inBOff, outOff;
  892. int32_t ne00, ne01, ne02;
  893. int32_t ne10, ne12;
  894. int32_t ne0, ne1;
  895. uint32_t r2, r3;
  896. } pushConsts {
  897. safe_divide(inAOff, block_size), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  898. ne00, ne01, ne02,
  899. ne10, ne12,
  900. ne0, ne1,
  901. r2, r3
  902. };
  903. auto name = std::string(__func__) + "_" + suffix;
  904. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  905. if (!komputeManager()->hasAlgorithm(name)) {
  906. const uint32_t local_x = ggml_vk_current_device().subgroupSize * 2;
  907. s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(name, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned((ne01 + 7)/8), unsigned(ne11), unsigned(ne12*ne13)}, {local_x}, {pushConsts});
  908. } else {
  909. s_algo = komputeManager()->getAlgorithm(name);
  910. s_algo->setTensors({inA, inB, out});
  911. s_algo->setWorkgroup({unsigned((ne01 + 7)/8), unsigned(ne11), unsigned(ne12*ne13)});
  912. s_algo->setPushConstants<PushConstants>({pushConsts});
  913. s_algo->updateDescriptors(s_kompute_context->pool.get());
  914. }
  915. seq.record<kp::OpAlgoDispatch>(s_algo);
  916. }
  917. template <typename... Args>
  918. static void ggml_vk_mul_mat_q4_0(Args&&... args) {
  919. const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q4_0_comp_spv,
  920. kp::shader_data::op_mul_mat_q4_0_comp_spv_len);
  921. ggml_vk_mul_mat_impl(spirv, "q4_0", 1/*We access blocks unaligned*/, std::forward<Args>(args)...);
  922. }
  923. template <typename... Args>
  924. static void ggml_vk_mul_mat_q4_1(Args&&... args) {
  925. const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q4_1_comp_spv,
  926. kp::shader_data::op_mul_mat_q4_1_comp_spv_len);
  927. ggml_vk_mul_mat_impl(spirv, "q4_1", 1/*We access blocks unaligned*/, std::forward<Args>(args)...);
  928. }
  929. template <typename... Args>
  930. static void ggml_vk_mul_mat_q8_0(Args&&... args) {
  931. const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q8_0_comp_spv,
  932. kp::shader_data::op_mul_mat_q8_0_comp_spv_len);
  933. ggml_vk_mul_mat_impl(spirv, "q8_0", 1/*We access blocks unaligned*/, std::forward<Args>(args)...);
  934. }
  935. static void ggml_vk_mul_mat_q6_k(
  936. kp::Sequence& seq,
  937. const std::shared_ptr<kp::Tensor>& inA,
  938. const std::shared_ptr<kp::Tensor>& inB,
  939. const std::shared_ptr<kp::Tensor>& out,
  940. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  941. int32_t ne00, int32_t ne10, int32_t ne0, int32_t ne1,
  942. int32_t ne01, int32_t ne11, int32_t ne12, int32_t ne02
  943. ) {
  944. const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q6_k_comp_spv,
  945. kp::shader_data::op_mul_mat_q6_k_comp_spv_len);
  946. struct PushConstants {
  947. uint32_t inAOff, inBOff, outOff;
  948. int32_t ne00, ne10, ne0, ne1, ne01, gqa;
  949. } pushConsts {
  950. inAOff, safe_divide(inBOff, 4), safe_divide(outOff, 4),
  951. ne00, ne10, ne0, ne1, ne01, ne12/ne02
  952. };
  953. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  954. if (!komputeManager()->hasAlgorithm(__func__)) {
  955. const uint32_t local_x = ggml_vk_current_device().subgroupSize * 2;
  956. s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned((ne01 + 1)/2), unsigned(ne11), unsigned(ne12)}, {local_x}, {pushConsts});
  957. } else {
  958. s_algo = komputeManager()->getAlgorithm(__func__);
  959. s_algo->setTensors({inA, inB, out});
  960. s_algo->setWorkgroup({unsigned((ne01 + 1)/2), unsigned(ne11), unsigned(ne12)});
  961. s_algo->setPushConstants<PushConstants>({pushConsts});
  962. s_algo->updateDescriptors(s_kompute_context->pool.get());
  963. }
  964. seq.record<kp::OpAlgoDispatch>(s_algo);
  965. }
  966. static void ggml_vk_get_rows(
  967. const std::vector<uint32_t>& spirv,
  968. const char * suffix,
  969. unsigned element_size, unsigned qk,
  970. kp::Sequence& seq,
  971. const std::shared_ptr<kp::Tensor>& inA,
  972. const std::shared_ptr<kp::Tensor>& inB,
  973. const std::shared_ptr<kp::Tensor>& out,
  974. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  975. int32_t ne00, int32_t nb01, int32_t nb1,
  976. uint32_t size
  977. ) {
  978. GGML_ASSERT(nb01%element_size == 0);
  979. GGML_ASSERT(nb1%sizeof(float) == 0);
  980. if (qk) GGML_ASSERT(ne00%qk == 0);
  981. struct PushConstants {
  982. uint32_t inAOff, inBOff, outOff;
  983. int32_t ne00, nb01, nb1;
  984. } pushConsts {
  985. safe_divide(inAOff, element_size), safe_divide(inBOff, 4), safe_divide(outOff, 4),
  986. ne00, nb01, nb1
  987. };
  988. auto name = std::string(__func__) + "_" + suffix;
  989. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  990. if (!komputeManager()->hasAlgorithm(name)) {
  991. s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {size}, {}, {pushConsts});
  992. } else {
  993. s_algo = komputeManager()->getAlgorithm(name);
  994. s_algo->setTensors({inA, inB, out});
  995. s_algo->setWorkgroup({size});
  996. s_algo->setPushConstants<PushConstants>({pushConsts});
  997. s_algo->updateDescriptors(s_kompute_context->pool.get());
  998. }
  999. seq.record<kp::OpAlgoDispatch>(s_algo);
  1000. }
  1001. template <typename... Args>
  1002. static void ggml_vk_get_rows_f16(Args&&... args) {
  1003. const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_f16_comp_spv,
  1004. kp::shader_data::op_getrows_f16_comp_spv_len);
  1005. ggml_vk_get_rows(spirv, "f16", sizeof(half), 0, std::forward<Args>(args)...);
  1006. }
  1007. template <typename... Args>
  1008. static void ggml_vk_get_rows_q4_0(Args&&... args) {
  1009. const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_q4_0_comp_spv,
  1010. kp::shader_data::op_getrows_q4_0_comp_spv_len);
  1011. ggml_vk_get_rows(spirv, "q4_0", 1/*We access blocks unaligned*/, QK4_0, std::forward<Args>(args)...);
  1012. }
  1013. template <typename... Args>
  1014. static void ggml_vk_get_rows_q4_1(Args&&... args) {
  1015. const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_q4_1_comp_spv,
  1016. kp::shader_data::op_getrows_q4_1_comp_spv_len);
  1017. ggml_vk_get_rows(spirv, "q4_1", 1/*We access blocks unaligned*/, QK4_1, std::forward<Args>(args)...);
  1018. }
  1019. template <typename... Args>
  1020. static void ggml_vk_get_rows_q6_k(Args&&... args) {
  1021. const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_q6_k_comp_spv,
  1022. kp::shader_data::op_getrows_q6_k_comp_spv_len);
  1023. ggml_vk_get_rows(spirv, "q6_k", 1/*We access blocks unaligned*/, QK_NL, std::forward<Args>(args)...);
  1024. }
  1025. static void ggml_vk_rope(
  1026. kp::Sequence& seq,
  1027. const std::shared_ptr<kp::Tensor>& inA,
  1028. const std::shared_ptr<kp::Tensor>& inB,
  1029. const std::shared_ptr<kp::Tensor>& out,
  1030. uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
  1031. ggml_type src0t, int32_t n_dims, int32_t mode, int32_t n_orig_ctx,
  1032. float freq_base, float freq_scale, float ext_factor, float attn_factor, float beta_fast, float beta_slow,
  1033. int32_t ne01, int32_t ne02, int32_t ne03,
  1034. uint32_t nb00, uint32_t nb01, uint32_t nb02, uint32_t nb03,
  1035. int32_t ne0,
  1036. uint32_t nb0, uint32_t nb1, uint32_t nb2, uint32_t nb3
  1037. ) {
  1038. GGML_ASSERT(src0t == GGML_TYPE_F16 || src0t == GGML_TYPE_F32);
  1039. static const auto spirv_f16 = getSpirvShader(
  1040. kp::shader_data::op_rope_f16_comp_spv, kp::shader_data::op_rope_f16_comp_spv_len
  1041. );
  1042. static const auto spirv_f32 = getSpirvShader(
  1043. kp::shader_data::op_rope_f32_comp_spv, kp::shader_data::op_rope_f32_comp_spv_len
  1044. );
  1045. int type_size = src0t == GGML_TYPE_F16 ? 2 : 4;
  1046. GGML_ASSERT(nb03 % type_size == 0);
  1047. GGML_ASSERT(nb02 % type_size == 0);
  1048. GGML_ASSERT(nb01 % type_size == 0);
  1049. GGML_ASSERT(nb00 % type_size == 0);
  1050. GGML_ASSERT(nb3 % type_size == 0);
  1051. GGML_ASSERT(nb2 % type_size == 0);
  1052. GGML_ASSERT(nb1 % type_size == 0);
  1053. GGML_ASSERT(nb0 % type_size == 0);
  1054. struct PushConstants {
  1055. uint32_t inAOff, inBOff, outOff;
  1056. int32_t n_dims, mode, n_orig_ctx;
  1057. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  1058. uint32_t nb00, nb01, nb02, nb03;
  1059. int32_t ne0;
  1060. uint32_t nb0, nb1, nb2, nb3;
  1061. } pushConsts {
  1062. safe_divide(inAOff, type_size), safe_divide(inBOff, 4), safe_divide(outOff, type_size),
  1063. n_dims, mode, n_orig_ctx,
  1064. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow,
  1065. nb00, nb01, nb02, nb03,
  1066. ne0,
  1067. nb0, nb1, nb2, nb3
  1068. };
  1069. auto name = std::string(__func__) + (src0t == GGML_TYPE_F16 ? "_f16" : "_f32");
  1070. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  1071. if (!komputeManager()->hasAlgorithm(name)) {
  1072. s_algo = komputeManager()->algorithm<float, PushConstants>(
  1073. name, s_kompute_context->pool.get(), {inA, inB, out},
  1074. src0t == GGML_TYPE_F16 ? spirv_f16 : spirv_f32,
  1075. {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts}
  1076. );
  1077. } else {
  1078. s_algo = komputeManager()->getAlgorithm(name);
  1079. s_algo->setTensors({inA, inB, out});
  1080. s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
  1081. s_algo->setPushConstants<PushConstants>({pushConsts});
  1082. s_algo->updateDescriptors(s_kompute_context->pool.get());
  1083. }
  1084. seq.record<kp::OpAlgoDispatch>(s_algo);
  1085. }
  1086. static void ggml_vk_cpy(
  1087. const std::vector<uint32_t>& spirv,
  1088. uint32_t in_element_size, uint32_t out_element_size,
  1089. kp::Sequence& seq,
  1090. const std::shared_ptr<kp::Tensor>& in,
  1091. const std::shared_ptr<kp::Tensor>& out,
  1092. uint32_t inOff, uint32_t outOff,
  1093. int32_t ne00, int32_t ne01, int32_t ne02, int32_t ne03,
  1094. uint32_t nb00, uint32_t nb01, uint32_t nb02, uint32_t nb03,
  1095. int32_t ne0, int32_t ne1, int32_t ne2,
  1096. uint32_t nb0, uint32_t nb1, uint32_t nb2, uint32_t nb3
  1097. ) {
  1098. struct PushConstants {
  1099. uint32_t inOff, outOff;
  1100. int32_t ne00, ne01, ne02;
  1101. uint32_t nb00, nb01, nb02, nb03;
  1102. int32_t ne0, ne1, ne2;
  1103. uint32_t nb0, nb1, nb2, nb3;
  1104. } pushConsts {
  1105. safe_divide(inOff, in_element_size), safe_divide(outOff, out_element_size),
  1106. ne00, ne01, ne02,
  1107. nb00, nb01, nb02, nb03,
  1108. ne0, ne1, ne2,
  1109. nb0, nb1, nb2, nb3
  1110. };
  1111. std::string name = std::string(__func__)
  1112. + "_i_" + std::to_string(in_element_size)
  1113. + "_o_" + std::to_string(out_element_size);
  1114. std::shared_ptr<kp::Algorithm> s_algo = nullptr;
  1115. if (!komputeManager()->hasAlgorithm(name))
  1116. s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts});
  1117. else {
  1118. s_algo = komputeManager()->getAlgorithm(name);
  1119. s_algo->setTensors({in, out});
  1120. s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
  1121. s_algo->setPushConstants<PushConstants>({pushConsts});
  1122. s_algo->updateDescriptors(s_kompute_context->pool.get());
  1123. }
  1124. seq.record<kp::OpAlgoDispatch>(s_algo);
  1125. }
  1126. template <typename... Args>
  1127. static void ggml_vk_cpy_f32_f16(Args&&... args) {
  1128. const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f32_f16_comp_spv,
  1129. kp::shader_data::op_cpy_f32_f16_comp_spv_len);
  1130. ggml_vk_cpy(spirv, 4, 2, std::forward<Args>(args)...);
  1131. }
  1132. template <typename... Args>
  1133. static void ggml_vk_cpy_f32_f32(Args&&... args) {
  1134. const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f32_f32_comp_spv,
  1135. kp::shader_data::op_cpy_f32_f32_comp_spv_len);
  1136. ggml_vk_cpy(spirv, 4, 4, std::forward<Args>(args)...);
  1137. }
  1138. template <typename... Args>
  1139. static void ggml_vk_cpy_f16_f16(Args&&... args) {
  1140. const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f16_f16_comp_spv,
  1141. kp::shader_data::op_cpy_f16_f16_comp_spv_len);
  1142. ggml_vk_cpy(spirv, 2, 2, std::forward<Args>(args)...);
  1143. }
  1144. template <typename... Args>
  1145. static void ggml_vk_cpy_f16_f32(Args&&... args) {
  1146. const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f16_f32_comp_spv,
  1147. kp::shader_data::op_cpy_f16_f32_comp_spv_len);
  1148. ggml_vk_cpy(spirv, 2, 4, std::forward<Args>(args)...);
  1149. }
  1150. static bool ggml_vk_supports_op(const struct ggml_tensor * op) {
  1151. switch (op->type) {
  1152. case GGML_TYPE_F16:
  1153. case GGML_TYPE_F32:
  1154. case GGML_TYPE_Q4_0:
  1155. case GGML_TYPE_Q4_1:
  1156. break;
  1157. default:
  1158. return false;
  1159. }
  1160. switch (op->op) {
  1161. case GGML_OP_UNARY:
  1162. switch (ggml_get_unary_op(op)) {
  1163. case GGML_UNARY_OP_RELU:
  1164. case GGML_UNARY_OP_GELU:
  1165. case GGML_UNARY_OP_SILU:
  1166. return true;
  1167. default:
  1168. ;
  1169. }
  1170. break;
  1171. case GGML_OP_NONE:
  1172. case GGML_OP_RESHAPE:
  1173. case GGML_OP_VIEW:
  1174. case GGML_OP_TRANSPOSE:
  1175. case GGML_OP_PERMUTE:
  1176. case GGML_OP_ADD:
  1177. case GGML_OP_MUL:
  1178. case GGML_OP_SCALE:
  1179. case GGML_OP_SOFT_MAX:
  1180. case GGML_OP_RMS_NORM:
  1181. case GGML_OP_NORM:
  1182. case GGML_OP_ROPE:
  1183. return true;
  1184. case GGML_OP_DUP:
  1185. case GGML_OP_CPY:
  1186. case GGML_OP_CONT:
  1187. switch (op->src[0]->type) {
  1188. case GGML_TYPE_F32:
  1189. case GGML_TYPE_F16:
  1190. break;
  1191. default:
  1192. return false;
  1193. }
  1194. switch (op->type) {
  1195. case GGML_TYPE_F32:
  1196. case GGML_TYPE_F16:
  1197. break;
  1198. default:
  1199. return false;
  1200. }
  1201. return true;
  1202. case GGML_OP_DIAG_MASK_INF:
  1203. return op->ne[3] == 1;
  1204. case GGML_OP_GET_ROWS:
  1205. switch (op->src[0]->type) {
  1206. case GGML_TYPE_F16:
  1207. case GGML_TYPE_Q4_0:
  1208. case GGML_TYPE_Q4_1:
  1209. case GGML_TYPE_Q6_K:
  1210. return op->ne[2] == 1 && op->ne[3] == 1;
  1211. default:
  1212. ;
  1213. }
  1214. return false;
  1215. case GGML_OP_MUL_MAT:
  1216. if (op->src[1]->type != GGML_TYPE_F32 || ggml_is_transposed(op->src[0]) || ggml_is_transposed(op->src[1]))
  1217. return false;
  1218. switch (op->src[0]->type) {
  1219. case GGML_TYPE_F32:
  1220. case GGML_TYPE_Q6_K:
  1221. return op->ne[3] == 1;
  1222. case GGML_TYPE_F16:
  1223. case GGML_TYPE_Q8_0:
  1224. case GGML_TYPE_Q4_0:
  1225. case GGML_TYPE_Q4_1:
  1226. return true;
  1227. default:
  1228. ;
  1229. }
  1230. default:
  1231. ;
  1232. }
  1233. return false;
  1234. }
  1235. static void ggml_vk_graph_compute(struct ggml_kompute_context * ctx, struct ggml_cgraph * gf) {
  1236. const int n_seq = 8;
  1237. // FIXME: Figure out if we can somehow optimize the size of the pool... right now we're setting
  1238. // it to the size of the graph, but I think it can be made smaller?
  1239. ggml_vk_allocate_descriptor_pool(ctx, gf->n_nodes);
  1240. std::vector<std::shared_ptr<kp::Sequence>> sequences(n_seq);
  1241. for (auto& sequence : sequences) {
  1242. sequence = komputeManager()->sequence();
  1243. }
  1244. for (int seq_idx = 0; seq_idx < n_seq; ++seq_idx) {
  1245. const int n_nodes_per_seq = (gf->n_nodes + n_seq - 1) / n_seq;
  1246. auto& seq = *sequences[seq_idx];
  1247. const int node_start = (seq_idx + 0) * n_nodes_per_seq;
  1248. const int node_end = std::min((seq_idx == n_seq - 1) ? gf->n_nodes : (seq_idx + 1) * n_nodes_per_seq, gf->n_nodes);
  1249. bool any_commands_recorded = false;
  1250. for (int i = node_start; i < node_end; ++i) {
  1251. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  1252. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  1253. struct ggml_tensor * src2 = gf->nodes[i]->src[2]; GGML_UNUSED(src2);
  1254. struct ggml_tensor * dst = gf->nodes[i];
  1255. GGML_ASSERT(dst->data != nullptr);
  1256. if (ggml_is_empty(dst)) {
  1257. continue;
  1258. }
  1259. switch (dst->op) {
  1260. case GGML_OP_NONE:
  1261. case GGML_OP_RESHAPE:
  1262. case GGML_OP_VIEW:
  1263. case GGML_OP_TRANSPOSE:
  1264. case GGML_OP_PERMUTE:
  1265. continue; // noop -> next node
  1266. default:
  1267. break;
  1268. }
  1269. any_commands_recorded = true;
  1270. if (!ggml_vk_supports_op(dst)) {
  1271. fprintf(stderr, "%s: error: unsupported op '%s'\n", __func__, ggml_op_desc(dst));
  1272. GGML_ASSERT(!"unsupported op");
  1273. }
  1274. const int32_t ne00 = src0 ? src0->ne[0] : 0;
  1275. const int32_t ne01 = src0 ? src0->ne[1] : 0;
  1276. const int32_t ne02 = src0 ? src0->ne[2] : 0;
  1277. const int32_t ne03 = src0 ? src0->ne[3] : 0;
  1278. const uint32_t nb00 = src0 ? src0->nb[0] : 0;
  1279. const uint32_t nb01 = src0 ? src0->nb[1] : 0;
  1280. const uint32_t nb02 = src0 ? src0->nb[2] : 0;
  1281. const uint32_t nb03 = src0 ? src0->nb[3] : 0;
  1282. const int32_t ne10 = src1 ? src1->ne[0] : 0;
  1283. const int32_t ne11 = src1 ? src1->ne[1] : 0;
  1284. const int32_t ne12 = src1 ? src1->ne[2] : 0;
  1285. const int32_t ne13 = src1 ? src1->ne[3] : 0;
  1286. const uint32_t nb10 = src1 ? src1->nb[0] : 0;
  1287. const uint32_t nb11 = src1 ? src1->nb[1] : 0;
  1288. const uint32_t nb12 = src1 ? src1->nb[2] : 0;
  1289. const uint32_t nb13 = src1 ? src1->nb[3] : 0;
  1290. const int32_t ne0 = dst ? dst->ne[0] : 0;
  1291. const int32_t ne1 = dst ? dst->ne[1] : 0;
  1292. const int32_t ne2 = dst ? dst->ne[2] : 0;
  1293. // const int32_t ne3 = dst ? dst->ne[3] : 0;
  1294. const uint32_t nb0 = dst ? dst->nb[0] : 0;
  1295. const uint32_t nb1 = dst ? dst->nb[1] : 0;
  1296. const uint32_t nb2 = dst ? dst->nb[2] : 0;
  1297. const uint32_t nb3 = dst ? dst->nb[3] : 0;
  1298. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  1299. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  1300. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  1301. const static std::shared_ptr<kp::Tensor> nullTensor = nullptr;
  1302. uint32_t off_src0 = 0;
  1303. uint32_t off_src1 = 0;
  1304. uint32_t off_dst = 0;
  1305. const std::shared_ptr<kp::Tensor>& id_src0 = src0 ? ggml_vk_get_tensor(src0, &off_src0) : nullTensor;
  1306. const std::shared_ptr<kp::Tensor>& id_src1 = src1 ? ggml_vk_get_tensor(src1, &off_src1) : nullTensor;
  1307. const std::shared_ptr<kp::Tensor>& id_dst = dst ? ggml_vk_get_tensor(dst, &off_dst) : nullTensor;
  1308. switch (dst->op) {
  1309. case GGML_OP_ADD:
  1310. {
  1311. if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) {
  1312. // src1 is a row
  1313. ggml_vk_addrow(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ggml_nelements(dst)/4, ne00);
  1314. } else {
  1315. ggml_vk_add(
  1316. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1317. ne00, ne01, ne02, ne03,
  1318. nb00, nb01, nb02, nb03,
  1319. ne10, ne11, ne12, ne13,
  1320. nb10, nb11, nb12, nb13,
  1321. ne0,
  1322. nb0, nb1, nb2, nb3
  1323. );
  1324. }
  1325. } break;
  1326. case GGML_OP_MUL:
  1327. {
  1328. ggml_vk_mul(
  1329. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1330. ne00, ne01, ne02, ne03,
  1331. nb00, nb01, nb02, nb03,
  1332. ne10, ne11, ne12, ne13,
  1333. nb10, nb11, nb12, nb13,
  1334. ne0,
  1335. nb0, nb1, nb2, nb3
  1336. );
  1337. } break;
  1338. case GGML_OP_SCALE:
  1339. {
  1340. float scale; memcpy(&scale, dst->op_params, sizeof(float));
  1341. ggml_vk_scale(seq, id_src0, id_dst, off_src0, off_dst, ggml_nelements(dst), scale);
  1342. } break;
  1343. case GGML_OP_UNARY:
  1344. {
  1345. int64_t n = ggml_nelements(dst);
  1346. GGML_ASSERT(n % 4 == 0);
  1347. switch (ggml_get_unary_op(gf->nodes[i])) {
  1348. case GGML_UNARY_OP_SILU:
  1349. {
  1350. ggml_vk_silu(seq, id_src0, id_dst, off_src0, off_dst, n/4);
  1351. } break;
  1352. case GGML_UNARY_OP_RELU:
  1353. {
  1354. ggml_vk_relu(seq, id_src0, id_dst, off_src0, off_dst, n/4);
  1355. } break;
  1356. case GGML_UNARY_OP_GELU:
  1357. {
  1358. GGML_ASSERT(n % 8 == 0);
  1359. ggml_vk_gelu(seq, id_src0, id_dst, off_src0, off_dst, n/8);
  1360. } break;
  1361. default:
  1362. {
  1363. fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1364. GGML_ASSERT(false);
  1365. }
  1366. }
  1367. } break;
  1368. case GGML_OP_SOFT_MAX:
  1369. {
  1370. float scale;
  1371. float max_bias;
  1372. memcpy(&scale, (float *)dst->op_params + 0, sizeof(float));
  1373. memcpy(&max_bias, (float *)dst->op_params + 1, sizeof(float));
  1374. #pragma message("TODO: add ggml_vk_soft_max() F16 src1 support")
  1375. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5021")
  1376. GGML_ASSERT(!src1 || src1t == GGML_TYPE_F32);
  1377. #pragma message("TODO: add ALiBi support")
  1378. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/7192")
  1379. GGML_ASSERT(max_bias == 0.0f);
  1380. ggml_vk_soft_max(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, ne01, ne02, ne03, scale);
  1381. } break;
  1382. case GGML_OP_DIAG_MASK_INF:
  1383. {
  1384. const int n_past = ((int32_t *)(dst->op_params))[0];
  1385. ggml_vk_diag_mask_inf(seq, id_src0, id_dst, off_src0, off_dst, n_past, ne00, ne01, ne02);
  1386. } break;
  1387. case GGML_OP_NORM:
  1388. {
  1389. float eps;
  1390. memcpy(&eps, dst->op_params, sizeof(float));
  1391. ggml_vk_norm(seq, id_src0, id_dst, off_src0, off_dst, ne00, nb01, ggml_nrows(src0), eps);
  1392. } break;
  1393. case GGML_OP_RMS_NORM:
  1394. {
  1395. GGML_ASSERT(ne00 % 4 == 0);
  1396. float eps;
  1397. memcpy(&eps, dst->op_params, sizeof(float));
  1398. ggml_vk_rms_norm(seq, id_src0, id_dst, off_src0, off_dst, ne00, nb01, ggml_nrows(src0), eps);
  1399. } break;
  1400. case GGML_OP_MUL_MAT:
  1401. {
  1402. GGML_ASSERT(ne00 == ne10);
  1403. // TODO: assert that dim2 and dim3 are contiguous
  1404. GGML_ASSERT(ne12 % ne02 == 0);
  1405. GGML_ASSERT(ne13 % ne03 == 0);
  1406. const uint32_t r2 = ne12/ne02;
  1407. const uint32_t r3 = ne13/ne03;
  1408. if (src1t != GGML_TYPE_F32) {
  1409. fprintf(stderr, "%s: %s: Unsupported src1 type: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
  1410. goto not_implemented;
  1411. }
  1412. if (ggml_is_transposed(src0) ||
  1413. ggml_is_transposed(src1)) {
  1414. fprintf(stderr, "%s: %s: matmul on tranposed tensor not supported: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
  1415. goto not_implemented;
  1416. }
  1417. switch (src0t) {
  1418. case GGML_TYPE_F32:
  1419. ggml_vk_mul_mat_mat_f32(
  1420. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1421. ne00, ne01, ne02, nb01, nb02, ne11, ne12, nb11, nb12, nb1, nb2
  1422. );
  1423. break;
  1424. case GGML_TYPE_F16:
  1425. ggml_vk_mul_mat_f16(
  1426. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1427. ne00, ne01, ne02, nb00, nb01, nb02, ne10, ne11, ne12, ne13, nb10, nb11, nb12,
  1428. ne0, ne1, r2, r3
  1429. );
  1430. break;
  1431. case GGML_TYPE_Q8_0:
  1432. ggml_vk_mul_mat_q8_0(
  1433. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1434. ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1, r2, r3
  1435. );
  1436. break;
  1437. case GGML_TYPE_Q4_0:
  1438. ggml_vk_mul_mat_q4_0(
  1439. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1440. ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1, r2, r3
  1441. );
  1442. break;
  1443. case GGML_TYPE_Q4_1:
  1444. ggml_vk_mul_mat_q4_1(
  1445. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1446. ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1, r2, r3
  1447. );
  1448. break;
  1449. case GGML_TYPE_Q6_K:
  1450. ggml_vk_mul_mat_q6_k(
  1451. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1452. ne00, ne10, ne0, ne1, ne01, ne11, ne12, ne02
  1453. );
  1454. break;
  1455. default: {
  1456. fprintf(stderr, "%s: %s: Unsupported quantization: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
  1457. goto not_implemented;
  1458. }
  1459. }
  1460. } break;
  1461. case GGML_OP_GET_ROWS:
  1462. {
  1463. if (src0t == GGML_TYPE_F16) {
  1464. ggml_vk_get_rows_f16(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
  1465. } else if (src0t == GGML_TYPE_Q4_0) {
  1466. ggml_vk_get_rows_q4_0(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
  1467. } else if (src0t == GGML_TYPE_Q4_1) {
  1468. ggml_vk_get_rows_q4_1(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
  1469. } else if (src0t == GGML_TYPE_Q6_K) {
  1470. ggml_vk_get_rows_q6_k(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
  1471. } else {
  1472. fprintf(stderr, "%s: %s: Unsupported quantization: %u\n", __func__, ggml_op_name(dst->op), src0t);
  1473. goto not_implemented;
  1474. }
  1475. } break;
  1476. case GGML_OP_ROPE:
  1477. {
  1478. GGML_ASSERT(ne10 == ne02);
  1479. GGML_ASSERT(src0t == dstt);
  1480. // const int n_past = ((int32_t *) dst->op_params)[0];
  1481. const int n_dims = ((int32_t *) dst->op_params)[1];
  1482. const int mode = ((int32_t *) dst->op_params)[2];
  1483. // skip 3, n_ctx used in GLM RoPE, unimplemented in Vulkan
  1484. const int n_orig_ctx = ((int32_t *) dst->op_params)[4];
  1485. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  1486. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  1487. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  1488. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  1489. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  1490. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  1491. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  1492. ggml_vk_rope(
  1493. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, src0t, n_dims, mode, n_orig_ctx,
  1494. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow,
  1495. ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, nb0, nb1, nb2, nb3
  1496. );
  1497. } break;
  1498. case GGML_OP_DUP:
  1499. case GGML_OP_CPY:
  1500. case GGML_OP_CONT:
  1501. {
  1502. switch (src0t) {
  1503. case GGML_TYPE_F32:
  1504. {
  1505. switch (dstt) {
  1506. case GGML_TYPE_F16: ggml_vk_cpy_f32_f16(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
  1507. case GGML_TYPE_F32: ggml_vk_cpy_f32_f32(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
  1508. default: goto not_implemented;
  1509. }
  1510. } break;
  1511. case GGML_TYPE_F16:
  1512. {
  1513. switch (dstt) {
  1514. case GGML_TYPE_F16: ggml_vk_cpy_f16_f16(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
  1515. case GGML_TYPE_F32: ggml_vk_cpy_f16_f32(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
  1516. default: goto not_implemented;
  1517. } break;
  1518. default: goto not_implemented;
  1519. }
  1520. }
  1521. } break;
  1522. default: goto not_implemented;
  1523. }
  1524. continue;
  1525. not_implemented: {}
  1526. fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1527. //GGML_ASSERT(false);
  1528. }
  1529. // Evaluate sequence
  1530. if (any_commands_recorded) {
  1531. seq.evalAsync();
  1532. }
  1533. }
  1534. // Wait for all sequences to finish
  1535. for (auto& sequence : sequences) {
  1536. if (sequence->isRunning())
  1537. sequence->evalAwait();
  1538. }
  1539. ggml_vk_free_descriptor_pool(ctx);
  1540. }
  1541. template<>
  1542. kp::Tensor::TensorDataTypes
  1543. kp::TensorT<half>::dataType()
  1544. {
  1545. return TensorDataTypes::eFloat;
  1546. }
  1547. template<>
  1548. kp::Tensor::TensorDataTypes
  1549. kp::TensorT<uint8_t>::dataType()
  1550. {
  1551. return TensorDataTypes::eUnsignedInt;
  1552. }
  1553. ////////////////////////////////////////////////////////////////////////////////
  1554. // backend interface
  1555. struct ggml_backend_kompute_buffer_type_context {
  1556. int device;
  1557. int device_ref = 0;
  1558. uint64_t buffer_alignment;
  1559. uint64_t max_alloc;
  1560. std::string name;
  1561. ggml_backend_kompute_buffer_type_context(int device, uint64_t buffer_alignment, uint64_t max_alloc)
  1562. : device(device), buffer_alignment(buffer_alignment), max_alloc(max_alloc), name(ggml_kompute_format_name(device)) {}
  1563. };
  1564. static void ggml_backend_kompute_device_ref(ggml_backend_buffer_type_t buft) {
  1565. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1566. if (!ctx->device_ref) {
  1567. komputeManager()->initializeDevice(
  1568. ctx->device, {}, {
  1569. "VK_KHR_shader_float16_int8", "VK_KHR_8bit_storage",
  1570. "VK_KHR_16bit_storage", "VK_KHR_shader_non_semantic_info"
  1571. }
  1572. );
  1573. }
  1574. assert(ggml_vk_has_device());
  1575. ctx->device_ref++;
  1576. }
  1577. static void ggml_backend_kompute_device_unref(ggml_backend_buffer_type_t buft) {
  1578. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1579. assert(ctx->device_ref > 0);
  1580. ctx->device_ref--;
  1581. if (!ctx->device_ref) {
  1582. komputeManager.destroy();
  1583. }
  1584. }
  1585. static const char * ggml_backend_kompute_buffer_get_name(ggml_backend_buffer_t buffer) {
  1586. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buffer->buft->context);
  1587. return ctx->name.c_str();
  1588. }
  1589. static void ggml_backend_kompute_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1590. auto * memory = (ggml_vk_memory *)buffer->context;
  1591. if (ggml_vk_has_device()) {
  1592. ggml_vk_free_memory(*memory);
  1593. }
  1594. delete memory;
  1595. }
  1596. static void * ggml_backend_kompute_buffer_get_base(ggml_backend_buffer_t buffer) {
  1597. return ((ggml_vk_memory *)buffer->context)->data;
  1598. }
  1599. static void ggml_backend_kompute_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  1600. GGML_UNUSED(buffer);
  1601. const auto res = ggml_vk_get_tensor(tensor);
  1602. GGML_ASSERT(res);
  1603. memcpy((char *)tensor->data + offset, data, size);
  1604. komputeManager()->sequence()->eval<kp::OpTensorSyncDevice>({res});
  1605. }
  1606. static void ggml_backend_kompute_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  1607. GGML_UNUSED(buffer);
  1608. const auto res = ggml_vk_get_tensor(tensor);
  1609. GGML_ASSERT(res);
  1610. komputeManager()->sequence()->eval<kp::OpTensorSyncLocal>({res});
  1611. memcpy(data, (const char *)tensor->data + offset, size);
  1612. }
  1613. static void ggml_backend_kompute_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  1614. auto * memory = (ggml_vk_memory *)buffer->context;
  1615. memset(memory->data, value, buffer->size);
  1616. if (memory->stagingBuffer)
  1617. komputeManager()->sequence()->eval<kp::OpBufferSyncDevice>(memory->primaryBuffer, memory->stagingBuffer, memory->size);
  1618. }
  1619. static ggml_backend_buffer_i ggml_backend_kompute_buffer_i = {
  1620. /* .get_name = */ ggml_backend_kompute_buffer_get_name,
  1621. /* .free_buffer = */ ggml_backend_kompute_buffer_free_buffer,
  1622. /* .get_base = */ ggml_backend_kompute_buffer_get_base,
  1623. /* .init_tensor = */ NULL,
  1624. /* .set_tensor = */ ggml_backend_kompute_buffer_set_tensor,
  1625. /* .get_tensor = */ ggml_backend_kompute_buffer_get_tensor,
  1626. /* .cpy_tensor = */ NULL,
  1627. /* .clear = */ ggml_backend_kompute_buffer_clear,
  1628. /* .reset = */ NULL,
  1629. };
  1630. // default buffer type
  1631. static const char * ggml_backend_kompute_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  1632. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1633. return ctx->name.c_str();
  1634. }
  1635. static ggml_backend_buffer_t ggml_backend_kompute_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  1636. ggml_backend_kompute_device_ref(buft);
  1637. auto * ctx = new ggml_vk_memory(ggml_vk_allocate(size));
  1638. return ggml_backend_buffer_init(buft, ggml_backend_kompute_buffer_i, ctx, size);
  1639. }
  1640. static size_t ggml_backend_kompute_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  1641. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1642. return ctx->buffer_alignment;
  1643. }
  1644. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  1645. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1646. return ctx->max_alloc;
  1647. }
  1648. static bool ggml_backend_kompute_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  1649. GGML_UNUSED(buft);
  1650. return ggml_backend_is_kompute(backend);
  1651. }
  1652. static ggml_backend_buffer_type_i ggml_backend_kompute_buffer_type_interface = {
  1653. /* .get_name = */ ggml_backend_kompute_buffer_type_get_name,
  1654. /* .alloc_buffer = */ ggml_backend_kompute_buffer_type_alloc_buffer,
  1655. /* .get_alignment = */ ggml_backend_kompute_buffer_type_get_alignment,
  1656. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  1657. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  1658. /* .supports_backend = */ ggml_backend_kompute_buffer_type_supports_backend,
  1659. /* .is_host = */ NULL,
  1660. };
  1661. ggml_backend_buffer_type_t ggml_backend_kompute_buffer_type(int device) {
  1662. static std::vector<ggml_backend_buffer_type> bufts = []() {
  1663. std::vector<ggml_backend_buffer_type> vec;
  1664. auto devices = ggml_vk_available_devices_internal(0);
  1665. vec.reserve(devices.size());
  1666. for (const auto & dev : devices) {
  1667. vec.push_back({
  1668. /* .iface = */ ggml_backend_kompute_buffer_type_interface,
  1669. /* .context = */ new ggml_backend_kompute_buffer_type_context(dev.index, dev.bufferAlignment, dev.maxAlloc)
  1670. });
  1671. }
  1672. return vec;
  1673. }();
  1674. auto it = std::find_if(bufts.begin(), bufts.end(), [device](const ggml_backend_buffer_type & t) {
  1675. return device == static_cast<ggml_backend_kompute_buffer_type_context *>(t.context)->device;
  1676. });
  1677. return it < bufts.end() ? &*it : nullptr;
  1678. }
  1679. // backend
  1680. static const char * ggml_backend_kompute_name(ggml_backend_t backend) {
  1681. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1682. return ctx->name.c_str();
  1683. }
  1684. static void ggml_backend_kompute_free(ggml_backend_t backend) {
  1685. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1686. assert(ctx == s_kompute_context);
  1687. s_kompute_context = nullptr;
  1688. if (ctx != nullptr) {
  1689. delete ctx;
  1690. }
  1691. delete backend;
  1692. }
  1693. static ggml_backend_buffer_type_t ggml_backend_kompute_get_default_buffer_type(ggml_backend_t backend) {
  1694. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1695. return ggml_backend_kompute_buffer_type(ctx->device);
  1696. }
  1697. static ggml_status ggml_backend_kompute_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  1698. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1699. ggml_vk_graph_compute(ctx, cgraph);
  1700. return GGML_STATUS_SUCCESS;
  1701. }
  1702. static bool ggml_backend_kompute_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  1703. GGML_UNUSED(backend);
  1704. return ggml_vk_supports_op(op);
  1705. }
  1706. static struct ggml_backend_i kompute_backend_i = {
  1707. /* .get_name = */ ggml_backend_kompute_name,
  1708. /* .free = */ ggml_backend_kompute_free,
  1709. /* .get_default_buffer_type = */ ggml_backend_kompute_get_default_buffer_type,
  1710. /* .set_tensor_async = */ NULL,
  1711. /* .get_tensor_async = */ NULL,
  1712. /* .cpy_tensor_async = */ NULL,
  1713. /* .synchronize = */ NULL,
  1714. /* .graph_plan_create = */ NULL,
  1715. /* .graph_plan_free = */ NULL,
  1716. /* .graph_plan_compute = */ NULL,
  1717. /* .graph_compute = */ ggml_backend_kompute_graph_compute,
  1718. /* .supports_op = */ ggml_backend_kompute_supports_op,
  1719. /* .offload_op = */ NULL,
  1720. /* .event_new = */ NULL,
  1721. /* .event_free = */ NULL,
  1722. /* .event_record = */ NULL,
  1723. /* .event_wait = */ NULL,
  1724. /* .event_synchronize = */ NULL,
  1725. };
  1726. static ggml_guid_t ggml_backend_kompute_guid() {
  1727. static ggml_guid guid = { 0x7b, 0x57, 0xdc, 0xaf, 0xde, 0x12, 0x1d, 0x49, 0xfb, 0x35, 0xfa, 0x9b, 0x18, 0x31, 0x1d, 0xca };
  1728. return &guid;
  1729. }
  1730. ggml_backend_t ggml_backend_kompute_init(int device) {
  1731. GGML_ASSERT(s_kompute_context == nullptr);
  1732. s_kompute_context = new ggml_kompute_context(device);
  1733. ggml_backend_t kompute_backend = new ggml_backend {
  1734. /* .guid = */ ggml_backend_kompute_guid(),
  1735. /* .interface = */ kompute_backend_i,
  1736. /* .context = */ s_kompute_context,
  1737. };
  1738. return kompute_backend;
  1739. }
  1740. bool ggml_backend_is_kompute(ggml_backend_t backend) {
  1741. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_kompute_guid());
  1742. }
  1743. static ggml_backend_t ggml_backend_reg_kompute_init(const char * params, void * user_data) {
  1744. GGML_UNUSED(params);
  1745. return ggml_backend_kompute_init(intptr_t(user_data));
  1746. }
  1747. extern "C" int ggml_backend_kompute_reg_devices();
  1748. int ggml_backend_kompute_reg_devices() {
  1749. auto devices = ggml_vk_available_devices_internal(0);
  1750. for (const auto & device : devices) {
  1751. ggml_backend_register(
  1752. ggml_kompute_format_name(device.index).c_str(),
  1753. ggml_backend_reg_kompute_init,
  1754. ggml_backend_kompute_buffer_type(device.index),
  1755. reinterpret_cast<void *>(intptr_t(device.index))
  1756. );
  1757. }
  1758. return devices.size();
  1759. }