ggml-kompute.cpp 78 KB

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