ggml-kompute.cpp 79 KB

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