1
0

ggml-kompute.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  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 * dst = gf->nodes[i];
  1254. GGML_ASSERT(dst->data != nullptr);
  1255. if (ggml_is_empty(dst)) {
  1256. continue;
  1257. }
  1258. switch (dst->op) {
  1259. case GGML_OP_NONE:
  1260. case GGML_OP_RESHAPE:
  1261. case GGML_OP_VIEW:
  1262. case GGML_OP_TRANSPOSE:
  1263. case GGML_OP_PERMUTE:
  1264. continue; // noop -> next node
  1265. default:
  1266. break;
  1267. }
  1268. any_commands_recorded = true;
  1269. if (!ggml_vk_supports_op(dst)) {
  1270. fprintf(stderr, "%s: error: unsupported op '%s'\n", __func__, ggml_op_desc(dst));
  1271. GGML_ASSERT(!"unsupported op");
  1272. }
  1273. const int32_t ne00 = src0 ? src0->ne[0] : 0;
  1274. const int32_t ne01 = src0 ? src0->ne[1] : 0;
  1275. const int32_t ne02 = src0 ? src0->ne[2] : 0;
  1276. const int32_t ne03 = src0 ? src0->ne[3] : 0;
  1277. const uint32_t nb00 = src0 ? src0->nb[0] : 0;
  1278. const uint32_t nb01 = src0 ? src0->nb[1] : 0;
  1279. const uint32_t nb02 = src0 ? src0->nb[2] : 0;
  1280. const uint32_t nb03 = src0 ? src0->nb[3] : 0;
  1281. const int32_t ne10 = src1 ? src1->ne[0] : 0;
  1282. const int32_t ne11 = src1 ? src1->ne[1] : 0;
  1283. const int32_t ne12 = src1 ? src1->ne[2] : 0;
  1284. const int32_t ne13 = src1 ? src1->ne[3] : 0;
  1285. const uint32_t nb10 = src1 ? src1->nb[0] : 0;
  1286. const uint32_t nb11 = src1 ? src1->nb[1] : 0;
  1287. const uint32_t nb12 = src1 ? src1->nb[2] : 0;
  1288. const uint32_t nb13 = src1 ? src1->nb[3] : 0;
  1289. const int32_t ne0 = dst ? dst->ne[0] : 0;
  1290. const int32_t ne1 = dst ? dst->ne[1] : 0;
  1291. const int32_t ne2 = dst ? dst->ne[2] : 0;
  1292. // const int32_t ne3 = dst ? dst->ne[3] : 0;
  1293. const uint32_t nb0 = dst ? dst->nb[0] : 0;
  1294. const uint32_t nb1 = dst ? dst->nb[1] : 0;
  1295. const uint32_t nb2 = dst ? dst->nb[2] : 0;
  1296. const uint32_t nb3 = dst ? dst->nb[3] : 0;
  1297. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  1298. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  1299. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  1300. const static std::shared_ptr<kp::Tensor> nullTensor = nullptr;
  1301. uint32_t off_src0 = 0;
  1302. uint32_t off_src1 = 0;
  1303. uint32_t off_dst = 0;
  1304. const std::shared_ptr<kp::Tensor>& id_src0 = src0 ? ggml_vk_get_tensor(src0, &off_src0) : nullTensor;
  1305. const std::shared_ptr<kp::Tensor>& id_src1 = src1 ? ggml_vk_get_tensor(src1, &off_src1) : nullTensor;
  1306. const std::shared_ptr<kp::Tensor>& id_dst = dst ? ggml_vk_get_tensor(dst, &off_dst) : nullTensor;
  1307. switch (dst->op) {
  1308. case GGML_OP_ADD:
  1309. {
  1310. if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) {
  1311. // src1 is a row
  1312. ggml_vk_addrow(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ggml_nelements(dst)/4, ne00);
  1313. } else {
  1314. ggml_vk_add(
  1315. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1316. ne00, ne01, ne02, ne03,
  1317. nb00, nb01, nb02, nb03,
  1318. ne10, ne11, ne12, ne13,
  1319. nb10, nb11, nb12, nb13,
  1320. ne0,
  1321. nb0, nb1, nb2, nb3
  1322. );
  1323. }
  1324. } break;
  1325. case GGML_OP_MUL:
  1326. {
  1327. ggml_vk_mul(
  1328. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1329. ne00, ne01, ne02, ne03,
  1330. nb00, nb01, nb02, nb03,
  1331. ne10, ne11, ne12, ne13,
  1332. nb10, nb11, nb12, nb13,
  1333. ne0,
  1334. nb0, nb1, nb2, nb3
  1335. );
  1336. } break;
  1337. case GGML_OP_SCALE:
  1338. {
  1339. float scale; memcpy(&scale, dst->op_params, sizeof(float));
  1340. ggml_vk_scale(seq, id_src0, id_dst, off_src0, off_dst, ggml_nelements(dst), scale);
  1341. } break;
  1342. case GGML_OP_UNARY:
  1343. {
  1344. int64_t n = ggml_nelements(dst);
  1345. GGML_ASSERT(n % 4 == 0);
  1346. switch (ggml_get_unary_op(gf->nodes[i])) {
  1347. case GGML_UNARY_OP_SILU:
  1348. {
  1349. ggml_vk_silu(seq, id_src0, id_dst, off_src0, off_dst, n/4);
  1350. } break;
  1351. case GGML_UNARY_OP_RELU:
  1352. {
  1353. ggml_vk_relu(seq, id_src0, id_dst, off_src0, off_dst, n/4);
  1354. } break;
  1355. case GGML_UNARY_OP_GELU:
  1356. {
  1357. GGML_ASSERT(n % 8 == 0);
  1358. ggml_vk_gelu(seq, id_src0, id_dst, off_src0, off_dst, n/8);
  1359. } break;
  1360. default:
  1361. {
  1362. fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1363. GGML_ASSERT(false);
  1364. }
  1365. }
  1366. } break;
  1367. case GGML_OP_SOFT_MAX:
  1368. {
  1369. float scale;
  1370. memcpy(&scale, dst->op_params, sizeof(float));
  1371. ggml_vk_soft_max(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, ne01, ne02, ne03, scale);
  1372. } break;
  1373. case GGML_OP_DIAG_MASK_INF:
  1374. {
  1375. const int n_past = ((int32_t *)(dst->op_params))[0];
  1376. ggml_vk_diag_mask_inf(seq, id_src0, id_dst, off_src0, off_dst, n_past, ne00, ne01, ne02);
  1377. } break;
  1378. case GGML_OP_NORM:
  1379. {
  1380. float eps;
  1381. memcpy(&eps, dst->op_params, sizeof(float));
  1382. ggml_vk_norm(seq, id_src0, id_dst, off_src0, off_dst, ne00, nb01, ggml_nrows(src0), eps);
  1383. } break;
  1384. case GGML_OP_RMS_NORM:
  1385. {
  1386. GGML_ASSERT(ne00 % 4 == 0);
  1387. float eps;
  1388. memcpy(&eps, dst->op_params, sizeof(float));
  1389. ggml_vk_rms_norm(seq, id_src0, id_dst, off_src0, off_dst, ne00, nb01, ggml_nrows(src0), eps);
  1390. } break;
  1391. case GGML_OP_MUL_MAT:
  1392. {
  1393. GGML_ASSERT(ne00 == ne10);
  1394. // TODO: assert that dim2 and dim3 are contiguous
  1395. GGML_ASSERT(ne12 % ne02 == 0);
  1396. GGML_ASSERT(ne13 % ne03 == 0);
  1397. const uint32_t r2 = ne12/ne02;
  1398. const uint32_t r3 = ne13/ne03;
  1399. if (src1t != GGML_TYPE_F32) {
  1400. fprintf(stderr, "%s: %s: Unsupported src1 type: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
  1401. goto not_implemented;
  1402. }
  1403. if (ggml_is_transposed(src0) ||
  1404. ggml_is_transposed(src1)) {
  1405. fprintf(stderr, "%s: %s: matmul on tranposed tensor not supported: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
  1406. goto not_implemented;
  1407. }
  1408. switch (src0t) {
  1409. case GGML_TYPE_F32:
  1410. ggml_vk_mul_mat_mat_f32(
  1411. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1412. ne00, ne01, ne02, nb01, nb02, ne11, ne12, nb11, nb12, nb1, nb2
  1413. );
  1414. break;
  1415. case GGML_TYPE_F16:
  1416. ggml_vk_mul_mat_f16(
  1417. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1418. ne00, ne01, ne02, nb00, nb01, nb02, ne10, ne11, ne12, ne13, nb10, nb11, nb12,
  1419. ne0, ne1, r2, r3
  1420. );
  1421. break;
  1422. case GGML_TYPE_Q8_0:
  1423. ggml_vk_mul_mat_q8_0(
  1424. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1425. ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1, r2, r3
  1426. );
  1427. break;
  1428. case GGML_TYPE_Q4_0:
  1429. ggml_vk_mul_mat_q4_0(
  1430. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1431. ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1, r2, r3
  1432. );
  1433. break;
  1434. case GGML_TYPE_Q4_1:
  1435. ggml_vk_mul_mat_q4_1(
  1436. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1437. ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1, r2, r3
  1438. );
  1439. break;
  1440. case GGML_TYPE_Q6_K:
  1441. ggml_vk_mul_mat_q6_k(
  1442. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
  1443. ne00, ne10, ne0, ne1, ne01, ne11, ne12, ne02
  1444. );
  1445. break;
  1446. default: {
  1447. fprintf(stderr, "%s: %s: Unsupported quantization: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
  1448. goto not_implemented;
  1449. }
  1450. }
  1451. } break;
  1452. case GGML_OP_GET_ROWS:
  1453. {
  1454. if (src0t == GGML_TYPE_F16) {
  1455. ggml_vk_get_rows_f16(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
  1456. } else if (src0t == GGML_TYPE_Q4_0) {
  1457. 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));
  1458. } else if (src0t == GGML_TYPE_Q4_1) {
  1459. 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));
  1460. } else if (src0t == GGML_TYPE_Q6_K) {
  1461. 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));
  1462. } else {
  1463. fprintf(stderr, "%s: %s: Unsupported quantization: %u\n", __func__, ggml_op_name(dst->op), src0t);
  1464. goto not_implemented;
  1465. }
  1466. } break;
  1467. case GGML_OP_ROPE:
  1468. {
  1469. GGML_ASSERT(ne10 == ne02);
  1470. GGML_ASSERT(src0t == dstt);
  1471. // const int n_past = ((int32_t *) dst->op_params)[0];
  1472. const int n_dims = ((int32_t *) dst->op_params)[1];
  1473. const int mode = ((int32_t *) dst->op_params)[2];
  1474. // skip 3, n_ctx used in GLM RoPE, unimplemented in Vulkan
  1475. const int n_orig_ctx = ((int32_t *) dst->op_params)[4];
  1476. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  1477. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  1478. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  1479. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  1480. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  1481. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  1482. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  1483. ggml_vk_rope(
  1484. seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, src0t, n_dims, mode, n_orig_ctx,
  1485. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow,
  1486. ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, nb0, nb1, nb2, nb3
  1487. );
  1488. } break;
  1489. case GGML_OP_DUP:
  1490. case GGML_OP_CPY:
  1491. case GGML_OP_CONT:
  1492. {
  1493. switch (src0t) {
  1494. case GGML_TYPE_F32:
  1495. {
  1496. switch (dstt) {
  1497. 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;
  1498. 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;
  1499. default: goto not_implemented;
  1500. }
  1501. } break;
  1502. case GGML_TYPE_F16:
  1503. {
  1504. switch (dstt) {
  1505. 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;
  1506. 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;
  1507. default: goto not_implemented;
  1508. } break;
  1509. default: goto not_implemented;
  1510. }
  1511. }
  1512. } break;
  1513. default: goto not_implemented;
  1514. }
  1515. continue;
  1516. not_implemented: {}
  1517. fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1518. //GGML_ASSERT(false);
  1519. }
  1520. // Evaluate sequence
  1521. if (any_commands_recorded) {
  1522. seq.evalAsync();
  1523. }
  1524. }
  1525. // Wait for all sequences to finish
  1526. for (auto& sequence : sequences) {
  1527. if (sequence->isRunning())
  1528. sequence->evalAwait();
  1529. }
  1530. ggml_vk_free_descriptor_pool(ctx);
  1531. }
  1532. template<>
  1533. kp::Tensor::TensorDataTypes
  1534. kp::TensorT<half>::dataType()
  1535. {
  1536. return TensorDataTypes::eFloat;
  1537. }
  1538. template<>
  1539. kp::Tensor::TensorDataTypes
  1540. kp::TensorT<uint8_t>::dataType()
  1541. {
  1542. return TensorDataTypes::eUnsignedInt;
  1543. }
  1544. ////////////////////////////////////////////////////////////////////////////////
  1545. // backend interface
  1546. struct ggml_backend_kompute_buffer_type_context {
  1547. int device;
  1548. int device_ref = 0;
  1549. uint64_t buffer_alignment;
  1550. uint64_t max_alloc;
  1551. std::string name;
  1552. ggml_backend_kompute_buffer_type_context(int device, uint64_t buffer_alignment, uint64_t max_alloc)
  1553. : device(device), buffer_alignment(buffer_alignment), max_alloc(max_alloc), name(ggml_kompute_format_name(device)) {}
  1554. };
  1555. static void ggml_backend_kompute_device_ref(ggml_backend_buffer_type_t buft) {
  1556. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1557. if (!ctx->device_ref) {
  1558. komputeManager()->initializeDevice(
  1559. ctx->device, {}, {
  1560. "VK_KHR_shader_float16_int8", "VK_KHR_8bit_storage",
  1561. "VK_KHR_16bit_storage", "VK_KHR_shader_non_semantic_info"
  1562. }
  1563. );
  1564. }
  1565. assert(ggml_vk_has_device());
  1566. ctx->device_ref++;
  1567. }
  1568. static void ggml_backend_kompute_device_unref(ggml_backend_buffer_type_t buft) {
  1569. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1570. assert(ctx->device_ref > 0);
  1571. ctx->device_ref--;
  1572. if (!ctx->device_ref) {
  1573. komputeManager.destroy();
  1574. }
  1575. }
  1576. static const char * ggml_backend_kompute_buffer_get_name(ggml_backend_buffer_t buffer) {
  1577. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buffer->buft->context);
  1578. return ctx->name.c_str();
  1579. }
  1580. static void ggml_backend_kompute_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1581. auto * memory = (ggml_vk_memory *)buffer->context;
  1582. if (ggml_vk_has_device()) {
  1583. ggml_vk_free_memory(*memory);
  1584. }
  1585. delete memory;
  1586. }
  1587. static void * ggml_backend_kompute_buffer_get_base(ggml_backend_buffer_t buffer) {
  1588. return ((ggml_vk_memory *)buffer->context)->data;
  1589. }
  1590. 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) {
  1591. GGML_UNUSED(buffer);
  1592. const auto res = ggml_vk_get_tensor(tensor);
  1593. GGML_ASSERT(res);
  1594. memcpy((char *)tensor->data + offset, data, size);
  1595. komputeManager()->sequence()->eval<kp::OpTensorSyncDevice>({res});
  1596. }
  1597. 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) {
  1598. GGML_UNUSED(buffer);
  1599. const auto res = ggml_vk_get_tensor(tensor);
  1600. GGML_ASSERT(res);
  1601. komputeManager()->sequence()->eval<kp::OpTensorSyncLocal>({res});
  1602. memcpy(data, (const char *)tensor->data + offset, size);
  1603. }
  1604. static void ggml_backend_kompute_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  1605. auto * memory = (ggml_vk_memory *)buffer->context;
  1606. memset(memory->data, value, buffer->size);
  1607. if (memory->stagingBuffer)
  1608. komputeManager()->sequence()->eval<kp::OpBufferSyncDevice>(memory->primaryBuffer, memory->stagingBuffer, memory->size);
  1609. }
  1610. static ggml_backend_buffer_i ggml_backend_kompute_buffer_i = {
  1611. /* .get_name = */ ggml_backend_kompute_buffer_get_name,
  1612. /* .free_buffer = */ ggml_backend_kompute_buffer_free_buffer,
  1613. /* .get_base = */ ggml_backend_kompute_buffer_get_base,
  1614. /* .init_tensor = */ NULL,
  1615. /* .set_tensor = */ ggml_backend_kompute_buffer_set_tensor,
  1616. /* .get_tensor = */ ggml_backend_kompute_buffer_get_tensor,
  1617. /* .cpy_tensor = */ NULL,
  1618. /* .clear = */ ggml_backend_kompute_buffer_clear,
  1619. /* .reset = */ NULL,
  1620. };
  1621. // default buffer type
  1622. static const char * ggml_backend_kompute_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  1623. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1624. return ctx->name.c_str();
  1625. }
  1626. static ggml_backend_buffer_t ggml_backend_kompute_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  1627. ggml_backend_kompute_device_ref(buft);
  1628. auto * ctx = new ggml_vk_memory(ggml_vk_allocate(size));
  1629. return ggml_backend_buffer_init(buft, ggml_backend_kompute_buffer_i, ctx, size);
  1630. }
  1631. static size_t ggml_backend_kompute_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  1632. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1633. return ctx->buffer_alignment;
  1634. }
  1635. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  1636. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1637. return ctx->max_alloc;
  1638. }
  1639. static bool ggml_backend_kompute_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  1640. GGML_UNUSED(buft);
  1641. return ggml_backend_is_kompute(backend);
  1642. }
  1643. static ggml_backend_buffer_type_i ggml_backend_kompute_buffer_type_interface = {
  1644. /* .get_name = */ ggml_backend_kompute_buffer_type_get_name,
  1645. /* .alloc_buffer = */ ggml_backend_kompute_buffer_type_alloc_buffer,
  1646. /* .get_alignment = */ ggml_backend_kompute_buffer_type_get_alignment,
  1647. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  1648. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  1649. /* .supports_backend = */ ggml_backend_kompute_buffer_type_supports_backend,
  1650. /* .is_host = */ NULL,
  1651. };
  1652. ggml_backend_buffer_type_t ggml_backend_kompute_buffer_type(int device) {
  1653. static std::vector<ggml_backend_buffer_type> bufts = []() {
  1654. std::vector<ggml_backend_buffer_type> vec;
  1655. auto devices = ggml_vk_available_devices_internal(0);
  1656. vec.reserve(devices.size());
  1657. for (const auto & dev : devices) {
  1658. vec.push_back({
  1659. /* .iface = */ ggml_backend_kompute_buffer_type_interface,
  1660. /* .context = */ new ggml_backend_kompute_buffer_type_context(dev.index, dev.bufferAlignment, dev.maxAlloc)
  1661. });
  1662. }
  1663. return vec;
  1664. }();
  1665. auto it = std::find_if(bufts.begin(), bufts.end(), [device](const ggml_backend_buffer_type & t) {
  1666. return device == static_cast<ggml_backend_kompute_buffer_type_context *>(t.context)->device;
  1667. });
  1668. return it < bufts.end() ? &*it : nullptr;
  1669. }
  1670. // backend
  1671. static const char * ggml_backend_kompute_name(ggml_backend_t backend) {
  1672. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1673. return ctx->name.c_str();
  1674. }
  1675. static void ggml_backend_kompute_free(ggml_backend_t backend) {
  1676. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1677. assert(ctx == s_kompute_context);
  1678. s_kompute_context = nullptr;
  1679. if (ctx != nullptr) {
  1680. delete ctx;
  1681. }
  1682. delete backend;
  1683. }
  1684. static ggml_backend_buffer_type_t ggml_backend_kompute_get_default_buffer_type(ggml_backend_t backend) {
  1685. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1686. return ggml_backend_kompute_buffer_type(ctx->device);
  1687. }
  1688. static ggml_status ggml_backend_kompute_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  1689. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1690. ggml_vk_graph_compute(ctx, cgraph);
  1691. return GGML_STATUS_SUCCESS;
  1692. }
  1693. static bool ggml_backend_kompute_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  1694. GGML_UNUSED(backend);
  1695. return ggml_vk_supports_op(op);
  1696. }
  1697. static struct ggml_backend_i kompute_backend_i = {
  1698. /* .get_name = */ ggml_backend_kompute_name,
  1699. /* .free = */ ggml_backend_kompute_free,
  1700. /* .get_default_buffer_type = */ ggml_backend_kompute_get_default_buffer_type,
  1701. /* .set_tensor_async = */ NULL,
  1702. /* .get_tensor_async = */ NULL,
  1703. /* .cpy_tensor_async = */ NULL,
  1704. /* .synchronize = */ NULL,
  1705. /* .graph_plan_create = */ NULL,
  1706. /* .graph_plan_free = */ NULL,
  1707. /* .graph_plan_compute = */ NULL,
  1708. /* .graph_compute = */ ggml_backend_kompute_graph_compute,
  1709. /* .supports_op = */ ggml_backend_kompute_supports_op,
  1710. /* .offload_op = */ NULL,
  1711. /* .event_new = */ NULL,
  1712. /* .event_free = */ NULL,
  1713. /* .event_record = */ NULL,
  1714. /* .event_wait = */ NULL,
  1715. /* .event_synchronize = */ NULL,
  1716. };
  1717. static ggml_guid_t ggml_backend_kompute_guid() {
  1718. static ggml_guid guid = { 0x7b, 0x57, 0xdc, 0xaf, 0xde, 0x12, 0x1d, 0x49, 0xfb, 0x35, 0xfa, 0x9b, 0x18, 0x31, 0x1d, 0xca };
  1719. return &guid;
  1720. }
  1721. ggml_backend_t ggml_backend_kompute_init(int device) {
  1722. GGML_ASSERT(s_kompute_context == nullptr);
  1723. s_kompute_context = new ggml_kompute_context(device);
  1724. ggml_backend_t kompute_backend = new ggml_backend {
  1725. /* .guid = */ ggml_backend_kompute_guid(),
  1726. /* .interface = */ kompute_backend_i,
  1727. /* .context = */ s_kompute_context,
  1728. };
  1729. return kompute_backend;
  1730. }
  1731. bool ggml_backend_is_kompute(ggml_backend_t backend) {
  1732. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_kompute_guid());
  1733. }
  1734. static ggml_backend_t ggml_backend_reg_kompute_init(const char * params, void * user_data) {
  1735. GGML_UNUSED(params);
  1736. return ggml_backend_kompute_init(intptr_t(user_data));
  1737. }
  1738. extern "C" int ggml_backend_kompute_reg_devices();
  1739. int ggml_backend_kompute_reg_devices() {
  1740. auto devices = ggml_vk_available_devices_internal(0);
  1741. for (const auto & device : devices) {
  1742. ggml_backend_register(
  1743. ggml_kompute_format_name(device.index).c_str(),
  1744. ggml_backend_reg_kompute_init,
  1745. ggml_backend_kompute_buffer_type(device.index),
  1746. reinterpret_cast<void *>(intptr_t(device.index))
  1747. );
  1748. }
  1749. return devices.size();
  1750. }