ggml-kompute.cpp 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  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_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_ASSERT(!"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 true;
  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_ASSERT(!"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_ASSERT(false);
  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_ASSERT(false);
  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. /* .set_tensor = */ ggml_backend_kompute_buffer_set_tensor,
  1639. /* .get_tensor = */ ggml_backend_kompute_buffer_get_tensor,
  1640. /* .cpy_tensor = */ NULL,
  1641. /* .clear = */ ggml_backend_kompute_buffer_clear,
  1642. /* .reset = */ NULL,
  1643. };
  1644. // default buffer type
  1645. static const char * ggml_backend_kompute_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  1646. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1647. return ctx->name.c_str();
  1648. }
  1649. static ggml_backend_buffer_t ggml_backend_kompute_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  1650. ggml_backend_kompute_device_ref(buft);
  1651. auto * ctx = new ggml_vk_memory(ggml_vk_allocate(size));
  1652. return ggml_backend_buffer_init(buft, ggml_backend_kompute_buffer_i, ctx, size);
  1653. }
  1654. static size_t ggml_backend_kompute_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  1655. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1656. return ctx->buffer_alignment;
  1657. }
  1658. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  1659. auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
  1660. return ctx->max_alloc;
  1661. }
  1662. static bool ggml_backend_kompute_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  1663. GGML_UNUSED(buft);
  1664. return ggml_backend_is_kompute(backend);
  1665. }
  1666. static ggml_backend_buffer_type_i ggml_backend_kompute_buffer_type_interface = {
  1667. /* .get_name = */ ggml_backend_kompute_buffer_type_get_name,
  1668. /* .alloc_buffer = */ ggml_backend_kompute_buffer_type_alloc_buffer,
  1669. /* .get_alignment = */ ggml_backend_kompute_buffer_type_get_alignment,
  1670. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  1671. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  1672. /* .supports_backend = */ ggml_backend_kompute_buffer_type_supports_backend,
  1673. /* .is_host = */ NULL,
  1674. };
  1675. ggml_backend_buffer_type_t ggml_backend_kompute_buffer_type(int device) {
  1676. static std::vector<ggml_backend_buffer_type> bufts = []() {
  1677. std::vector<ggml_backend_buffer_type> vec;
  1678. auto devices = ggml_vk_available_devices_internal(0);
  1679. vec.reserve(devices.size());
  1680. for (const auto & dev : devices) {
  1681. vec.push_back({
  1682. /* .iface = */ ggml_backend_kompute_buffer_type_interface,
  1683. /* .context = */ new ggml_backend_kompute_buffer_type_context(dev.index, dev.bufferAlignment, dev.maxAlloc)
  1684. });
  1685. }
  1686. return vec;
  1687. }();
  1688. auto it = std::find_if(bufts.begin(), bufts.end(), [device](const ggml_backend_buffer_type & t) {
  1689. return device == static_cast<ggml_backend_kompute_buffer_type_context *>(t.context)->device;
  1690. });
  1691. return it < bufts.end() ? &*it : nullptr;
  1692. }
  1693. // backend
  1694. static const char * ggml_backend_kompute_name(ggml_backend_t backend) {
  1695. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1696. return ctx->name.c_str();
  1697. }
  1698. static void ggml_backend_kompute_free(ggml_backend_t backend) {
  1699. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1700. assert(ctx == s_kompute_context);
  1701. s_kompute_context = nullptr;
  1702. if (ctx != nullptr) {
  1703. delete ctx;
  1704. }
  1705. delete backend;
  1706. }
  1707. static ggml_backend_buffer_type_t ggml_backend_kompute_get_default_buffer_type(ggml_backend_t backend) {
  1708. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1709. return ggml_backend_kompute_buffer_type(ctx->device);
  1710. }
  1711. static ggml_status ggml_backend_kompute_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  1712. auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
  1713. ggml_vk_graph_compute(ctx, cgraph);
  1714. return GGML_STATUS_SUCCESS;
  1715. }
  1716. static bool ggml_backend_kompute_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  1717. GGML_UNUSED(backend);
  1718. return ggml_vk_supports_op(op);
  1719. }
  1720. static struct ggml_backend_i kompute_backend_i = {
  1721. /* .get_name = */ ggml_backend_kompute_name,
  1722. /* .free = */ ggml_backend_kompute_free,
  1723. /* .get_default_buffer_type = */ ggml_backend_kompute_get_default_buffer_type,
  1724. /* .set_tensor_async = */ NULL,
  1725. /* .get_tensor_async = */ NULL,
  1726. /* .cpy_tensor_async = */ NULL,
  1727. /* .synchronize = */ NULL,
  1728. /* .graph_plan_create = */ NULL,
  1729. /* .graph_plan_free = */ NULL,
  1730. /* .graph_plan_compute = */ NULL,
  1731. /* .graph_compute = */ ggml_backend_kompute_graph_compute,
  1732. /* .supports_op = */ ggml_backend_kompute_supports_op,
  1733. /* .offload_op = */ NULL,
  1734. /* .event_new = */ NULL,
  1735. /* .event_free = */ NULL,
  1736. /* .event_record = */ NULL,
  1737. /* .event_wait = */ NULL,
  1738. /* .event_synchronize = */ 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. /* .context = */ s_kompute_context,
  1751. };
  1752. return kompute_backend;
  1753. }
  1754. bool ggml_backend_is_kompute(ggml_backend_t backend) {
  1755. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_kompute_guid());
  1756. }
  1757. static ggml_backend_t ggml_backend_reg_kompute_init(const char * params, void * user_data) {
  1758. GGML_UNUSED(params);
  1759. return ggml_backend_kompute_init(intptr_t(user_data));
  1760. }
  1761. extern "C" int ggml_backend_kompute_reg_devices();
  1762. int ggml_backend_kompute_reg_devices() {
  1763. auto devices = ggml_vk_available_devices_internal(0);
  1764. for (const auto & device : devices) {
  1765. ggml_backend_register(
  1766. ggml_kompute_format_name(device.index).c_str(),
  1767. ggml_backend_reg_kompute_init,
  1768. ggml_backend_kompute_buffer_type(device.index),
  1769. reinterpret_cast<void *>(intptr_t(device.index))
  1770. );
  1771. }
  1772. return devices.size();
  1773. }