ggml-kompute.cpp 85 KB

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