Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/src/ggml-vulkan/ggml-vulkan.cpp # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / src / ggml-vulkan / ggml-vulkan.cpp` 16821 lines ยท 896817 bytes Raw Blame History 1 #include "ggml-vulkan-common.h" 2 3 static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) { 4 vk::PhysicalDeviceProperties props = device.getProperties(); 5 6 if (props.vendorID == VK_VENDOR_ID_AMD) { 7 const std::vector ext_props = device.enumerateDeviceExtensionProperties(); 8 9 bool amd_shader_core_properties = false; 10 bool integer_dot_product = false; 11 bool subgroup_size_control = false; 12 bool shader_float8 = false; 13 14 for (const auto& properties : ext_props) { 15 if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) { 16 amd_shader_core_properties = true; 17 } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) { 18 integer_dot_product = true; 19 } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) { 20 subgroup_size_control = true; 21 } else if (strcmp("VK_EXT_shader_float8", properties.extensionName) == 0) { 22 shader_float8 = true; 23 } 24 } 25 26 if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) { 27 return vk_device_architecture::OTHER; 28 } 29 30 vk::PhysicalDeviceProperties2 props2; 31 vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd; 32 vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props; 33 vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props; 34 35 props2.pNext = &shader_core_props_amd; 36 shader_core_props_amd.pNext = &integer_dot_props; 37 integer_dot_props.pNext = &subgroup_size_control_props; 38 39 device.getProperties2(&props2); 40 41 if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) { 42 return vk_device_architecture::AMD_GCN; 43 } 44 if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) { 45 // RDNA 46 if (shader_core_props_amd.wavefrontsPerSimd == 20) { 47 return vk_device_architecture::AMD_RDNA1; 48 } 49 if (shader_float8) { 50 return vk_device_architecture::AMD_RDNA4; 51 } 52 if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) { 53 return vk_device_architecture::AMD_RDNA3; 54 } 55 return vk_device_architecture::AMD_RDNA2; 56 } 57 } else if (props.vendorID == VK_VENDOR_ID_INTEL) { 58 const std::vector ext_props = device.enumerateDeviceExtensionProperties(); 59 60 bool subgroup_size_control = false; 61 bool integer_dot_product = false; 62 63 for (const auto& properties : ext_props) { 64 if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) { 65 subgroup_size_control = true; 66 } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) { 67 integer_dot_product = true; 68 } 69 } 70 71 if (!subgroup_size_control || !integer_dot_product) { 72 return vk_device_architecture::OTHER; 73 } 74 75 vk::PhysicalDeviceProperties2 props2; 76 vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props; 77 vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props; 78 79 props2.pNext = &subgroup_size_control_props; 80 subgroup_size_control_props.pNext = &integer_dot_props; 81 device.getProperties2(&props2); 82 83 if (subgroup_size_control_props.minSubgroupSize == 16) { 84 // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8. 85 // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value. 86 // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html 87 // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html 88 return vk_device_architecture::INTEL_XE2; 89 } else if (subgroup_size_control_props.minSubgroupSize == 8 && 90 integer_dot_product && integer_dot_props.integerDotProduct4x8BitPackedSignedAccelerated) { 91 return vk_device_architecture::INTEL_XE1; 92 } 93 } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) { 94 const std::vector ext_props = device.enumerateDeviceExtensionProperties(); 95 96 bool cooperative_matrix = false; 97 bool sm_builtins = false; 98 99 // Detect "pre-turing" based on lack of coopmat support. 100 for (const auto& properties : ext_props) { 101 if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) { 102 cooperative_matrix = true; 103 } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) { 104 sm_builtins = true; 105 } 106 } 107 108 if (!cooperative_matrix) { 109 return vk_device_architecture::NVIDIA_PRE_TURING; 110 } 111 112 if (sm_builtins) { 113 vk::PhysicalDeviceProperties2 props2; 114 vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props; 115 116 props2.pNext = &sm_props; 117 118 device.getProperties2(&props2); 119 120 // Turing has 32, following architectures have 48 121 if (sm_props.shaderWarpsPerSM == 32) { 122 return vk_device_architecture::NVIDIA_TURING; 123 } 124 } 125 } else if(props.vendorID == VK_VENDOR_ID_QUALCOMM){ 126 const std::vector ext_props = device.enumerateDeviceExtensionProperties(); 127 128 bool cooperative_matrix = false; 129 bool cooperative_matrix_conversion = false; 130 131 for (const auto& properties : ext_props) { 132 if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) { 133 cooperative_matrix = true; 134 } else if (strcmp("VK_QCOM_cooperative_matrix_conversion", properties.extensionName) == 0) { 135 cooperative_matrix_conversion = true; 136 } 137 } 138 139 if (cooperative_matrix && cooperative_matrix_conversion) { 140 return vk_device_architecture::QUALCOMM_ADRENO; 141 } 142 } 143 return vk_device_architecture::OTHER; 144 } 145 146 bool ggml_vk_lightning_indexer_k_type_supported(ggml_type type) { 147 return std::find(lightning_indexer_k_types.begin(), lightning_indexer_k_types.end(), type) != lightning_indexer_k_types.end(); 148 } 149 void ggml_vk_print_device_fault_info(const vk_device& device) { 150 if (!device->device_fault || !device->pfn_vkGetDeviceFaultInfoEXT) { 151 return; 152 } 153 154 VkDeviceFaultCountsEXT fault_counts {}; 155 fault_counts.sType = VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT; 156 VkResult res = device->pfn_vkGetDeviceFaultInfoEXT(device->device, &fault_counts, nullptr); 157 if (res != VK_SUCCESS) { 158 GGML_LOG_ERROR("ggml_vulkan: vkGetDeviceFaultInfoEXT (counts) failed: %d\n", res); 159 return; 160 } 161 162 std::vector address_infos(fault_counts.addressInfoCount); 163 std::vector vendor_infos(fault_counts.vendorInfoCount); 164 165 VkDeviceFaultInfoEXT fault_info {}; 166 fault_info.sType = VK_STRUCTURE_TYPE_DEVICE_FAULT_INFO_EXT; 167 fault_info.pAddressInfos = address_infos.data(); 168 fault_info.pVendorInfos = vendor_infos.data(); 169 170 res = device->pfn_vkGetDeviceFaultInfoEXT(device->device, &fault_counts, &fault_info); 171 if (res != VK_SUCCESS) { 172 GGML_LOG_ERROR("ggml_vulkan: vkGetDeviceFaultInfoEXT (info) failed: %d\n", res); 173 return; 174 } 175 176 if (fault_counts.addressInfoCount == 0 && fault_counts.vendorInfoCount == 0 && fault_info.description[0] == '\0') { 177 return; 178 } 179 180 if (fault_info.description[0] != '\0') { 181 GGML_LOG_ERROR("ggml_vulkan: device fault on %s: %s\n", device->name.c_str(), fault_info.description); 182 } 183 184 for (uint32_t i = 0; i < fault_counts.addressInfoCount; i++) { 185 const auto& info = address_infos[i]; 186 GGML_LOG_CONT(" address fault %u: type=%d address=0x%llx precision=0x%llx\n", 187 i, (int)info.addressType, 188 (unsigned long long)info.reportedAddress, 189 (unsigned long long)info.addressPrecision); 190 } 191 for (uint32_t i = 0; i < fault_counts.vendorInfoCount; i++) { 192 const auto& info = vendor_infos[i]; 193 GGML_LOG_CONT(" vendor fault %u: %s (code=0x%llx data=0x%llx)\n", 194 i, info.description, 195 (unsigned long long)info.vendorFaultCode, 196 (unsigned long long)info.vendorFaultData); 197 } 198 } 199 uint64_t ggml_vk_get_node_flops(const ggml_tensor * node) { 200 if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) { 201 const uint64_t m = node->ne[0]; 202 const uint64_t n = node->ne[1]; 203 const uint64_t k = node->src[1]->ne[0]; 204 const uint64_t batch = node->ne[2] * node->ne[3]; 205 return m * n * (k + (k - 1)) * batch; 206 } 207 if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) { 208 const ggml_tensor * knl = node->src[0]; 209 const uint64_t Cout = node->ne[2]; 210 const uint64_t size_K = node->src[1]->ne[2] * knl->ne[0] * knl->ne[1]; 211 const uint64_t size_N = node->ne[3] * node->ne[0] * node->ne[1]; 212 return Cout * size_N * (size_K + (size_K - 1)); 213 } 214 if (node->op == GGML_OP_CONV_3D) { 215 const ggml_tensor * knl = node->src[0]; 216 const uint64_t OC = ggml_get_op_params_i32(node, 11); 217 const uint64_t IC = ggml_get_op_params_i32(node, 9); 218 const uint64_t size_K = IC * knl->ne[0] * knl->ne[1] * knl->ne[2]; 219 const uint64_t size_N = node->ne[3] / OC * node->ne[0] * node->ne[1] * node->ne[2]; 220 return OC * size_N * (size_K + (size_K - 1)); 221 } 222 if (node->op == GGML_OP_FLASH_ATTN_EXT) { 223 const ggml_tensor * q = node->src[0]; 224 const ggml_tensor * k = node->src[1]; 225 const ggml_tensor * v = node->src[2]; 226 return 2ull * q->ne[1] * q->ne[2] * (k->ne[0] + v->ne[0]) * k->ne[1] * q->ne[3]; 227 } 228 return 0; 229 } 230 void ggml_vk_print_node_list(const ggml_cgraph * cgraph, int start, int end) { 231 uint64_t total_flops = 0; 232 int n_ops = 0; 233 for (int j = start; j <= end && j < cgraph->n_nodes; j++) { 234 uint64_t flops = ggml_vk_get_node_flops(cgraph->nodes[j]); 235 total_flops += flops; 236 n_ops++; 237 if (flops > 0) { 238 GGML_LOG_CONT(" node %d: %s (%s) [%.2f GFLOP]\n", 239 j, cgraph->nodes[j]->name, ggml_op_name(cgraph->nodes[j]->op), 240 flops / 1e9); 241 } else { 242 GGML_LOG_CONT(" node %d: %s (%s)\n", 243 j, cgraph->nodes[j]->name, ggml_op_name(cgraph->nodes[j]->op)); 244 } 245 } 246 GGML_LOG_CONT(" total: %d ops, %.2f GFLOP\n", n_ops, total_flops / 1e9); 247 } 248 void ggml_vk_print_device_lost_info(const vk_device& device) { 249 ggml_vk_print_device_fault_info(device); 250 if (device->serialize_submissions && device->diag_cgraph != nullptr && device->diag_prev_start >= 0) { 251 GGML_LOG_ERROR("ggml_vulkan: device lost on %s, likely caused by previous submission (nodes %d to %d):\n", 252 device->name.c_str(), device->diag_prev_start, device->diag_prev_end); 253 ggml_vk_print_node_list(device->diag_cgraph, device->diag_prev_start, device->diag_prev_end); 254 } else { 255 GGML_LOG_ERROR("ggml_vulkan: device lost on %s\n", device->name.c_str()); 256 } 257 } 258 void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT 259 260 uint64_t vk_tensor_offset(const ggml_tensor * tensor) { 261 if (tensor->view_src) { 262 return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base; 263 } 264 return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base; 265 } 266 267 size_t ggml_vk_tensor_buffer_offset(const ggml_backend_vk_context * ctx, const ggml_tensor * t) { 268 // vk_tensor_offset() is relative to vk_ptr_base, but mapped host tensors need an offset relative to their Vulkan buffer. 269 if (ctx->device->uma) { 270 vk_buffer buf = nullptr; 271 size_t off = 0; 272 ggml_vk_host_get(ctx->device, t->data, buf, off); 273 if (buf) { 274 return off; 275 } 276 } 277 return (size_t)(vk_tensor_offset(t) + t->view_offs); 278 } 279 size_t ggml_vk_descriptor_offset(size_t tensor_offset, size_t alignment, size_t type_size) { 280 // Move the descriptor back until its distance to the tensor is divisible by the tensor type size. 281 size_t descriptor_offset = tensor_offset & ~(alignment - 1); 282 while ((tensor_offset - descriptor_offset) % type_size != 0) { 283 GGML_ASSERT(descriptor_offset >= alignment); 284 descriptor_offset -= alignment; 285 } 286 287 return descriptor_offset; 288 } 289 uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t) { 290 const size_t tensor_offset = ggml_vk_tensor_buffer_offset(ctx, t); 291 const size_t descriptor_offset = ggml_vk_descriptor_offset( 292 tensor_offset, ctx->device->properties.limits.minStorageBufferOffsetAlignment, ggml_type_size(t->type)); 293 GGML_ASSERT(tensor_offset - descriptor_offset <= UINT32_MAX); 294 return tensor_offset - descriptor_offset; 295 } 296 297 uint32_t ggml_vk_concat_unit_size(ggml_type type) { 298 const uint32_t type_size = ggml_type_size(type); 299 300 if (!ggml_is_quantized(type)) { 301 return type_size; 302 } 303 304 // Use the widest existing concat shader that evenly divides a quant block. 305 if (type_size % 8 == 0) { 306 return 8; 307 } 308 if (type_size % 4 == 0) { 309 return 4; 310 } 311 if (type_size % 2 == 0) { 312 return 2; 313 } 314 return 1; 315 } 316 bool ggml_vk_concat_supported(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst) { 317 if (src0->type != src1->type || src0->type != dst->type) { 318 return false; 319 } 320 321 if (!ggml_is_quantized(src0->type)) { 322 const size_t type_size = ggml_type_size(src0->type); 323 return type_size == 1 || type_size == 2 || type_size == 4 || type_size == 8; 324 } 325 326 // Quantized tensor rows are block-aligned when created. 327 return ggml_is_contiguous_rows(src0) && ggml_is_contiguous_rows(src1) && ggml_is_contiguous_rows(dst); 328 } 329 static bool vk_instance_initialized = false; 330 331 vk_instance_t vk_instance; 332 333 static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) { 334 const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset}, 335 VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange}); 336 return range; 337 } 338 339 void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) { 340 // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep 341 // during this wait. 342 if (ctx->almost_ready_fence_pending) { 343 VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence", ctx->device); 344 ctx->device->device.resetFences({ ctx->almost_ready_fence }); 345 ctx->almost_ready_fence_pending = false; 346 } 347 348 // Spin (w/pause) waiting for the graph to finish executing. 349 vk::Result result; 350 for (;;) { 351 try { 352 result = ctx->device->device.getFenceStatus(ctx->fence); 353 } catch (vk::DeviceLostError &) { 354 ggml_vk_print_device_lost_info(ctx->device); 355 GGML_LOG_ERROR("ggml_vulkan: getFenceStatus at %s:%d\n", __FILE__, __LINE__); 356 throw; 357 } 358 if (result == vk::Result::eSuccess) { 359 break; 360 } 361 if (result != vk::Result::eNotReady) { 362 GGML_LOG_ERROR("ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__); 363 throw vk::SystemError(vk::make_error_code(result), "ggml_vulkan: getFenceStatus"); 364 } 365 for (uint32_t i = 0; i < 100; ++i) { 366 YIELD(); 367 YIELD(); 368 YIELD(); 369 YIELD(); 370 YIELD(); 371 YIELD(); 372 YIELD(); 373 YIELD(); 374 YIELD(); 375 YIELD(); 376 } 377 } 378 ctx->device->device.resetFences({ ctx->fence }); 379 } 380 381 static bool ggml_vk_strip_decode_vector(const uint32_t * code, size_t word_count, std::vector & out) { 382 static const char kDecodeVectorExt[] = "SPV_NV_cooperative_matrix_decode_vector"; 383 384 if (word_count < 5) { 385 return false; 386 } 387 388 bool uses_decode_vector = false; 389 for (size_t pos = 5; pos < word_count; ) { 390 uint32_t word = code[pos]; 391 uint32_t wc = word >> spv::WordCountShift; 392 uint32_t op = word & spv::OpCodeMask; 393 GGML_ASSERT(wc > 0 && pos + wc <= word_count); 394 if (op == spv::OpExtension && wc >= 2) { 395 const char * s = reinterpret_cast(&code[pos + 1]); 396 if (strcmp(s, kDecodeVectorExt) == 0) { 397 uses_decode_vector = true; 398 break; 399 } 400 } 401 pos += wc; 402 } 403 404 if (!uses_decode_vector) { 405 return false; 406 } 407 408 VK_LOG_DEBUG("ggml_vk_strip_decode_vector: stripping SPV_NV_cooperative_matrix_decode_vector"); 409 410 // Bulk-copy unchanged runs and only break the run when an instruction needs to 411 // be dropped or patched. Use reserve + insert/push_back so the destination buffer 412 // is touched exactly once (no zero-initialization pass from resize()). 413 out.clear(); 414 out.reserve(word_count); 415 416 size_t run_start = 0; 417 auto flush_run = [&](size_t up_to) { 418 if (up_to > run_start) { 419 out.insert(out.end(), code + run_start, code + up_to); 420 } 421 }; 422 423 for (size_t pos = 5; pos < word_count; ) { 424 uint32_t word = code[pos]; 425 uint32_t wc = word >> spv::WordCountShift; 426 uint32_t op = word & spv::OpCodeMask; 427 GGML_ASSERT(wc > 0 && pos + wc <= word_count); 428 429 if (op == spv::OpExtension && wc >= 2) { 430 const char * s = reinterpret_cast(&code[pos + 1]); 431 if (strcmp(s, kDecodeVectorExt) == 0) { 432 flush_run(pos); 433 pos += wc; 434 run_start = pos; 435 continue; 436 } 437 } 438 439 if (op == spv::OpCapability && wc == 2 && code[pos + 1] == kSpvCapabilityCooperativeMatrixDecodeVectorNV) { 440 flush_run(pos); 441 pos += wc; 442 run_start = pos; 443 continue; 444 } 445 446 if (op == kSpvOpCooperativeMatrixLoadTensorNV) { 447 // [opcode/wc][ResultType][Result][Pointer][Object][TensorLayout][MemOperand mask][mem extras...][TA mask][ta extras...] 448 GGML_ASSERT(wc >= 8); 449 450 uint32_t mem_mask = code[pos + 6]; 451 size_t cur = pos + 7; 452 // Each of these MemoryAccess bits (when set) carries one trailing operand. 453 cur += (mem_mask & 0x2) ? 1 : 0; // Aligned 454 cur += (mem_mask & 0x8) ? 1 : 0; // MakePointerAvailable 455 cur += (mem_mask & 0x10) ? 1 : 0; // MakePointerVisible 456 cur += (mem_mask & 0x10000) ? 1 : 0; // AliasScopeINTELMask 457 cur += (mem_mask & 0x20000) ? 1 : 0; // NoAliasINTELMask 458 GGML_ASSERT(cur < pos + wc); 459 460 uint32_t ta_mask = code[cur]; 461 if ((ta_mask & kSpvTensorAddressingDecodeVectorFuncBit) == 0) { 462 pos += wc; 463 continue; // leave instruction inside the current unchanged run 464 } 465 466 flush_run(pos); 467 468 // Append unchanged prefix of the instruction (header through the mem-extras). 469 size_t inst_start = out.size(); 470 size_t pre_n = cur - pos; 471 out.insert(out.end(), code + pos, code + pos + pre_n); 472 473 // Emit TA mask with the DecodeVectorFunc bit cleared. 474 out.push_back(ta_mask & ~kSpvTensorAddressingDecodeVectorFuncBit); 475 476 // TA extras: TensorView (0x1) and DecodeFunc (0x2) are kept verbatim; 477 // DecodeVectorFunc (0x4) is dropped along with its trailing id operand. 478 size_t keep_ta_extras = ((ta_mask & 0x1) ? 1 : 0) + ((ta_mask & 0x2) ? 1 : 0); 479 if (keep_ta_extras) { 480 out.insert(out.end(), code + cur + 1, code + cur + 1 + keep_ta_extras); 481 } 482 483 GGML_ASSERT(wc == pre_n + 1 + keep_ta_extras + 1); 484 485 // Patch the instruction header with the new (one-shorter) word count. 486 uint32_t new_wc = wc - 1; 487 out[inst_start] = (new_wc << spv::WordCountShift) | op; 488 489 pos += wc; 490 run_start = pos; 491 continue; 492 } 493 494 pos += wc; 495 } 496 497 flush_run(word_count); 498 return true; 499 } 500 501 static bool ggml_vk_roll_bk_loop(const uint32_t * code, size_t word_count, std::vector & out) { 502 if (word_count < 5) { 503 return false; 504 } 505 506 struct vk_spv_loop { 507 size_t header; 508 size_t end; 509 uint32_t control; 510 }; 511 512 std::vector loops; 513 514 // Collect a list of all loops in the module. 515 for (size_t pos = 5; pos < word_count; ) { 516 const uint32_t wc = code[pos] >> spv::WordCountShift; 517 const uint32_t op = code[pos] & spv::OpCodeMask; 518 if (wc == 0 || pos + wc > word_count) { 519 return false; 520 } 521 522 if (op == spv::OpLoopMerge && wc >= 4) { loops.push_back({ pos, 0, code[pos + 3] }); } 523 524 if (op == spv::OpLabel && wc >= 2) { 525 for (auto & l : loops) { 526 if (l.end == 0 && code[l.header + 1] == code[pos + 1]) { l.end = pos; } 527 } 528 } 529 530 pos += wc; 531 } 532 533 auto encloses = [](const vk_spv_loop & a, const vk_spv_loop & b) { 534 return a.header < b.header && b.header < a.end; 535 }; 536 537 // Find the BK loop. 538 const vk_spv_loop * bk = nullptr; 539 for (const auto & h : loops) { 540 if (h.control != spv::LoopControlUnrollMask) { 541 continue; 542 } 543 const vk_spv_loop * parent = nullptr; 544 bool has_child = false; 545 for (const auto & g : loops) { 546 if (encloses(g, h) && (!parent || g.header > parent->header)) { 547 parent = &g; 548 } 549 if (encloses(h, g)) { 550 has_child = true; 551 } 552 } 553 // BK loop should be the last loop nested inside the loop with no hint 554 // and have at least one child loop. 555 if (parent && 556 parent->control == spv::LoopControlMaskNone && 557 has_child && 558 (!bk || h.header > bk->header)) { 559 bk = &h; 560 } 561 } 562 if (!bk) { 563 return false; 564 } 565 566 // set DontUnroll instead of Unroll 567 out.assign(code, code + word_count); 568 out[bk->header + 3] = spv::LoopControlDontUnrollMask; 569 return true; 570 } 571 572 static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint, 573 uint32_t parameter_count, std::array wg_denoms, std::vector specialization_constants, 574 bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) { 575 VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count << 576 ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " << 577 disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")"); 578 GGML_ASSERT(parameter_count > 0); 579 GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT); 580 GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT 581 582 vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast(spv_data)); 583 584 // Patch SPIR-V to enable supported FP16 float controls, avoiding the need 585 // for separate shader variants. 586 std::vector spirv; 587 if (device->float_controls_rte_fp16 || device->float_controls_denorm_preserve_fp16) { 588 const uint32_t* spv_words = reinterpret_cast(spv_data); 589 size_t word_count = spv_size / sizeof(uint32_t); 590 spirv.assign(spv_words, spv_words + word_count); 591 592 // Find insertion points respecting SPIR-V layout order: 593 // Header(5) -> OpCapability -> OpExtension -> ... -> OpEntryPoint -> OpExecutionMode -> ... 594 size_t pos = 5; // skip header 595 size_t cap_insert_pos = pos; 596 size_t ext_insert_pos = pos; 597 size_t exec_insert_pos = pos; 598 uint32_t entry_point_id = 0; 599 600 while (pos < spirv.size()) { 601 uint32_t opcode = spirv[pos] & spv::OpCodeMask; 602 uint32_t len = spirv[pos] >> spv::WordCountShift; 603 if (len == 0) break; 604 605 if (opcode == spv::OpCapability) { 606 cap_insert_pos = pos + len; 607 ext_insert_pos = pos + len; 608 } else if (opcode == spv::OpExtension) { 609 ext_insert_pos = pos + len; 610 } else if (opcode == spv::OpEntryPoint) { 611 entry_point_id = spirv[pos + 2]; 612 exec_insert_pos = pos + len; 613 } else if (opcode == spv::OpExecutionMode || opcode == spv::OpExecutionModeId) { 614 exec_insert_pos = pos + len; 615 } else if (entry_point_id != 0) { 616 break; 617 } 618 619 pos += len; 620 } 621 622 // Insert from latest position first so earlier indices stay valid. 623 624 if (device->float_controls_rte_fp16) { 625 // OpExecutionMode %entrypoint RoundingModeRTE 16 626 uint32_t exec_mode[] = { (4u << spv::WordCountShift) | spv::OpExecutionMode, entry_point_id, spv::ExecutionModeRoundingModeRTE, 16 }; 627 spirv.insert(spirv.begin() + exec_insert_pos, std::begin(exec_mode), std::end(exec_mode)); 628 } 629 630 if (device->float_controls_denorm_preserve_fp16) { 631 // OpExecutionMode %entrypoint DenormPreserve 16 632 uint32_t exec_mode[] = { (4u << spv::WordCountShift) | spv::OpExecutionMode, entry_point_id, spv::ExecutionModeDenormPreserve, 16 }; 633 spirv.insert(spirv.begin() + exec_insert_pos, std::begin(exec_mode), std::end(exec_mode)); 634 } 635 636 // OpExtension "SPV_KHR_float_controls" 637 const char ext_str[] = "SPV_KHR_float_controls"; 638 size_t ext_str_words = CEIL_DIV(sizeof(ext_str), sizeof(uint32_t)); 639 std::vector extension(1 + ext_str_words, 0); 640 extension[0] = (uint32_t)((1 + ext_str_words) << spv::WordCountShift) | spv::OpExtension; 641 memcpy(&extension[1], ext_str, sizeof(ext_str)); 642 spirv.insert(spirv.begin() + ext_insert_pos, extension.begin(), extension.end()); 643 644 if (device->float_controls_rte_fp16) { 645 // OpCapability RoundingModeRTE 646 uint32_t capability[] = { (2u << spv::WordCountShift) | spv::OpCapability, spv::CapabilityRoundingModeRTE }; 647 spirv.insert(spirv.begin() + cap_insert_pos, std::begin(capability), std::end(capability)); 648 } 649 650 if (device->float_controls_denorm_preserve_fp16) { 651 // OpCapability DenormPreserve 652 uint32_t capability[] = { (2u << spv::WordCountShift) | spv::OpCapability, spv::CapabilityDenormPreserve }; 653 spirv.insert(spirv.begin() + cap_insert_pos, std::begin(capability), std::end(capability)); 654 } 655 656 shader_module_create_info = vk::ShaderModuleCreateInfo({}, spirv.size() * sizeof(uint32_t), spirv.data()); 657 } 658 659 #if defined(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) 660 if (device->coopmat2 && !device->coopmat2_decode_vector) { 661 const uint32_t * src = spirv.empty() ? reinterpret_cast(spv_data) : spirv.data(); 662 size_t src_n = spirv.empty() ? spv_size / sizeof(uint32_t) : spirv.size(); 663 std::vector stripped; 664 if (ggml_vk_strip_decode_vector(src, src_n, stripped)) { 665 spirv = std::move(stripped); 666 shader_module_create_info = vk::ShaderModuleCreateInfo({}, spirv.size() * sizeof(uint32_t), spirv.data()); 667 } 668 } 669 #endif 670 671 #if VK_HEADER_VERSION >= 287 672 // Roll the mul_mm BK loop on Asahi Linux. Skip bf16 and the mul_mmq pipelines. 673 if (device->driver_id == vk::DriverId::eMesaHoneykrisp && 674 pipeline->name.rfind("matmul", 0) == 0 && 675 pipeline->name.find("bf16") == std::string::npos && 676 pipeline->name.find("q8_1") == std::string::npos) { 677 const uint32_t * src = spirv.empty() ? reinterpret_cast(spv_data) : spirv.data(); 678 size_t src_n = spirv.empty() ? spv_size / sizeof(uint32_t) : spirv.size(); 679 std::vector rolled; 680 if (ggml_vk_roll_bk_loop(src, src_n, rolled)) { 681 spirv = std::move(rolled); 682 shader_module_create_info = vk::ShaderModuleCreateInfo({}, spirv.size() * sizeof(uint32_t), spirv.data()); 683 } 684 } 685 #endif 686 687 try { 688 pipeline->shader_module = device->device.createShaderModule(shader_module_create_info); 689 } catch (const vk::SystemError& e) { 690 std::cerr << "ggml_vulkan: shader module creation failed for " << pipeline->name << ": " << e.what() << std::endl; 691 throw; 692 } 693 694 vk::PushConstantRange pcr( 695 vk::ShaderStageFlagBits::eCompute, 696 0, 697 pipeline->push_constant_size 698 ); 699 700 vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr); 701 try { 702 pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info); 703 } catch (const vk::SystemError& e) { 704 std::cerr << "ggml_vulkan: pipeline layout creation failed for " << pipeline->name << ": " << e.what() << std::endl; 705 throw; 706 } 707 708 std::vector specialization_entries(specialization_constants.size()); 709 710 for (size_t i = 0; i < specialization_constants.size(); i++) { 711 specialization_entries[i].constantID = i; 712 specialization_entries[i].offset = i * sizeof(uint32_t); 713 specialization_entries[i].size = sizeof(uint32_t); 714 } 715 716 vk::SpecializationInfo specialization_info( 717 specialization_entries.size(), 718 specialization_entries.data(), 719 specialization_constants.size() * sizeof(uint32_t), 720 specialization_constants.data() 721 ); 722 723 vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{}; 724 725 if (device->subgroup_require_full_support && require_full_subgroups) { 726 pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT; 727 } 728 729 vk::PipelineShaderStageCreateInfo pipeline_shader_create_info( 730 pipeline_shader_stage_create_flags, 731 vk::ShaderStageFlagBits::eCompute, 732 pipeline->shader_module, 733 entrypoint.c_str(), 734 &specialization_info); 735 736 vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info; 737 pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size; 738 if (device->subgroup_size_control && required_subgroup_size > 0) { 739 GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size); 740 pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info); 741 } 742 743 vk::ComputePipelineCreateInfo compute_pipeline_create_info( 744 device->pipeline_executable_properties_support ? 745 vk::PipelineCreateFlagBits::eCaptureStatisticsKHR : 746 vk::PipelineCreateFlags{}, 747 pipeline_shader_create_info, 748 pipeline->layout); 749 750 vk::PipelineRobustnessCreateInfoEXT rci; 751 752 if (device->pipeline_robustness && disable_robustness) { 753 rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled; 754 rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled; 755 compute_pipeline_create_info.setPNext(&rci); 756 } 757 758 #if defined(VK_EXT_shader_64bit_indexing) 759 vk::PipelineCreateFlags2CreateInfo pipelineFlags2CreateInfo; 760 if (pipeline->is_64b_indexing) 761 { 762 pipelineFlags2CreateInfo.flags = vk::PipelineCreateFlagBits2::e64BitIndexingEXT; 763 if (device->pipeline_executable_properties_support) { 764 pipelineFlags2CreateInfo.flags |= vk::PipelineCreateFlagBits2::eCaptureStatisticsKHR; 765 } 766 pipelineFlags2CreateInfo.setPNext(compute_pipeline_create_info.pNext); 767 compute_pipeline_create_info.setPNext(&pipelineFlags2CreateInfo); 768 } 769 #endif 770 771 try { 772 pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value; 773 } catch (const vk::SystemError& e) { 774 std::cerr << "ggml_vulkan: compute pipeline creation failed for " << pipeline->name << ": " << e.what() << std::endl; 775 throw; 776 } 777 778 if (vk_instance.debug_utils_support) { 779 vk::DebugUtilsObjectNameInfoEXT duoni; 780 duoni.objectType = vk::ObjectType::ePipeline; 781 duoni.pObjectName = pipeline->name.c_str(); 782 duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast(pipeline->pipeline)); 783 vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast(duoni)); 784 } 785 786 if (device->pipeline_executable_properties_support) { 787 vk::PipelineExecutableInfoKHR executableInfo; 788 executableInfo.pipeline = pipeline->pipeline; 789 790 auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo); 791 792 bool print_stats = !vk_pipeline_stats_filter.empty() && 793 pipeline->name.find(vk_pipeline_stats_filter) != std::string::npos; 794 if (print_stats) { 795 std::cerr << "ggml_vulkan: pipeline stats for " << pipeline->name << ":" << std::endl; 796 } 797 798 for (auto & s : statistics) { 799 if (print_stats) { 800 std::cerr << "ggml_vulkan: " << s.name.data() << ": "; 801 switch (s.format) { 802 case vk::PipelineExecutableStatisticFormatKHR::eBool32: 803 std::cerr << (s.value.b32 ? "true" : "false"); 804 break; 805 case vk::PipelineExecutableStatisticFormatKHR::eInt64: 806 std::cerr << s.value.i64; 807 break; 808 case vk::PipelineExecutableStatisticFormatKHR::eUint64: 809 std::cerr << s.value.u64; 810 break; 811 case vk::PipelineExecutableStatisticFormatKHR::eFloat64: 812 std::cerr << s.value.f64; 813 break; 814 } 815 std::cerr << std::endl; 816 } 817 // "Register Count" is reported by NVIDIA drivers. 818 if (strcmp(s.name, "Register Count") == 0) { 819 VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers"); 820 pipeline->register_count = (uint32_t)s.value.u64; 821 } 822 } 823 } 824 825 { 826 std::lock_guard guard(device->compile_mutex); 827 device->all_pipelines.push_back(pipeline); 828 pipeline->compiled = true; 829 pipeline->compile_pending = false; 830 } 831 device->compile_cv.notify_all(); 832 } 833 834 void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) { 835 VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")"); 836 device.destroyPipelineLayout(pipeline->layout); 837 838 device.destroyShaderModule(pipeline->shader_module); 839 840 device.destroyPipeline(pipeline->pipeline); 841 } 842 843 void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) { 844 VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")"); 845 ctx->pipeline_descriptor_set_requirements += n; 846 if (!pipeline->compiled) { 847 ggml_vk_load_shaders(ctx->device, pipeline); 848 } 849 ggml_pipeline_allocate_descriptor_sets(ctx); 850 } 851 852 void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) { 853 854 if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) { 855 // Enough descriptors are available 856 return; 857 } 858 859 vk_device& device = ctx->device; 860 861 // Grow by 50% to avoid frequent allocations 862 uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements}); 863 uint32_t to_alloc = needed - ctx->descriptor_sets.size(); 864 uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE; 865 uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE; 866 867 while (to_alloc > 0) { 868 const uint32_t alloc_count = std::min(pool_remaining, to_alloc); 869 to_alloc -= alloc_count; 870 pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE; 871 872 if (pool_idx >= ctx->descriptor_pools.size()) { 873 vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE); 874 vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size); 875 ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info)); 876 } 877 878 std::vector layouts(alloc_count); 879 for (uint32_t i = 0; i < alloc_count; i++) { 880 layouts[i] = device->dsl; 881 } 882 vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data()); 883 std::vector sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info); 884 ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end()); 885 886 pool_idx++; 887 } 888 ctx->descriptor_set_bindings.resize(ctx->descriptor_sets.size()); 889 } 890 891 static vk_command_buffer* ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) { 892 VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()"); 893 vk::CommandBufferAllocateInfo command_buffer_alloc_info( 894 p.pool, 895 vk::CommandBufferLevel::ePrimary, 896 1); 897 const std::vector cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info); 898 p.cmd_buffers.push_back({ cmd_buffers.front(), 0, true }); 899 return &p.cmd_buffers[p.cmd_buffers.size()-1]; 900 } 901 902 void ggml_vk_submit(vk_context& ctx, vk::Fence fence) { 903 if (ctx->seqs.empty()) { 904 if (fence) { 905 ctx->p->q->handle->submit({}, fence); 906 } 907 return; 908 } 909 VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")"); 910 911 std::vector> tl_wait_vals; 912 std::vector> tl_signal_vals; 913 std::vector> tl_wait_semaphores; 914 std::vector> tl_signal_semaphores; 915 std::vector tl_submit_infos; 916 std::vector submit_infos; 917 int idx = -1; 918 std::vector> stage_flags; 919 920 size_t reserve = 0; 921 922 for (const auto& sequence : ctx->seqs) { 923 reserve += sequence.size(); 924 } 925 926 // Pre-reserve vectors to prevent reallocation, which invalidates pointers 927 tl_wait_semaphores.reserve(reserve); 928 tl_wait_vals.reserve(reserve); 929 tl_signal_semaphores.reserve(reserve); 930 tl_signal_vals.reserve(reserve); 931 tl_submit_infos.reserve(reserve); 932 submit_infos.reserve(reserve); 933 stage_flags.reserve(reserve); 934 935 for (const auto& sequence : ctx->seqs) { 936 for (const auto& submission : sequence) { 937 if (submission.ready) { 938 while (submission.ready->load(std::memory_order_acquire) < submission.ready_value) { 939 YIELD(); 940 } 941 } 942 stage_flags.push_back({}); 943 idx++; 944 tl_wait_vals.push_back({}); 945 tl_wait_semaphores.push_back({}); 946 tl_signal_vals.push_back({}); 947 tl_signal_semaphores.push_back({}); 948 for (size_t i = 0; i < submission.wait_semaphores.size(); i++) { 949 stage_flags[idx].push_back(ctx->p->q->stage_flags); 950 tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value); 951 tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s); 952 } 953 for (size_t i = 0; i < submission.signal_semaphores.size(); i++) { 954 tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value); 955 tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s); 956 } 957 tl_submit_infos.push_back({ 958 (uint32_t) submission.wait_semaphores.size(), 959 tl_wait_vals[idx].data(), 960 (uint32_t) submission.signal_semaphores.size(), 961 tl_signal_vals[idx].data(), 962 }); 963 tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo; 964 tl_submit_infos[idx].pNext = nullptr; 965 vk::SubmitInfo si{ 966 (uint32_t) submission.wait_semaphores.size(), 967 tl_wait_semaphores[idx].data(), 968 stage_flags[idx].data(), 969 1, 970 &submission.buffer->buf, 971 (uint32_t) submission.signal_semaphores.size(), 972 tl_signal_semaphores[idx].data(), 973 }; 974 si.setPNext(&tl_submit_infos[idx]); 975 submit_infos.push_back(si); 976 } 977 } 978 979 ctx->p->q->handle->submit(submit_infos, fence); 980 981 ctx->seqs.clear(); 982 } 983 984 uint32_t ggml_vk_find_queue_family_index(std::vector& queue_family_props, const vk::QueueFlags& required, const vk::QueueFlags& avoid, int32_t compute_index, uint32_t min_num_queues) { 985 VK_LOG_DEBUG("ggml_vk_find_queue_family_index()"); 986 const uint32_t qfsize = queue_family_props.size(); 987 988 // Try with avoid preferences first 989 for (uint32_t i = 0; i < qfsize; i++) { 990 if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required && !(queue_family_props[i].queueFlags & avoid)) { 991 return i; 992 } 993 } 994 995 // Fall back to only required 996 for (size_t i = 0; i < qfsize; i++) { 997 if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) { 998 return i; 999 } 1000 } 1001 1002 // Fall back to reusing compute queue 1003 for (size_t i = 0; i < qfsize; i++) { 1004 if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) { 1005 return i; 1006 } 1007 } 1008 1009 // Fall back to ignoring min_num_queries 1010 for (size_t i = 0; i < qfsize; i++) { 1011 if (queue_family_props[i].queueFlags & required) { 1012 return i; 1013 } 1014 } 1015 1016 // All commands that are allowed on a queue that supports transfer operations are also allowed on a queue that supports either graphics or compute operations. 1017 // Thus, if the capabilities of a queue family include VK_QUEUE_GRAPHICS_BIT or VK_QUEUE_COMPUTE_BIT, then reporting the VK_QUEUE_TRANSFER_BIT capability separately for that queue family is optional. 1018 if (compute_index >= 0) { 1019 return compute_index; 1020 } 1021 1022 std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl; 1023 1024 for(auto &q_family : queue_family_props) { 1025 std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl; 1026 } 1027 abort(); 1028 } 1029 1030 std::unique_ptr ggml_vk_create_queue(vk_device& device, uint32_t queue_family_index, uint32_t queue_index, vk::PipelineStageFlags&& stage_flags, bool transfer_only) { 1031 VK_LOG_DEBUG("ggml_vk_create_queue()"); 1032 std::lock_guard guard(device->mutex); 1033 1034 auto q = std::make_unique(); 1035 q->queue_family_index = queue_family_index; 1036 q->transfer_only = transfer_only; 1037 1038 std::shared_ptr h; 1039 vk::DeviceQueueInfo2 queue_info2{}; 1040 queue_info2.queueFamilyIndex = queue_family_index; 1041 queue_info2.queueIndex = queue_index; 1042 1043 if (device->has_internally_synchronized_queues) { 1044 h = std::make_shared(); 1045 queue_info2.flags = eInternallySynchronizedKHR; 1046 } else { 1047 h = std::make_shared(); 1048 } 1049 1050 h->queue = device->device.getQueue2(queue_info2); 1051 h->device = device; 1052 // Avoid concurrent submissions on NVIDIA due to driver bug. 1053 if (device->vendor_id == VK_VENDOR_ID_NVIDIA) { 1054 h->device_submit_mutex = &device->queue_submit_mutex; 1055 } 1056 q->handle = h; 1057 1058 q->cmd_pool.init(device, q.get()); 1059 1060 q->stage_flags = stage_flags; 1061 return q; 1062 } 1063 1064 std::unique_ptr ggml_vk_create_aliased_queue(vk_device& device, const std::unique_ptr& source) { 1065 std::lock_guard guard(device->mutex); 1066 auto q = std::make_unique(); 1067 q->handle = source->handle; 1068 q->queue_family_index = source->queue_family_index; 1069 q->stage_flags = source->stage_flags; 1070 q->transfer_only = source->transfer_only; 1071 q->cmd_pool.init(device, q.get()); 1072 return q; 1073 } 1074 1075 vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) { 1076 vk_context result = std::make_shared(); 1077 VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")"); 1078 ctx->gc.contexts.emplace_back(result); 1079 result->p = &p; 1080 return result; 1081 } 1082 1083 vk_context ggml_vk_create_temporary_context(vk_command_pool& p) { 1084 vk_context result = std::make_shared(); 1085 VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")"); 1086 result->p = &p; 1087 return result; 1088 } 1089 1090 vk::Semaphore ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) { 1091 VK_LOG_DEBUG("ggml_vk_create_binary_semaphore()"); 1092 if (ctx->binary_semaphore_idx >= ctx->gc.semaphores.size()) { 1093 vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 }; 1094 vk::SemaphoreCreateInfo ci{}; 1095 ci.setPNext(&tci); 1096 vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci); 1097 ctx->gc.semaphores.push_back({ semaphore, 0 }); 1098 } 1099 return ctx->gc.semaphores[ctx->binary_semaphore_idx++].s; 1100 } 1101 1102 static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) { 1103 VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()"); 1104 if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) { 1105 vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 }; 1106 vk::SemaphoreCreateInfo ci{}; 1107 ci.setPNext(&tci); 1108 vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci); 1109 ctx->gc.tl_semaphores.push_back({ semaphore, 0 }); 1110 } 1111 return &ctx->gc.tl_semaphores[ctx->semaphore_idx++]; 1112 } 1113 1114 static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) { 1115 if (ctx->event_idx >= ctx->gc.events.size()) { 1116 ctx->gc.events.push_back(ctx->device->device.createEvent({})); 1117 } 1118 return ctx->gc.events[ctx->event_idx++]; 1119 } 1120 1121 void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) { 1122 VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()"); 1123 1124 // Requires command buffers to be done 1125 device->device.resetCommandPool(p.pool); 1126 // Don't clear the command buffers and mark them as not in use. 1127 // This allows us to reuse them 1128 for (auto& cmd_buffer : p.cmd_buffers) { 1129 cmd_buffer.in_use = false; 1130 } 1131 } 1132 1133 void ggml_vk_queue_command_pools_cleanup(vk_device& device) { 1134 VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()"); 1135 1136 // Arbitrary frequency to cleanup/reuse command buffers 1137 static constexpr uint32_t cleanup_frequency = 10; 1138 1139 if (device->compute_queue && device->compute_queue->cmd_pool.buffers_in_use() >= cleanup_frequency) { 1140 ggml_vk_command_pool_cleanup(device, device->compute_queue->cmd_pool); 1141 } 1142 if (device->transfer_queue && device->transfer_queue->cmd_pool.buffers_in_use() >= cleanup_frequency) { 1143 ggml_vk_command_pool_cleanup(device, device->transfer_queue->cmd_pool); 1144 } 1145 } 1146 1147 vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset) { 1148 return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) }; 1149 } 1150 1151 void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) { 1152 VK_LOG_DEBUG("ggml_vk_sync_buffers()"); 1153 1154 const bool transfer_queue = subctx->p->q->transfer_only; 1155 1156 if (ctx) { 1157 ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false; 1158 } 1159 1160 subctx->s->buffer->buf.pipelineBarrier( 1161 subctx->p->q->stage_flags, 1162 subctx->p->q->stage_flags, 1163 {}, 1164 { { 1165 { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }, 1166 { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) } 1167 } }, 1168 {}, 1169 {} 1170 ); 1171 } 1172 1173 static void ggml_vk_reset_event(vk_context& ctx, vk::Event& event) { 1174 VK_LOG_DEBUG("ggml_vk_set_event()"); 1175 1176 ctx->s->buffer->buf.resetEvent( 1177 event, 1178 ctx->p->q->stage_flags 1179 ); 1180 } 1181 1182 void ggml_vk_set_event(vk_context& ctx, vk::Event& event) { 1183 VK_LOG_DEBUG("ggml_vk_set_event()"); 1184 1185 ctx->s->buffer->buf.setEvent( 1186 event, 1187 ctx->p->q->stage_flags 1188 ); 1189 } 1190 1191 void ggml_vk_wait_events(vk_context& ctx, std::vector&& events) { 1192 VK_LOG_DEBUG("ggml_vk_wait_events()"); 1193 if (events.empty()) { 1194 return; 1195 } 1196 1197 ctx->s->buffer->buf.waitEvents( 1198 events, 1199 ctx->p->q->stage_flags, 1200 ctx->p->q->stage_flags, 1201 {}, 1202 {}, 1203 {} 1204 ); 1205 } 1206 1207 static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc) { 1208 1209 vk_fa_tuning_params result{}; 1210 result.path = FA_SCALAR; 1211 1212 if (device->vendor_id == VK_VENDOR_ID_INTEL) { 1213 // Disable subgroup use due to performance issues when enforcing subgroup sizes 1214 result.subgroup_size = 32; 1215 result.disable_subgroups = true; 1216 } else if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN) { 1217 result.subgroup_size = n_rows < 4 ? 32 : device->subgroup_size; 1218 } else { 1219 result.subgroup_size = device->subgroup_size; 1220 } 1221 1222 // Row split splits the workgroup so that synchronization only has to happen within subgroups, which avoids barriers 1223 uint32_t row_split_max_hsk = 64; 1224 if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN && !device->uma) { 1225 row_split_max_hsk = n_rows <= 8 ? 64 : 128; 1226 } 1227 result.row_split = (n_rows < 4 || hsk <= row_split_max_hsk) ? 1 : 4; 1228 1229 if (result.subgroup_size > 32 && (n_rows < 4 || hsk < (result.row_split == 1 ? 128 : 64))) { 1230 result.workgroup_size = result.subgroup_size * 2; 1231 } else { 1232 result.workgroup_size = result.subgroup_size * 4; 1233 } 1234 1235 const uint32_t D = hsk | hsv; 1236 1237 const bool reduce_block_rows = D & 8 || n_kv < 1024 || device->vendor_id == VK_VENDOR_ID_INTEL; 1238 1239 if (n_rows == 1) { 1240 result.block_rows = 1; 1241 result.block_cols = 64; 1242 } else { 1243 // row_split 1 means higher register use per row, so block size has to be adjusted 1244 if (result.row_split == 1) { 1245 result.block_rows = n_rows == 2 ? 2 : ((n_rows <= 4 || reduce_block_rows) ? 4 : 8); 1246 } else { 1247 result.block_rows = n_rows <= 4 ? 4 : ((n_rows <= 8 || reduce_block_rows) ? 8 : 16); 1248 } 1249 1250 result.block_cols = (D & 8) ? 64 : 32; 1251 } 1252 1253 const uint32_t D_lsb = D ^ (D & (D-1)); // extract lowest set bit 1254 1255 result.d_split = std::min(std::min(result.subgroup_size, 8u), D_lsb / 4); 1256 1257 result.shmem_staging = (device->vendor_id == VK_VENDOR_ID_NVIDIA && hsk < 256 && hsv < 256) ? 1 : 0; 1258 1259 if (!reduce_block_rows && !ggml_vk_flash_attn_scalar_shmem_support(device, result, hsk, hsv, f32acc, k_type, v_type)) { 1260 result.block_rows /= 2; 1261 } 1262 1263 // On AMD RDNA, for small head sizes and big batch size the shader uses few registers, so too many subgroups get scheduled 1264 // at once and end up thrashing the cache. Fix this by setting a large (unused) shmem buffer that reduces occupancy. 1265 // This targets an occupancy of 4 subgroups per SIMD. 1266 if (device->vendor_id == VK_VENDOR_ID_AMD && device->properties.limits.maxComputeSharedMemorySize == 65536) { 1267 if (device->architecture != AMD_GCN && n_rows >= 64 && hsk <= 128) { 1268 // 30kb target for hsk > 64, 26kb for <= 64 due to smaller workgroup size 1269 // Values are guessed, tested on RDNA2 1270 result.limit_occupancy_shmem = (hsk <= 64 ? 26 : 30) * 1024 / 4 / 4; 1271 } else if (device->architecture == AMD_GCN && n_rows <= 8 && hsk >= 256) { 1272 // Same thing for GCN, with an occupancy target of 2 subgroups per SIMD. 1273 // Here low-batch FA with large head size is affected. 1274 // n_rows < 4 switch because workgroup size switches from 128 to 256 there. 1275 result.limit_occupancy_shmem = (n_rows < 4 ? 14 : 26) * 1024 / 4 / 4; 1276 } 1277 } 1278 1279 return result; 1280 } 1281 1282 static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc) { 1283 GGML_UNUSED(n_rows); 1284 GGML_UNUSED(n_kv); 1285 GGML_UNUSED(k_type); 1286 GGML_UNUSED(v_type); 1287 GGML_UNUSED(f32acc); 1288 1289 vk_fa_tuning_params result{}; 1290 result.path = FA_COOPMAT1; 1291 1292 const uint32_t D = hsk | hsv; 1293 1294 const uint32_t coopmat_block_rows = 16; 1295 const uint32_t coopmat_block_cols = 16; 1296 1297 const uint32_t num_subgroups = 4; 1298 1299 result.block_rows = coopmat_block_rows; 1300 result.block_cols = coopmat_block_cols * num_subgroups; 1301 result.row_split = num_subgroups; 1302 result.subgroup_size = device->subgroup_size; 1303 result.workgroup_size = num_subgroups * result.subgroup_size; 1304 1305 const uint32_t D_lsb = D ^ (D & (D-1)); // extract lowest set bit 1306 result.d_split = std::min(std::min(result.subgroup_size, 8u), D_lsb / 4); 1307 1308 result.shmem_staging = (device->vendor_id == VK_VENDOR_ID_NVIDIA && hsk < 256 && hsv < 256) ? 1 : 0; 1309 1310 return result; 1311 } 1312 1313 static vk_fa_tuning_params get_fa_tuning_params_coopmat2(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc) { 1314 GGML_UNUSED(n_kv); 1315 GGML_UNUSED(f32acc); 1316 1317 vk_fa_tuning_params result{}; 1318 result.path = FA_COOPMAT2; 1319 1320 const uint32_t D = hsk | hsv; 1321 1322 const bool small_rows = n_rows < 32; 1323 1324 if (small_rows) { 1325 result.block_rows = 32; 1326 result.block_cols = 32; 1327 } else if (ggml_is_quantized(k_type) || ggml_is_quantized(v_type) || hsk >= 256 || hsv >= 256) { 1328 result.block_rows = (hsk >= 512 || hsv >= 512) ? 32 : 64; 1329 result.block_cols = 32; 1330 } else { 1331 result.block_rows = 64; 1332 result.block_cols = 64; 1333 } 1334 1335 result.subgroup_size = device->subgroup_size; 1336 result.workgroup_size = (small_rows && (D % 32) == 0) ? 256 : 128; 1337 1338 return result; 1339 } 1340 1341 vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc) { 1342 FaCodePath path = device->coopmat2 ? FA_COOPMAT2 : 1343 device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR; 1344 1345 if (path == FA_COOPMAT2 && k_type == GGML_TYPE_BF16 && !device->coopmat2_bf16_support) { 1346 path = FA_COOPMAT1; 1347 } 1348 if (path == FA_COOPMAT1 && k_type == GGML_TYPE_BF16 && !device->coopmat_bf16_support) { 1349 path = FA_SCALAR; 1350 } 1351 1352 if (path == FA_COOPMAT1 && device->architecture == vk_device_architecture::NVIDIA_TURING) { 1353 // Nvidia compiler bug, see https://github.com/ggml-org/llama.cpp/pull/19075#issuecomment-`3820716090` 1354 path = FA_SCALAR; 1355 } 1356 1357 if (path == FA_COOPMAT1) { 1358 bool shape_ok = (f32acc && device->coopmat_support_16x16x16_f32acc) || 1359 (!f32acc && device->coopmat_support_16x16x16_f16acc); 1360 const vk_fa_tuning_params params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc); 1361 bool shmem_ok = ggml_vk_flash_attn_coopmat_shmem_support(device, params, hsk, hsv, f32acc, k_type, v_type); 1362 1363 if (!shape_ok || !shmem_ok) { 1364 path = FA_SCALAR; 1365 } 1366 } 1367 1368 // scalar is faster than coopmat when N==1 1369 if (n_rows == 1 && (path == FA_COOPMAT1 || path == FA_COOPMAT2)) { 1370 path = FA_SCALAR; 1371 } 1372 1373 switch (path) { 1374 case FA_SCALAR: 1375 return get_fa_tuning_params_scalar(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc); 1376 case FA_COOPMAT1: 1377 return get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc); 1378 case FA_COOPMAT2: 1379 return get_fa_tuning_params_coopmat2(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc); 1380 default: 1381 throw std::runtime_error("unsupported FaCodePath"); 1382 } 1383 } 1384 1385 vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc, 1386 bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type) { 1387 const bool old_amd_windows = device->vendor_id == VK_VENDOR_ID_AMD && device->driver_id == vk::DriverId::eAmdProprietary && 1388 (device->architecture == AMD_GCN || device->architecture == AMD_RDNA1 || device->architecture == AMD_RDNA2); 1389 1390 uint32_t flags = (use_mask_opt ? 1 : 0) | 1391 (use_mask ? 2 : 0) | 1392 (use_logit_softcap ? 4 : 0) | 1393 (old_amd_windows ? 8 : 0) | 1394 (use_sparse ? 16 : 0); 1395 1396 const uint32_t subgroup_size = params.disable_subgroups ? 0 : params.subgroup_size; 1397 1398 return vk_fa_pipeline_state{hsk, hsv, params.block_rows, params.block_cols, params.d_split, params.row_split, params.shmem_staging, params.path, params.workgroup_size, subgroup_size, aligned, f32acc, flags, params.limit_occupancy_shmem, k_type, v_type}; 1399 } 1400 1401 static uint32_t fa_block_bytes(ggml_type t) { 1402 if (t == GGML_TYPE_F32) { 1403 return 16u; 1404 } 1405 return (uint32_t) ggml_type_size(t); 1406 } 1407 1408 static std::vector get_fa_spec_constants(const vk_fa_pipeline_state& state) { 1409 return { 1410 /* 0 WorkGroupSize */ state.workgroup_size, 1411 /* 1 Br */ state.Br, 1412 /* 2 Bc */ state.Bc, 1413 /* 3 HSK */ state.HSK, 1414 /* 4 HSV */ state.HSV, 1415 /* 5 Clamp */ static_cast(!state.aligned), 1416 /* 6 D_split */ state.D_split, 1417 /* 7 row_split */ state.row_split, 1418 /* 8 SubGroupSize */ state.subgroup_size, 1419 /* 9 SHMEM_STAGING */ state.shmem_staging ? 1u : 0u, 1420 /*10 Flags */ state.flags, 1421 /*11 LIMIT_OCCUPANCY_SHMEM */ state.limit_occupancy_shmem, 1422 /*12 FaTypeK */ static_cast(state.k_type), 1423 /*13 FaTypeV */ static_cast(state.v_type), 1424 /*14 FaBlockBytesK */ fa_block_bytes(state.k_type), 1425 /*15 FaBlockBytesV */ fa_block_bytes(state.v_type), 1426 }; 1427 } 1428 1429 static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { 1430 1431 uint32_t lut_size = 0; 1432 switch (src0_type) { 1433 case GGML_TYPE_IQ1_S: 1434 case GGML_TYPE_IQ1_M: 1435 // Regular matmul uses the compact uint16_t IQ1 grid; the expanded 1436 // uint32_t grid is only enabled for the q8_1/int-dot vector path. 1437 lut_size = 2*2048; 1438 break; 1439 case GGML_TYPE_IQ2_XXS: 1440 lut_size = 8*256; 1441 break; 1442 case GGML_TYPE_IQ2_XS: 1443 lut_size = 8*512; 1444 break; 1445 case GGML_TYPE_IQ2_S: 1446 lut_size = 8*1024; 1447 break; 1448 case GGML_TYPE_IQ3_XXS: 1449 lut_size = 4*256; 1450 break; 1451 case GGML_TYPE_IQ3_S: 1452 lut_size = 4*512; 1453 break; 1454 case GGML_TYPE_IQ4_NL: 1455 case GGML_TYPE_IQ4_XS: 1456 case GGML_TYPE_MXFP4: 1457 lut_size = 4*16; 1458 break; 1459 case GGML_TYPE_NVFP4: 1460 // Same kvalues budget as MXFP4 plus ue4m3_fp32_lut[256] (types.glsl, DATA_A_NVFP4). 1461 lut_size = 4*16 + 256u * (uint32_t)sizeof(float); 1462 break; 1463 default: 1464 break; 1465 } 1466 1467 // Needs to be kept up to date on shader changes 1468 // Needs to stay aligned with ggml_vk_mul_mm_spec. 1469 const bool intel_shmem_stride_pad_zero = device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && 1470 device->driver_id == vk::DriverId::eIntelProprietaryWindows; 1471 const uint32_t bank_conflict_offset = intel_shmem_stride_pad_zero ? 0 : (device->coopmat_support ? 8 : 1); 1472 const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float); 1473 const uint32_t warps = warptile[0] / warptile[10]; 1474 1475 const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size; 1476 const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0; 1477 const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0; 1478 1479 const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size; 1480 const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize; 1481 1482 VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), " 1483 "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported); 1484 1485 return supported; 1486 } 1487 1488 static bool ggml_vk_matmul_int_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { 1489 1490 // FLOAT_TYPE in the shader is float16_t with fp16 support, otherwise float. 1491 const uint32_t fp_size = device->fp16 ? 2u : 4u; 1492 const uint32_t fp_align = fp_size; 1493 const uint32_t fp2_size = 2u * fp_size; 1494 const uint32_t fp2_align = device->fp16 ? 4u : 8u; 1495 1496 struct member { uint32_t size, align; }; 1497 auto std430_size = [](std::initializer_list members) { 1498 uint32_t off = 0, struct_align = 1; 1499 for (const auto &m : members) { 1500 off = (off + m.align - 1) & ~(m.align - 1); 1501 off += m.size; 1502 struct_align = std::max(struct_align, m.align); 1503 } 1504 return (off + struct_align - 1) & ~(struct_align - 1); 1505 }; 1506 1507 uint32_t block_a_size = 0; 1508 switch (src0_type) { 1509 case GGML_TYPE_Q2_0: block_a_size = std430_size({{32, 4}, {fp_size, fp_align}}); break; // qs[8] + dm 1510 case GGML_TYPE_Q4_0: block_a_size = std430_size({{16, 4}, {fp_size, fp_align}}); break; // qs[16/4] + dm 1511 case GGML_TYPE_Q4_1: block_a_size = std430_size({{16, 4}, {fp2_size, fp2_align}}); break; // qs[16/4] + dm(vec2) 1512 case GGML_TYPE_Q5_0: block_a_size = std430_size({{16, 4}, {4, 4}, {fp_size, fp_align}}); break; // qs[16/4] + qh + dm 1513 case GGML_TYPE_Q5_1: block_a_size = std430_size({{16, 4}, {4, 4}, {fp2_size, fp2_align}}); break; // qs[16/4] + qh + dm(vec2) 1514 case GGML_TYPE_Q8_0: block_a_size = std430_size({{32, 4}, {fp_size, fp_align}}); break; // qs[8] + dm 1515 case GGML_TYPE_IQ4_XS: block_a_size = std430_size({{32, 4}, {fp_size, fp_align}}); break; // qs[8] + d 1516 case GGML_TYPE_MXFP4: block_a_size = std430_size({{32, 4}, {fp_size, fp_align}}); break; // qs[8] + d 1517 case GGML_TYPE_IQ4_NL: block_a_size = std430_size({{32, 4}, {fp_size, fp_align}}); break; // qs[8] + d 1518 case GGML_TYPE_NVFP4: block_a_size = std430_size({{32, 4}, {fp2_size, fp2_align}}); break; // qs[8] + d_scales(vec2) 1519 case GGML_TYPE_Q2_K: block_a_size = std430_size({{ 8, 4}, {2, 2}, {fp2_size, fp2_align}}); break; // qs[2] + scales(u8vec2) + dm(vec2) 1520 case GGML_TYPE_Q3_K: block_a_size = std430_size({{16, 4}, {fp2_size, fp2_align}}); break; // qs[4] + d_scales(vec2) 1521 case GGML_TYPE_Q4_K: block_a_size = std430_size({{16, 4}, {fp2_size, fp2_align}}); break; // qs[4] + dm(vec2) 1522 case GGML_TYPE_Q5_K: block_a_size = std430_size({{32, 4}, {fp2_size, fp2_align}}); break; // qs[8] + dm(vec2) 1523 case GGML_TYPE_Q6_K: block_a_size = std430_size({{32, 4}, {fp2_size, fp2_align}}); break; // qs[8] + d_scales(vec2) 1524 case GGML_TYPE_IQ3_S: block_a_size = std430_size({{32, 4}, {fp_size, fp_align}}); break; // qs[8] + d 1525 default: 1526 return false; 1527 } 1528 1529 // IQ3_S also copies its 512-entry grid into shared memory (types.glsl, init_iq_shmem) 1530 const uint32_t lut_size = (src0_type == GGML_TYPE_IQ3_S) ? 4*512 : 0; 1531 1532 // block_b_cache: { int32_t qs[8]; FLOAT_TYPEV2 ds; } 1533 const uint32_t block_b_size = std430_size({{32, 4}, {fp2_size, fp2_align}}); 1534 1535 const uint32_t BM = warptile[1]; 1536 const uint32_t BN = warptile[2]; 1537 // mul_mmq.comp: BK_STEP=1 for MUL_MAT_ID, 4 otherwise. 1538 const uint32_t BK_STEP = mul_mat_id ? 1u : 4u; 1539 1540 const uint32_t buf_a_size = BM * BK_STEP * block_a_size; 1541 const uint32_t buf_b_size = BN * BK_STEP * block_b_size; 1542 const uint32_t mmid_row_ids = mul_mat_id ? (BN * 2u * (uint32_t)sizeof(uint16_t)) : 0u; 1543 1544 const uint32_t total_size = buf_a_size + buf_b_size + mmid_row_ids + lut_size; 1545 const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize; 1546 1547 VK_LOG_DEBUG("ggml_vk_matmul_int_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), " 1548 "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", total=" << total_size << ", supported=" << supported); 1549 1550 return supported; 1551 } 1552 1553 static bool ggml_vk_matmul_cm1_int_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { 1554 1555 bool kscales2 = false; // two scale sets per block 1556 bool has_dm = false; // d+m as vec2 + b-side sum 1557 bool has_kvalues = false; 1558 switch (src0_type) { 1559 case GGML_TYPE_Q4_0: case GGML_TYPE_Q5_0: case GGML_TYPE_Q8_0: 1560 break; 1561 case GGML_TYPE_Q4_1: case GGML_TYPE_Q5_1: 1562 case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: 1563 has_dm = true; break; 1564 case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: case GGML_TYPE_MXFP4: 1565 has_kvalues = true; break; 1566 case GGML_TYPE_Q3_K: case GGML_TYPE_Q6_K: 1567 kscales2 = true; break; 1568 case GGML_TYPE_NVFP4: 1569 kscales2 = true; has_kvalues = true; break; 1570 default: 1571 return false; 1572 } 1573 1574 const uint32_t BM = warptile[1]; 1575 const uint32_t BN = warptile[2]; 1576 1577 const uint32_t BK = 32; 1578 const uint32_t BK_STEP = mul_mat_id ? 2u : 4u; 1579 const uint32_t QPITCH = BK_STEP * (BK / 4u) + 4u; 1580 const uint32_t KSCALES = kscales2 ? 2u : 1u; 1581 1582 uint32_t total = 0; 1583 total += BM * QPITCH * (uint32_t)sizeof(uint32_t); // buf_a_qs 1584 total += BN * QPITCH * (uint32_t)sizeof(uint32_t); // buf_b_qs 1585 total += has_dm ? (BM * BK_STEP * 2u * (uint32_t)sizeof(float)) // buf_a_dm (vec2) 1586 : (BM * BK_STEP * KSCALES * (uint32_t)sizeof(float)); // buf_a_d 1587 total += BN * BK_STEP * (uint32_t)sizeof(float); // buf_b_d 1588 if (has_dm) { 1589 total += BN * BK_STEP * (uint32_t)sizeof(float); // buf_b_s 1590 } 1591 if (has_kvalues) { 1592 total += 16u * (uint32_t)sizeof(int8_t); // cm1_kvalues[16] 1593 } 1594 if (src0_type == GGML_TYPE_NVFP4 && !device->ocp_fp4) { 1595 total += 256u * (uint32_t)sizeof(float); // ue4m3_fp32_lut[256] 1596 } 1597 if (mul_mat_id) { 1598 total += BN * 2u * (uint32_t)sizeof(uint16_t); // row_ids[BN] (u16vec2) 1599 } 1600 1601 const bool supported = total <= device->properties.limits.maxComputeSharedMemorySize; 1602 1603 VK_LOG_DEBUG("ggml_vk_matmul_cm1_int_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), " 1604 "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", total=" << total << ", supported=" << supported); 1605 1606 return supported; 1607 } 1608 1609 static const std::unordered_map rdna1_pipelines = { 1610 {"soft_max", 64}, {"im2col", 64}, 1611 {"argmax", 64}, {"mul_mat_vec", 64}, 1612 {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32} 1613 }; 1614 1615 static const std::unordered_map rdna2_pipelines = { 1616 {"soft_max", 64}, {"im2col", 64}, 1617 }; 1618 1619 static std::vector gpu_pipeline_configs = { 1620 { 1621 vk_device_architecture::AMD_RDNA1, 1622 { 1623 rdna1_pipelines, 1624 }, 1625 RDNA_DEFAULT_SUBGROUP_SIZE 1626 }, 1627 { 1628 vk_device_architecture::AMD_RDNA2, 1629 { 1630 rdna2_pipelines, 1631 }, 1632 RDNA_DEFAULT_SUBGROUP_SIZE 1633 }, 1634 }; 1635 1636 uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) { 1637 for (const auto &config : gpu_pipeline_configs) { 1638 if (config.arch == arch) { 1639 auto pipIt = config.pipelines.find(pipeline_name); 1640 if (pipIt != config.pipelines.end()) { 1641 return pipIt->second; 1642 } 1643 std::vector> sorted_pipelines(config.pipelines.begin(), config.pipelines.end()); 1644 std::sort(sorted_pipelines.begin(), sorted_pipelines.end(), 1645 [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); }); 1646 for (const auto &entry : sorted_pipelines) { 1647 if (pipeline_name.find(entry.first) != std::string::npos) { 1648 return entry.second; 1649 } 1650 } 1651 return config.default_subgroup_size; 1652 } 1653 } 1654 return 0; // If no matching configuration is found 1655 } 1656 1657 static bool ggml_vk_fa_type_needs_shmem(ggml_type type) { 1658 switch (type) { 1659 case GGML_TYPE_IQ4_NL: 1660 return true; 1661 default: 1662 return false; 1663 } 1664 } 1665 1666 static bool ggml_vk_fa_scalar_uses_mmq(const vk_device& device, ggml_type k_type, ggml_type v_type) { 1667 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 1668 return device->integer_dot_product && device->subgroup_clustered && 1669 !ggml_vk_fa_type_needs_shmem(v_type) && 1670 (k_type == GGML_TYPE_Q4_0 || k_type == GGML_TYPE_Q4_1 || 1671 k_type == GGML_TYPE_Q5_0 || k_type == GGML_TYPE_Q5_1 || 1672 k_type == GGML_TYPE_Q8_0); 1673 #else 1674 GGML_UNUSED(device); 1675 GGML_UNUSED(k_type); 1676 GGML_UNUSED(v_type); 1677 return false; 1678 #endif 1679 } 1680 1681 void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { 1682 VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")"); 1683 1684 // some shaders have a minimum subgroup size 1685 const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u); 1686 const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u); 1687 const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u); 1688 1689 // clamp WARP for l_/m_ warptiles so WM <= BM (breaks on subgroupSize > 64) 1690 const uint32_t mm_warp_8 = std::min(subgroup_size_8, 64u); 1691 const uint32_t mm_warp_16 = std::min(subgroup_size_16, 64u); 1692 1693 const uint32_t mul_mat_subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size; 1694 const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u); 1695 const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u); 1696 const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u); 1697 const uint32_t mul_mat_mm_warp_8 = std::min(mul_mat_subgroup_size_8, 64u); 1698 const uint32_t mul_mat_mm_warp_16 = std::min(mul_mat_subgroup_size_16, 64u); 1699 1700 // small warptiles split BM=32 between BLOCK_SIZE/WARP subgroups, so each subgroup needs its own warp tile 1701 const uint32_t s_warptile_wm_8 = 32 * subgroup_size_8 / subgroup_size_32; 1702 const uint32_t mul_mat_s_warptile_wm_8 = 32 * mul_mat_subgroup_size_8 / mul_mat_subgroup_size_32; 1703 const uint32_t mul_mat_s_warptile_wm_16 = 32 * mul_mat_subgroup_size_16 / mul_mat_subgroup_size_32; 1704 1705 const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) || 1706 (device->subgroup_size_control && device->subgroup_max_size >= 16); 1707 1708 // mulmat 1709 // Warptile layout (indices match mul_mm.comp constantIDs): 1710 // [0..9] : BLOCK_SIZE, BM, BN, BK, WM, WN, WMITER, TM, TN, TK 1711 // [10] : WARP / required_subgroup_size (read via WARP_SIZE_IDX) 1712 static constexpr size_t WARP_SIZE_IDX = 10; 1713 std::vector l_warptile, m_warptile, s_warptile, 1714 l_warptile_id, m_warptile_id, s_warptile_id, 1715 l_warptile_mmq, m_warptile_mmq, s_warptile_mmq, 1716 l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int, 1717 l_warptile_mmq_cm1_int, m_warptile_mmq_cm1_int, s_warptile_mmq_cm1_int, 1718 l_warptile_mmq_cm1_int_k, m_warptile_mmq_cm1_int_k, s_warptile_mmq_cm1_int_k, 1719 l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k, 1720 l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k, 1721 l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid, 1722 l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int, 1723 l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k; 1724 std::array l_wg_denoms, m_wg_denoms, s_wg_denoms, 1725 l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms, 1726 l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k, 1727 l_mmq_cm1_wg_denoms_k, m_mmq_cm1_wg_denoms_k, s_mmq_cm1_wg_denoms_k, 1728 l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms; 1729 1730 uint32_t l_align, m_align, s_align; 1731 1732 // RDNA3.5 preferred wave32 here 1733 const bool cm1_use_wave32 = device->vendor_id == VK_VENDOR_ID_AMD && 1734 device->subgroup_size_control && 1735 device->subgroup_min_size <= 32 && device->subgroup_max_size >= 32; 1736 const uint32_t cm1_sg = cm1_use_wave32 ? 32 : device->subgroup_size; 1737 1738 vk_pipeline wait_pipeline; 1739 CompileTask claimed_task {}; 1740 bool has_claimed_task = false; 1741 1742 // The rest of the walk reads and writes shared device state, so hold the 1743 // lock until we're done deciding what to compile. 1744 std::unique_lock compile_lock(device->compile_mutex); 1745 1746 if (device->coopmat2) { 1747 // spec constants and tile sizes for non-quant matmul/matmul_id 1748 l_warptile = { 256, 128, 256, 64, 1 }; 1749 m_warptile = { 256, 128, 128, 64, 0 }; 1750 s_warptile = { 128, 64, 64, 64, 0 }; 1751 l_wg_denoms = {128, 256, 1 }; 1752 m_wg_denoms = {128, 128, 1 }; 1753 s_wg_denoms = { 64, 64, 1 }; 1754 1755 // spec constants and tile sizes for quant matmul (non-Qi_K) 1756 l_warptile_mmq = { 256, 128, 256, 64, 1 }; 1757 m_warptile_mmq = { 256, 128, 128, 64, 1 }; 1758 s_warptile_mmq = { 256, 32, 64, 128, 0 }; 1759 l_mmq_wg_denoms = { 128, 256, 1 }; 1760 m_mmq_wg_denoms = { 128, 128, 1 }; 1761 s_mmq_wg_denoms = { 32, 64, 1 }; 1762 1763 // spec constants and tile sizes for quant matmul (Qi_K) 1764 l_warptile_mmq_k = { 256, 128, 256, 64, 1 }; 1765 m_warptile_mmq_k = { 256, 128, 128, 64, 1 }; 1766 s_warptile_mmq_k = { 256, 32, 64, 128, 0 }; 1767 l_mmq_wg_denoms_k = { 128, 256, 1 }; 1768 m_mmq_wg_denoms_k = { 128, 128, 1 }; 1769 s_mmq_wg_denoms_k = { 32, 64, 1 }; 1770 1771 // spec constants and tile sizes for quant matmul_id 1772 const uint32_t mmqid_bk = device->coopmat2_decode_vector ? 64u : 32u; 1773 l_warptile_mmqid = { 256, 128, 128, mmqid_bk, 1 }; 1774 m_warptile_mmqid = { 256, 128, 64, mmqid_bk, 0 }; 1775 s_warptile_mmqid = { 256, 128, 64, mmqid_bk, 0 }; 1776 l_mmqid_wg_denoms = { 128, 128, 1 }; 1777 m_mmqid_wg_denoms = { 128, 64, 1 }; 1778 s_mmqid_wg_denoms = { 128, 64, 1 }; 1779 1780 l_align = 128; 1781 m_align = 64; 1782 s_align = 32; 1783 } else { 1784 // Matrix cores require different warp group sizes 1785 const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4; 1786 const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4; 1787 const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2; 1788 const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4; 1789 const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2; 1790 const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2; 1791 const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1; 1792 const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1; 1793 const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1; 1794 1795 const uint32_t itm = device->coopmat_int_m; 1796 const uint32_t itn = device->coopmat_int_n; 1797 const uint32_t itk = device->coopmat_int_k; 1798 1799 l_warptile = { 128, 128, 128, 16, mm_warp_8 * 2, 64, 2, tm_l, tn_l, tk_l, mm_warp_8 }; 1800 m_warptile = { 128, 64, 64, 16, mm_warp_8, 32, 2, tm_m, tn_m, tk_m, mm_warp_8 }; 1801 s_warptile = { subgroup_size_32, 32, 32, 16, s_warptile_wm_8, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 }; 1802 1803 l_warptile_mmq = { 128, 128, 128, 32, mm_warp_8 * 2, 64, 2, tm_l, tn_l, tk_l, mm_warp_8 }; 1804 m_warptile_mmq = { 128, 64, 64, 32, mm_warp_8, 32, 2, tm_m, tn_m, tk_m, mm_warp_8 }; 1805 s_warptile_mmq = { subgroup_size_32, 32, 32, 32, s_warptile_wm_8, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 }; 1806 1807 // Integer MMQ has a smaller shared memory profile, but heavier register use 1808 l_warptile_mmq_int = { 128, 128, 128, 32, mm_warp_8 * 2, 64, 2, 4, 4, 1, mm_warp_8 }; 1809 m_warptile_mmq_int = { 128, 64, 64, 32, mm_warp_8, 32, 2, 2, 2, 1, mm_warp_8 }; 1810 s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, s_warptile_wm_8, 32, 2, 2, 1, 1, subgroup_size_8 }; 1811 1812 const auto cm1_bs = [cm1_sg](uint32_t bm, uint32_t bn) { 1813 return cm1_sg * (bm / std::min(cm1_sg, bm)) * (bn / 32); 1814 }; 1815 1816 l_warptile_mmq_cm1_int = { cm1_bs(128, 128), 128, 128, 32, std::min(cm1_sg, 128u), 32, 2, itm, itn, itk, cm1_sg, (uint32_t)device->architecture }; 1817 m_warptile_mmq_cm1_int = { cm1_bs( 64, 64), 64, 64, 32, std::min(cm1_sg, 64u), 32, 2, itm, itn, itk, cm1_sg, (uint32_t)device->architecture }; 1818 s_warptile_mmq_cm1_int = { cm1_bs( 32, 32), 32, 32, 32, std::min(cm1_sg, 32u), 32, 2, itm, itn, itk, cm1_sg, (uint32_t)device->architecture }; 1819 1820 l_warptile_mmq_cm1_int_k = { cm1_bs( 64, 128), 64, 128, 32, std::min(cm1_sg, 64u), 32, 2, itm, itn, itk, cm1_sg, (uint32_t)device->architecture }; 1821 m_warptile_mmq_cm1_int_k = { cm1_bs( 64, 64), 64, 64, 32, std::min(cm1_sg, 64u), 32, 2, itm, itn, itk, cm1_sg, (uint32_t)device->architecture }; 1822 s_warptile_mmq_cm1_int_k = { cm1_bs( 32, 32), 32, 32, 32, std::min(cm1_sg, 32u), 32, 2, itm, itn, itk, cm1_sg, (uint32_t)device->architecture }; 1823 1824 l_mmq_cm1_wg_denoms_k = { l_warptile_mmq_cm1_int_k[1], l_warptile_mmq_cm1_int_k[2], 1 }; 1825 m_mmq_cm1_wg_denoms_k = { m_warptile_mmq_cm1_int_k[1], m_warptile_mmq_cm1_int_k[2], 1 }; 1826 s_mmq_cm1_wg_denoms_k = { s_warptile_mmq_cm1_int_k[1], s_warptile_mmq_cm1_int_k[2], 1 }; 1827 1828 // K-quants use even more registers, mitigate by setting WMITER to 1 1829 l_warptile_mmq_int_k = { 128, 128, 128, 32, mm_warp_8 * 2, 64, 1, 4, 4, 1, mm_warp_8 }; 1830 m_warptile_mmq_int_k = { 128, 64, 64, 32, mm_warp_8, 32, 1, 2, 2, 1, mm_warp_8 }; 1831 s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, s_warptile_wm_8, 32, 1, 2, 1, 1, subgroup_size_8 }; 1832 1833 l_warptile_id = { 128, 128, 128, 16, mul_mat_mm_warp_16 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_mm_warp_16 }; 1834 m_warptile_id = { 128, 64, 64, 16, mul_mat_mm_warp_16, 32, 2, tm_m, tn_m, tk_m, mul_mat_mm_warp_16 }; 1835 s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 }; 1836 1837 l_warptile_mmqid = { 128, 128, 128, 32, mul_mat_mm_warp_8 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_mm_warp_8 }; 1838 m_warptile_mmqid = { 128, 64, 64, 32, mul_mat_mm_warp_8, 32, 2, tm_m, tn_m, tk_m, mul_mat_mm_warp_8 }; 1839 s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, mul_mat_s_warptile_wm_8, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 }; 1840 1841 l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_mm_warp_8 * 2, 64, 2, 4, 4, 1, mul_mat_mm_warp_8 }; 1842 m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_mm_warp_8, 32, 2, 2, 2, 1, mul_mat_mm_warp_8 }; 1843 s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, mul_mat_s_warptile_wm_8, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 }; 1844 1845 l_warptile_mmqid_int_k = { 128, 128, 128, 32, mul_mat_mm_warp_16 * 2, 64, 1, 4, 4, 1, mul_mat_mm_warp_16 }; 1846 m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_mm_warp_16, 32, 1, 2, 2, 1, mul_mat_mm_warp_16 }; 1847 s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, mul_mat_s_warptile_wm_16, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 }; 1848 1849 // chip specific tuning 1850 if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) { 1851 m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 }; 1852 m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 }; 1853 } else if (device->vendor_id == VK_VENDOR_ID_AMD && device->coopmat_support && device->driver_id != vk::DriverId::eAmdProprietary) { 1854 // This is intentionally using tx_m values, slight performance increase 1855 l_warptile = { 256, 128, 128, 16, mm_warp_8, 64, 2, tm_m, tn_m, tk_m, mm_warp_8 }; 1856 l_warptile_mmq = l_warptile_mmq_int = { 256, 128, 128, 32, mm_warp_8, 64, 2, tm_m, tn_m, tk_m, mm_warp_8 }; 1857 l_warptile_mmq_int_k = { 256, 128, 128, 32, mm_warp_16, 64, 1, 4, 2, 1, mm_warp_16 }; 1858 } else if (device->vendor_id == VK_VENDOR_ID_QUALCOMM && device->coopmat_support) { 1859 m_warptile = { 64, 64, 64, 16, 64, 64, 1, tm_l, tn_l, tk_l, 64 }; 1860 m_warptile_mmq = { 64, 64, 64, 32, 64, 64, 1, tm_m, tn_m, tk_m, 64 }; 1861 } 1862 1863 l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 }; 1864 m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 }; 1865 s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 }; 1866 l_align = 128; 1867 m_align = 64; 1868 s_align = 32; 1869 1870 if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support) { 1871 // Xe1/Xe2/Xe3 with coopmat enabled - warptile performance tuning 1872 l_warptile = { 512, 128, 128, 16, mm_warp_8, 32, 2, tm_l, tn_l, tk_l, mm_warp_8 }; 1873 if (device->architecture == INTEL_XE1) { 1874 l_warptile_mmq = { 512, 256, 128, 32, 32, 32, 2, tm_l, tn_l, tk_l, 16 }; 1875 l_mmq_wg_denoms = { 256, 128, 1 }; 1876 l_align = 32; //set as BK 1877 } else { 1878 l_warptile_mmq = { 512, 128, 256, 32, 32, 32, 2, tm_l, tn_l, tk_l, 16 }; 1879 l_mmq_wg_denoms = { 128, 256, 1 }; 1880 l_align = 32; //set as BK 1881 } 1882 } 1883 1884 const bool use_cm1_int = device->coopmat_int_support && 1885 (device->architecture == AMD_RDNA3 || device->architecture == AMD_RDNA4); 1886 1887 for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) { 1888 ggml_type t = (ggml_type)i; 1889 // Disable medium and large matrix multiplication if not enough shared memory is available 1890 // Check mmq warptiles as the largest configuration 1891 // Throw an error if not enough for any matrix multiplication is available 1892 if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) { 1893 std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl; 1894 throw std::runtime_error("Shared memory size too small for matrix multiplication."); 1895 } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) { 1896 device->mul_mat_m[i] = false; 1897 device->mul_mat_l[i] = false; 1898 } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) { 1899 device->mul_mat_l[i] = false; 1900 } 1901 1902 // Disable mul_mat_id if not enough shared memory is available 1903 if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) { 1904 device->mul_mat_id_s[i] = false; 1905 device->mul_mat_id_m[i] = false; 1906 device->mul_mat_id_l[i] = false; 1907 } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) { 1908 device->mul_mat_id_m[i] = false; 1909 device->mul_mat_id_l[i] = false; 1910 } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) { 1911 device->mul_mat_id_l[i] = false; 1912 } 1913 1914 // The q8_1 mmq path has its own (larger) shmem layout, check it separately. 1915 // K-quants and IQ3_S use the _int_k warptiles, others use _int. 1916 // cm1 splits k-tiles on the KSCALES==2 types and shares tiles between dense/id. 1917 const bool is_k_quant = (t == GGML_TYPE_Q2_K || t == GGML_TYPE_Q3_K || 1918 t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || 1919 t == GGML_TYPE_Q6_K || t == GGML_TYPE_IQ3_S); 1920 const bool cm1_k_tile = (t == GGML_TYPE_Q3_K || t == GGML_TYPE_Q6_K || 1921 t == GGML_TYPE_NVFP4); 1922 1923 const auto & s_int = use_cm1_int ? (cm1_k_tile ? s_warptile_mmq_cm1_int_k : s_warptile_mmq_cm1_int) 1924 : (is_k_quant ? s_warptile_mmq_int_k : s_warptile_mmq_int); 1925 const auto & m_int = use_cm1_int ? (cm1_k_tile ? m_warptile_mmq_cm1_int_k : m_warptile_mmq_cm1_int) 1926 : (is_k_quant ? m_warptile_mmq_int_k : m_warptile_mmq_int); 1927 const auto & l_int = use_cm1_int ? (cm1_k_tile ? l_warptile_mmq_cm1_int_k : l_warptile_mmq_cm1_int) 1928 : (is_k_quant ? l_warptile_mmq_int_k : l_warptile_mmq_int); 1929 const auto & s_intid = use_cm1_int ? (cm1_k_tile ? s_warptile_mmq_cm1_int_k : s_warptile_mmq_cm1_int) 1930 : (is_k_quant ? s_warptile_mmqid_int_k : s_warptile_mmqid_int); 1931 const auto & m_intid = use_cm1_int ? (cm1_k_tile ? m_warptile_mmq_cm1_int_k : m_warptile_mmq_cm1_int) 1932 : (is_k_quant ? m_warptile_mmqid_int_k : m_warptile_mmqid_int); 1933 const auto & l_intid = use_cm1_int ? (cm1_k_tile ? l_warptile_mmq_cm1_int_k : l_warptile_mmq_cm1_int) 1934 : (is_k_quant ? l_warptile_mmqid_int_k : l_warptile_mmqid_int); 1935 1936 const auto int_shmem_support = [&](const std::vector& wt, bool id) { 1937 return use_cm1_int ? ggml_vk_matmul_cm1_int_shmem_support(device, wt, id, t) 1938 : ggml_vk_matmul_int_shmem_support(device, wt, id, t); 1939 }; 1940 1941 if (!int_shmem_support(s_int, false)) { 1942 device->mul_mat_s_int[i] = false; 1943 device->mul_mat_m_int[i] = false; 1944 device->mul_mat_l_int[i] = false; 1945 } else if (!int_shmem_support(m_int, false)) { 1946 device->mul_mat_m_int[i] = false; 1947 device->mul_mat_l_int[i] = false; 1948 } else if (!int_shmem_support(l_int, false)) { 1949 device->mul_mat_l_int[i] = false; 1950 } 1951 1952 if (!int_shmem_support(s_intid, true)) { 1953 device->mul_mat_id_s_int[i] = false; 1954 device->mul_mat_id_m_int[i] = false; 1955 device->mul_mat_id_l_int[i] = false; 1956 } else if (!int_shmem_support(m_intid, true)) { 1957 device->mul_mat_id_m_int[i] = false; 1958 device->mul_mat_id_l_int[i] = false; 1959 } else if (!int_shmem_support(l_intid, true)) { 1960 device->mul_mat_id_l_int[i] = false; 1961 } 1962 } 1963 } 1964 1965 auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& base_pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint, 1966 uint32_t parameter_count, uint32_t push_constant_size, std::array wg_denoms, const std::vector& specialization_constants, 1967 uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) { 1968 1969 if (!require_full_subgroups && required_subgroup_size == 0) { 1970 required_subgroup_size = get_subgroup_size(name, device->architecture); 1971 } 1972 1973 vk_pipeline *ptr = &base_pipeline; 1974 1975 int num_pipelines = 1; 1976 #if defined(VK_EXT_shader_64bit_indexing) 1977 if (device->shader_64b_indexing) { 1978 num_pipelines = 2; 1979 } 1980 #endif 1981 for (int i = 0; i < num_pipelines; ++i, ptr = &(*ptr)->next) { 1982 vk_pipeline &pipeline = *ptr; 1983 if (!pipeline) { 1984 pipeline = std::make_shared(); 1985 } 1986 if (!pipeline->initialized) { 1987 pipeline->name = name; 1988 pipeline->parameter_count = parameter_count; 1989 pipeline->push_constant_size = push_constant_size; 1990 pipeline->wg_denoms = wg_denoms; 1991 pipeline->align = align; 1992 pipeline->initialized = true; 1993 #if defined(VK_EXT_shader_64bit_indexing) 1994 pipeline->is_64b_indexing = (i == 1); 1995 #endif 1996 } 1997 1998 // We only care about the pipeline this call asked for; the rest 1999 // (including the 64-bit indexing variant) are handled by their 2000 // own request_descriptor_sets / load_shaders calls. 2001 if (pipeline.get() != requested.get()) { 2002 continue; 2003 } 2004 2005 if (pipeline->compiled) { 2006 continue; 2007 } 2008 2009 wait_pipeline = pipeline; 2010 2011 if (!pipeline->compile_pending) { 2012 pipeline->compile_pending = true; 2013 claimed_task.pipeline = pipeline; 2014 claimed_task.spv_size = spv_size; 2015 claimed_task.spv_data = spv_data; 2016 claimed_task.entrypoint = entrypoint; 2017 claimed_task.parameter_count = parameter_count; 2018 claimed_task.wg_denoms = wg_denoms; 2019 claimed_task.specialization_constants = specialization_constants; 2020 claimed_task.disable_robustness = disable_robustness; 2021 claimed_task.require_full_subgroups = require_full_subgroups; 2022 claimed_task.required_subgroup_size = required_subgroup_size; 2023 has_claimed_task = true; 2024 } 2025 } 2026 }; 2027 2028 auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint, 2029 uint32_t parameter_count, uint32_t push_constant_size, std::array wg_denoms, const std::vector& specialization_constants, 2030 uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) { 2031 return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint, 2032 parameter_count, push_constant_size, wg_denoms, specialization_constants, 2033 align, disable_robustness, require_full_subgroups, required_subgroup_size); 2034 }; 2035 2036 // FA scalar has two SPIR-V modules (MMQ vs non-MMQ); FA cm1 has one. K/V 2037 // quant type is selected at runtime via the FaTypeK / FaTypeV spec constants. 2038 2039 for (auto &fa : device->pipeline_flash_attn_f32_f16) { 2040 if (fa.first.path != FA_SCALAR) continue; 2041 const uint32_t Br = fa.first.Br; 2042 const uint32_t Bc = fa.first.Bc; 2043 const bool aligned = fa.first.aligned; 2044 const bool f32acc = fa.first.f32acc; 2045 const uint32_t fa_sgs = fa.first.subgroup_size; 2046 const bool fa_ds = fa.first.subgroup_size == 0; 2047 2048 const bool bf16_kv = fa.first.k_type == GGML_TYPE_BF16; 2049 const bool use_mmq = ggml_vk_fa_scalar_uses_mmq(device, fa.first.k_type, fa.first.v_type); 2050 const void * spv_data = nullptr; 2051 size_t spv_size = 0; 2052 const char *name = nullptr; 2053 if (bf16_kv) { 2054 spv_data = flash_attn_f32_f16_fp32_data; 2055 spv_size = flash_attn_f32_f16_fp32_len; 2056 name = aligned ? "flash_attn_f32_bf16_aligned" : "flash_attn_f32_bf16"; 2057 } else if (use_mmq) { 2058 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 2059 if (device->fp16) { 2060 if (f32acc) { spv_data = flash_attn_f32_f16_int8_data; spv_size = flash_attn_f32_f16_int8_len; } 2061 else { spv_data = flash_attn_f32_f16_f16acc_int8_data; spv_size = flash_attn_f32_f16_f16acc_int8_len; } 2062 } else { 2063 spv_data = flash_attn_f32_f16_fp32_int8_data; 2064 spv_size = flash_attn_f32_f16_fp32_int8_len; 2065 } 2066 #endif 2067 name = aligned ? "flash_attn_f32_f16_aligned" : "flash_attn_f32_f16"; 2068 } else { 2069 if (device->fp16) { 2070 if (device->dot2_f16) { 2071 if (f32acc) { spv_data = flash_attn_f32_f16_dot2_data; spv_size = flash_attn_f32_f16_dot2_len; } 2072 else { spv_data = flash_attn_f32_f16_dot2_f16acc_data; spv_size = flash_attn_f32_f16_dot2_f16acc_len; } 2073 } else { 2074 if (f32acc) { spv_data = flash_attn_f32_f16_data; spv_size = flash_attn_f32_f16_len; } 2075 else { spv_data = flash_attn_f32_f16_f16acc_data; spv_size = flash_attn_f32_f16_f16acc_len; } 2076 } 2077 } else { 2078 spv_data = flash_attn_f32_f16_fp32_data; 2079 spv_size = flash_attn_f32_f16_fp32_len; 2080 } 2081 name = aligned ? "flash_attn_f32_f16_aligned" : "flash_attn_f32_f16"; 2082 } 2083 ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, 2084 sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, 2085 get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, 2086 !fa_ds, !fa_ds ? fa_sgs : 0); 2087 } 2088 2089 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 2090 if (device->coopmat1_fa_support) { 2091 for (auto &fa : device->pipeline_flash_attn_f32_f16) { 2092 if (fa.first.path != FA_COOPMAT1) continue; 2093 const uint32_t Br = fa.first.Br; 2094 const uint32_t Bc = fa.first.Bc; 2095 const bool aligned = fa.first.aligned; 2096 const bool f32acc = fa.first.f32acc; 2097 const uint32_t fa_sgs = fa.first.subgroup_size; 2098 const bool fa_ds = fa.first.subgroup_size == 0; 2099 2100 const bool bf16_kv = fa.first.k_type == GGML_TYPE_BF16; 2101 2102 const void * spv_data; 2103 size_t spv_size; 2104 const char *name; 2105 if (bf16_kv) { 2106 #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 2107 if (!device->coopmat_bf16_support) continue; 2108 spv_data = flash_attn_f32_f16_bf16_cm1_data; 2109 spv_size = flash_attn_f32_f16_bf16_cm1_len; 2110 name = aligned ? "flash_attn_f32_bf16_aligned_cm1" : "flash_attn_f32_bf16_cm1"; 2111 #else 2112 continue; 2113 #endif 2114 } else { 2115 if (f32acc) { spv_data = flash_attn_f32_f16_cm1_data; spv_size = flash_attn_f32_f16_cm1_len; } 2116 else { spv_data = flash_attn_f32_f16_f16acc_cm1_data; spv_size = flash_attn_f32_f16_f16acc_cm1_len; } 2117 name = aligned ? "flash_attn_f32_f16_aligned_cm1" : "flash_attn_f32_f16_cm1"; 2118 } 2119 ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, 2120 sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, 2121 get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, 2122 !fa_ds, !fa_ds ? fa_sgs : 0); 2123 } 2124 } 2125 #endif 2126 2127 #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 2128 if (device->coopmat2) { 2129 for (auto &fa : device->pipeline_flash_attn_f32_f16) { 2130 if (fa.first.path != FA_COOPMAT2) continue; 2131 const uint32_t Br = fa.first.Br; 2132 const uint32_t Bc = fa.first.Bc; 2133 const bool aligned = fa.first.aligned; 2134 const bool f32acc = fa.first.f32acc; 2135 2136 const bool bf16_kv = fa.first.k_type == GGML_TYPE_BF16; 2137 const void * spv_data; 2138 size_t spv_size; 2139 const char * name; 2140 if (bf16_kv) { 2141 #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 2142 if (!device->coopmat2_bf16_support) continue; 2143 spv_data = flash_attn_f32_f16_bf16_cm2_data; 2144 spv_size = flash_attn_f32_f16_bf16_cm2_len; 2145 name = aligned ? "flash_attn_f32_bf16_aligned_cm2" : "flash_attn_f32_bf16_cm2"; 2146 #else 2147 continue; 2148 #endif 2149 } else if (aligned) { 2150 if (f32acc) { spv_data = flash_attn_f32_f16_cm2_data; spv_size = flash_attn_f32_f16_cm2_len; name = "flash_attn_f32_f16_aligned_f32acc_cm2"; } 2151 else { spv_data = flash_attn_f32_f16_f16acc_cm2_data; spv_size = flash_attn_f32_f16_f16acc_cm2_len; name = "flash_attn_f32_f16_aligned_f16acc_cm2"; } 2152 } else { 2153 if (f32acc) { spv_data = flash_attn_f32_f16_cm2_data; spv_size = flash_attn_f32_f16_cm2_len; name = "flash_attn_f32_f16_f32acc_cm2"; } 2154 else { spv_data = flash_attn_f32_f16_f16acc_cm2_data; spv_size = flash_attn_f32_f16_f16acc_cm2_len; name = "flash_attn_f32_f16_f16acc_cm2"; } 2155 } 2156 ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8, 2157 sizeof(vk_flash_attn_push_constants), {Br, 1, 1}, 2158 get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, false, 0); 2159 } 2160 } 2161 #endif 2162 2163 auto const &ggml_vk_mul_mm_spec = [&device](std::vector spec, bool aligned) { 2164 spec.push_back(aligned ? 1u : 0u); // constantID=11: ALIGNED 2165 if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && 2166 device->driver_id == vk::DriverId::eIntelProprietaryWindows) { 2167 spec.push_back(0u); // constantID=12: SHMEM_STRIDE_PAD = 0 2168 spec.push_back(1u); // constantID=13: APPLY_SLM_A_RESHAPE = true 2169 } 2170 return spec; 2171 }; 2172 2173 auto const &ggml_vk_mul_mm_spec_quant = [&device](std::vector spec, bool aligned, uint32_t type) { 2174 spec.push_back(aligned ? 1u : 0u); // constantID=11: ALIGNED 2175 spec.push_back(type); // constantID=12: MmTypeA 2176 if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && 2177 device->driver_id == vk::DriverId::eIntelProprietaryWindows) { 2178 spec.push_back(0u); // constantID=13: SHMEM_STRIDE_PAD = 0 2179 spec.push_back(1u); // constantID=14: APPLY_SLM_A_RESHAPE = true 2180 } 2181 return spec; 2182 }; 2183 2184 static const ggml_type non_lut_quant_types[] = { 2185 GGML_TYPE_Q1_0, GGML_TYPE_Q2_0, GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0, 2186 GGML_TYPE_Q2_K, GGML_TYPE_Q3_K, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_TQ1_0, GGML_TYPE_TQ2_0, 2187 }; 2188 2189 #define FOR_EACH_LUT_TYPE_NONFP4(X) \ 2190 X(GGML_TYPE_IQ1_S, iq1_s) \ 2191 X(GGML_TYPE_IQ1_M, iq1_m) \ 2192 X(GGML_TYPE_IQ2_XXS, iq2_xxs) \ 2193 X(GGML_TYPE_IQ2_XS, iq2_xs) \ 2194 X(GGML_TYPE_IQ2_S, iq2_s) \ 2195 X(GGML_TYPE_IQ3_XXS, iq3_xxs) \ 2196 X(GGML_TYPE_IQ3_S, iq3_s) \ 2197 X(GGML_TYPE_IQ4_XS, iq4_xs) \ 2198 X(GGML_TYPE_IQ4_NL, iq4_nl) 2199 #define FOR_EACH_LUT_FP4_TYPE(X) \ 2200 X(GGML_TYPE_MXFP4, mxfp4) \ 2201 X(GGML_TYPE_NVFP4, nvfp4) 2202 #define FOR_EACH_LUT_TYPE(X) \ 2203 FOR_EACH_LUT_TYPE_NONFP4(X) \ 2204 FOR_EACH_LUT_FP4_TYPE(X) 2205 2206 const int mul_mat_id_param_count = 5; 2207 2208 using spec_fn_t = std::function(const std::vector&, bool)>; 2209 auto const &create_mm_pipelines = [&]( 2210 const vk_matmul_pipeline_key& key, 2211 const std::vector& tile_configs, 2212 const std::string& shader_name, size_t spv_len, const void* spv_data, 2213 uint32_t push_constant_size, uint32_t param_count, 2214 const spec_fn_t& spec_fn, 2215 bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0, 2216 bool create_aligned = true, bool pin_subgroup_to_warp = false 2217 ) { 2218 auto& vec = device->pipeline_matmul[key]; 2219 const bool first_call = vec.empty(); 2220 for (size_t i = 0; i < tile_configs.size(); i++) { 2221 const auto& tc = tile_configs[i]; 2222 2223 // Intel coopmat1 pins the required subgroup size to each warptile's WARP element. 2224 const uint32_t rsgs = pin_subgroup_to_warp ? tc.warptile[WARP_SIZE_IDX] : required_subgroup_size; 2225 const bool rfs = require_full_subgroups || pin_subgroup_to_warp; 2226 2227 if (first_call) { 2228 vk_matmul_pipeline_pair pair{}; 2229 pair.align = tc.align; 2230 std::string suffix = "_" + std::to_string(i); 2231 pair.unaligned = std::make_shared(); 2232 if (create_aligned) { 2233 pair.aligned = std::make_shared(); 2234 } 2235 vec.push_back(pair); 2236 } 2237 2238 ggml_vk_create_pipeline(device, vec[i].unaligned, 2239 vec[i].unaligned->name.empty() ? (shader_name + "_" + std::to_string(i)).c_str() : vec[i].unaligned->name.c_str(), 2240 spv_len, spv_data, "main", param_count, push_constant_size, 2241 tc.wg_denoms, spec_fn(tc.warptile, false), 1, 2242 disable_robustness, rfs, rsgs); 2243 2244 if (vec[i].aligned) { 2245 ggml_vk_create_pipeline(device, vec[i].aligned, 2246 vec[i].aligned->name.empty() ? (shader_name + "_aligned_" + std::to_string(i)).c_str() : vec[i].aligned->name.c_str(), 2247 spv_len, spv_data, "main", param_count, push_constant_size, 2248 tc.wg_denoms, spec_fn(tc.warptile, true), tc.align, 2249 disable_robustness, rfs, rsgs); 2250 } 2251 } 2252 }; 2253 2254 auto filter_tc = [&](const std::vector& configs, ggml_type type, bool is_id, bool is_int = false) -> std::vector { 2255 std::vector result; 2256 bool enabled[3]; 2257 if (is_int) { 2258 enabled[0] = is_id ? device->mul_mat_id_s_int[type] : device->mul_mat_s_int[type]; 2259 enabled[1] = is_id ? device->mul_mat_id_m_int[type] : device->mul_mat_m_int[type]; 2260 enabled[2] = is_id ? device->mul_mat_id_l_int[type] : device->mul_mat_l_int[type]; 2261 } else { 2262 enabled[0] = is_id ? device->mul_mat_id_s[type] : device->mul_mat_s[type]; 2263 enabled[1] = is_id ? device->mul_mat_id_m[type] : device->mul_mat_m[type]; 2264 enabled[2] = is_id ? device->mul_mat_id_l[type] : device->mul_mat_l[type]; 2265 } 2266 for (size_t i = 0; i < configs.size() && i < 3; i++) { 2267 if (enabled[i]) result.push_back(configs[i]); 2268 } 2269 return result; 2270 }; 2271 2272 std::vector tc_mm = {{s_warptile, s_wg_denoms, s_align}, {m_warptile, m_wg_denoms, m_align}, {l_warptile, l_wg_denoms, l_align}}; 2273 std::vector tc_mmq = {{s_warptile_mmq, s_mmq_wg_denoms, s_align}, {m_warptile_mmq, m_mmq_wg_denoms, m_align}, {l_warptile_mmq, l_mmq_wg_denoms, l_align}}; 2274 2275 #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 2276 if (device->coopmat2) { 2277 auto const &ggml_vk_mul_mm_cm2_spec = [&](std::vector spec, bool aligned, uint32_t type = UINT32_MAX) { 2278 spec.push_back(aligned ? 1u : 0u); // ALIGNED 2279 spec.push_back(device->subgroup_size); // subgroup_size 2280 if (type != UINT32_MAX) { 2281 spec.push_back(type); // MmTypeA 2282 spec.push_back((uint32_t)ggml_type_size((ggml_type)type)); // MmABlockBytes 2283 } 2284 return spec; 2285 }; 2286 2287 std::vector tc_mmq_k = {{s_warptile_mmq_k, s_mmq_wg_denoms_k, s_align}, {m_warptile_mmq_k, m_mmq_wg_denoms_k, m_align}, {l_warptile_mmq_k, l_mmq_wg_denoms_k, l_align}}; 2288 std::vector tc_mmqid = {{s_warptile_mmqid, s_mmqid_wg_denoms, s_align}, {m_warptile_mmqid, m_mmqid_wg_denoms, m_align}, {l_warptile_mmqid, l_mmqid_wg_denoms, l_align}}; 2289 2290 spec_fn_t cm2_spec = [&](const std::vector& wt, bool a) { return ggml_vk_mul_mm_cm2_spec(wt, a); }; 2291 2292 // F16 x F16 2293 create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, false, true}, tc_mm, "matmul_f16_f16acc", matmul_f16_f16acc_cm2_len, matmul_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); 2294 create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", matmul_f16_cm2_len, matmul_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); 2295 #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 2296 if (device->coopmat_bf16_support) { 2297 create_mm_pipelines({GGML_TYPE_BF16, GGML_TYPE_BF16, false, false}, tc_mm, "matmul_bf16", matmul_bf16_cm2_len, matmul_bf16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); 2298 } 2299 #endif 2300 for (const auto type : non_lut_quant_types) { 2301 // regression in unified shader on Ampere 2302 if (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) { 2303 continue; 2304 } 2305 auto& tc = ((type >= GGML_TYPE_Q2_K && type <= GGML_TYPE_Q6_K) || type == GGML_TYPE_TQ1_0 || type == GGML_TYPE_TQ2_0) ? tc_mmq_k : tc_mmq; 2306 spec_fn_t qs = [&, type](const std::vector& wt, bool a) { return ggml_vk_mul_mm_cm2_spec(wt, a, (uint32_t)type); }; 2307 create_mm_pipelines({type, GGML_TYPE_F16, false, true}, tc, "matmul_quant_f16_f16acc", matmul_quant_f16_f16acc_cm2_len, matmul_quant_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, qs, true); 2308 create_mm_pipelines({type, GGML_TYPE_F16, false, false}, tc, "matmul_quant_f16", matmul_quant_f16_cm2_len, matmul_quant_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, qs, true); 2309 } 2310 create_mm_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, false, true}, tc_mmq_k, "matmul_q4_k_f16_f16acc", matmul_q4_k_f16_f16acc_cm2_len, matmul_q4_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); 2311 create_mm_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, false, false}, tc_mmq_k, "matmul_q4_k_f16", matmul_q4_k_f16_cm2_len, matmul_q4_k_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); 2312 create_mm_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, false, true}, tc_mmq_k, "matmul_q5_k_f16_f16acc", matmul_q5_k_f16_f16acc_cm2_len, matmul_q5_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); 2313 create_mm_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, false, false}, tc_mmq_k, "matmul_q5_k_f16", matmul_q5_k_f16_cm2_len, matmul_q5_k_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); 2314 #define X_CM2(TYPE, tstr) \ 2315 { auto tc = filter_tc(tc_mmq, TYPE, false); \ 2316 if (!tc.empty()) { \ 2317 create_mm_pipelines({TYPE, GGML_TYPE_F16, false, true}, tc, "matmul_" #tstr "_f16_f16acc", matmul_##tstr##_f16_f16acc_cm2_len, matmul_##tstr##_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ 2318 create_mm_pipelines({TYPE, GGML_TYPE_F16, false, false}, tc, "matmul_" #tstr "_f16", matmul_##tstr##_f16_cm2_len, matmul_##tstr##_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ 2319 } } 2320 FOR_EACH_LUT_TYPE_NONFP4(X_CM2) 2321 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 2322 if (device->ocp_fp4) { 2323 #define X_CM2_OCP(TYPE, tstr) \ 2324 { auto tc = filter_tc(tc_mmq, TYPE, false); \ 2325 if (!tc.empty()) { \ 2326 create_mm_pipelines({TYPE, GGML_TYPE_F16, false, true}, tc, "matmul_" #tstr "_f16_ocp_f16acc", matmul_##tstr##_f16_ocp_f16acc_cm2_len, matmul_##tstr##_f16_ocp_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ 2327 create_mm_pipelines({TYPE, GGML_TYPE_F16, false, false}, tc, "matmul_" #tstr "_f16_ocp", matmul_##tstr##_f16_ocp_cm2_len, matmul_##tstr##_f16_ocp_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ 2328 } } 2329 FOR_EACH_LUT_FP4_TYPE(X_CM2_OCP) 2330 #undef X_CM2_OCP 2331 } else 2332 #endif 2333 { 2334 FOR_EACH_LUT_FP4_TYPE(X_CM2) 2335 } 2336 #undef X_CM2 2337 2338 GGML_ASSERT(device->subgroup_ballot); 2339 2340 create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_mm, "matmul_id_subgroup_f16_f16acc", matmul_id_subgroup_f16_f16acc_cm2_len, matmul_id_subgroup_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); 2341 create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_mm, "matmul_id_subgroup_f16", matmul_id_subgroup_f16_cm2_len, matmul_id_subgroup_f16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); 2342 #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 2343 if (device->coopmat_bf16_support) { 2344 create_mm_pipelines({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_mm, "matmul_id_subgroup_bf16", matmul_id_subgroup_bf16_cm2_len, matmul_id_subgroup_bf16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); 2345 } 2346 #endif 2347 for (const auto type : non_lut_quant_types) { 2348 if (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) { 2349 continue; 2350 } 2351 spec_fn_t qs_id = [&, type](const std::vector& wt, bool a) { return ggml_vk_mul_mm_cm2_spec(wt, a, (uint32_t)type); }; 2352 create_mm_pipelines({type, GGML_TYPE_F16, true, true}, tc_mmqid, "matmul_id_subgroup_quant_f16_f16acc", matmul_id_subgroup_quant_f16_f16acc_cm2_len, matmul_id_subgroup_quant_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, qs_id, true); 2353 create_mm_pipelines({type, GGML_TYPE_F16, true, false}, tc_mmqid, "matmul_id_subgroup_quant_f16", matmul_id_subgroup_quant_f16_cm2_len, matmul_id_subgroup_quant_f16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, qs_id, true); 2354 } 2355 create_mm_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, true, true}, tc_mmqid, "matmul_id_subgroup_q4_k_f16_f16acc", matmul_id_subgroup_q4_k_f16_f16acc_cm2_len, matmul_id_subgroup_q4_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); 2356 create_mm_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, true, false}, tc_mmqid, "matmul_id_subgroup_q4_k_f16", matmul_id_subgroup_q4_k_f16_cm2_len, matmul_id_subgroup_q4_k_f16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); 2357 create_mm_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, true, true}, tc_mmqid, "matmul_id_subgroup_q5_k_f16_f16acc", matmul_id_subgroup_q5_k_f16_f16acc_cm2_len, matmul_id_subgroup_q5_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); 2358 create_mm_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, true, false}, tc_mmqid, "matmul_id_subgroup_q5_k_f16", matmul_id_subgroup_q5_k_f16_cm2_len, matmul_id_subgroup_q5_k_f16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); 2359 #define X_CM2_ID(TYPE, tstr) \ 2360 { auto tc = filter_tc(tc_mmqid, TYPE, true); \ 2361 if (!tc.empty()) { \ 2362 create_mm_pipelines({TYPE, GGML_TYPE_F16, true, true}, tc, "matmul_id_subgroup_" #tstr "_f16_f16acc", matmul_id_subgroup_##tstr##_f16_f16acc_cm2_len, matmul_id_subgroup_##tstr##_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); \ 2363 create_mm_pipelines({TYPE, GGML_TYPE_F16, true, false}, tc, "matmul_id_subgroup_" #tstr "_f16", matmul_id_subgroup_##tstr##_f16_cm2_len, matmul_id_subgroup_##tstr##_f16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); \ 2364 } } 2365 FOR_EACH_LUT_TYPE_NONFP4(X_CM2_ID) 2366 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 2367 if (device->ocp_fp4) { 2368 #define X_CM2_ID_OCP(TYPE, tstr) \ 2369 { auto tc = filter_tc(tc_mmqid, TYPE, true); \ 2370 if (!tc.empty()) { \ 2371 create_mm_pipelines({TYPE, GGML_TYPE_F16, true, true}, tc, "matmul_id_subgroup_" #tstr "_f16_ocp_f16acc", matmul_id_subgroup_##tstr##_f16_ocp_f16acc_cm2_len, matmul_id_subgroup_##tstr##_f16_ocp_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); \ 2372 create_mm_pipelines({TYPE, GGML_TYPE_F16, true, false}, tc, "matmul_id_subgroup_" #tstr "_f16_ocp", matmul_id_subgroup_##tstr##_f16_ocp_cm2_len, matmul_id_subgroup_##tstr##_f16_ocp_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true); \ 2373 } } 2374 FOR_EACH_LUT_FP4_TYPE(X_CM2_ID_OCP) 2375 #undef X_CM2_ID_OCP 2376 } else 2377 #endif 2378 { 2379 FOR_EACH_LUT_FP4_TYPE(X_CM2_ID) 2380 } 2381 #undef X_CM2_ID 2382 } else 2383 #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 2384 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 2385 if (device->coopmat_support) { 2386 spec_fn_t cm1_spec = [&](const std::vector& wt, bool a) { return ggml_vk_mul_mm_spec(wt, a); }; 2387 2388 // Intel coopmat1 pins each pipeline's required subgroup size to its warptile WARP element. 2389 const bool cm1_pin = device->vendor_id == VK_VENDOR_ID_INTEL; 2390 2391 // Intel coopmat1 uses a dedicated large-tile config for quant matmul_id. 2392 std::vector tc_mmq_id = tc_mmq; 2393 if (cm1_pin) { 2394 tc_mmq_id[2] = { { 512, 128, 128, 32, 32, 32, 2, device->coopmat_m, device->coopmat_n, device->coopmat_k, 32 }, { 128, 128, 1 }, 32 }; 2395 } 2396 2397 auto cm1_create = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, 2398 const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc) { 2399 auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id); 2400 if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, cm1_spec, false, true, 0, true, cm1_pin); 2401 }; 2402 auto cm1_create_quant = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, 2403 const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc) { 2404 spec_fn_t qs = [&, type_a=key.type_a](const std::vector& wt, bool a) { return ggml_vk_mul_mm_spec_quant(wt, a, (uint32_t)type_a); }; 2405 auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id); 2406 if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, qs, false, true, 0, true, cm1_pin); 2407 }; 2408 // int8 MMQ helper: per-type cm1 shader, warptile passed as-is (carries DEVICE_ARCH in 2409 // spec constant WARP_SIZE_IDX+1), subgroup size pinned to the warptile WARP element, no aligned variant. 2410 auto cm1_create_mmq = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, 2411 const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc) { 2412 spec_fn_t identity = [](const std::vector& wt, bool) { return wt; }; 2413 auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id, true); 2414 if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, identity, false, false, 0, false, true); 2415 }; 2416 2417 std::vector tc_mmq_cm1_int = { 2418 {s_warptile_mmq_cm1_int, s_mmq_wg_denoms, s_align}, 2419 {m_warptile_mmq_cm1_int, m_mmq_wg_denoms, m_align}, 2420 {l_warptile_mmq_cm1_int, l_mmq_wg_denoms, l_align}, 2421 }; 2422 std::vector tc_mmq_cm1_int_k = { 2423 {s_warptile_mmq_cm1_int_k, s_mmq_cm1_wg_denoms_k, s_align}, 2424 {m_warptile_mmq_cm1_int_k, m_mmq_cm1_wg_denoms_k, m_align}, 2425 {l_warptile_mmq_cm1_int_k, l_mmq_cm1_wg_denoms_k, l_align}, 2426 }; 2427 2428 // Some quants are not performant on RDNA4, those fall back to FP16 matmul 2429 const bool rdna3 = device->architecture == AMD_RDNA3; 2430 const bool rdna4 = device->architecture == AMD_RDNA4; 2431 2432 cm1_create({GGML_TYPE_F32, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f32_f32", matmul_f32_f32_cm1_len, matmul_f32_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2433 cm1_create({GGML_TYPE_F32, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f32_f16", matmul_f32_f16_cm1_len, matmul_f32_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2434 if (device->coopmat_acc_f16_support) { 2435 cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, false, true}, tc_mm, "matmul_f16_f16acc", matmul_f16_f16acc_cm1_len, matmul_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2436 cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, false, true}, tc_mm, "matmul_f16_f32_f16acc", matmul_f16_f32_f16acc_cm1_len, matmul_f16_f32_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2437 } 2438 if (device->coopmat_acc_f32_support) { 2439 cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", matmul_f16_cm1_len, matmul_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2440 cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f16_f32", matmul_f16_f32_cm1_len, matmul_f16_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2441 } 2442 #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 2443 if (device->coopmat_bf16_support) { 2444 cm1_create({GGML_TYPE_BF16, GGML_TYPE_BF16, false, false}, tc_mm, "matmul_bf16", matmul_bf16_cm1_len, matmul_bf16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2445 } 2446 #endif 2447 for (const auto type : non_lut_quant_types) { 2448 if (device->coopmat_acc_f16_support) { 2449 cm1_create_quant({type, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_quant_f32_f16acc", matmul_quant_f32_f16acc_cm1_len, matmul_quant_f32_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2450 cm1_create_quant({type, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_quant_f16_f16acc", matmul_quant_f16_f16acc_cm1_len, matmul_quant_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2451 } 2452 if (device->coopmat_acc_f32_support) { 2453 cm1_create_quant({type, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_quant_f32", matmul_quant_f32_cm1_len, matmul_quant_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2454 cm1_create_quant({type, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_quant_f16", matmul_quant_f16_cm1_len, matmul_quant_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2455 } 2456 } 2457 // The _f16 variants provide the f16 B-type pipeline used when y_non_contig converts f32->f16. 2458 #define X_CM1(TYPE, tstr) \ 2459 if (device->coopmat_acc_f16_support) { \ 2460 cm1_create({TYPE, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_" #tstr "_f32_f16acc", matmul_##tstr##_f32_f16acc_cm1_len, matmul_##tstr##_f32_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2461 cm1_create({TYPE, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_" #tstr "_f16_f16acc", matmul_##tstr##_f16_f16acc_cm1_len, matmul_##tstr##_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2462 } \ 2463 if (device->coopmat_acc_f32_support) { \ 2464 cm1_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", matmul_##tstr##_f32_cm1_len, matmul_##tstr##_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2465 cm1_create({TYPE, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_" #tstr "_f16", matmul_##tstr##_f16_cm1_len, matmul_##tstr##_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2466 } 2467 FOR_EACH_LUT_TYPE_NONFP4(X_CM1) 2468 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 2469 if (device->ocp_fp4) { 2470 #define X_CM1_OCP(TYPE, tstr) \ 2471 if (device->coopmat_acc_f16_support) { \ 2472 cm1_create({TYPE, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_" #tstr "_f32_ocp_f16acc", matmul_##tstr##_f32_ocp_f16acc_cm1_len, matmul_##tstr##_f32_ocp_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2473 cm1_create({TYPE, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_" #tstr "_f16_ocp_f16acc", matmul_##tstr##_f16_ocp_f16acc_cm1_len, matmul_##tstr##_f16_ocp_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2474 } \ 2475 if (device->coopmat_acc_f32_support) { \ 2476 cm1_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32_ocp", matmul_##tstr##_f32_ocp_cm1_len, matmul_##tstr##_f32_ocp_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2477 cm1_create({TYPE, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_" #tstr "_f16_ocp", matmul_##tstr##_f16_ocp_cm1_len, matmul_##tstr##_f16_ocp_cm1_data, sizeof(vk_mat_mat_push_constants), 3); \ 2478 } 2479 FOR_EACH_LUT_FP4_TYPE(X_CM1_OCP) 2480 #undef X_CM1_OCP 2481 } else 2482 #endif 2483 { 2484 FOR_EACH_LUT_FP4_TYPE(X_CM1) 2485 } 2486 #undef X_CM1 2487 2488 if (device->coopmat_int_support && (rdna3 || rdna4)) { 2489 cm1_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_q4_0_q8_1", matmul_q4_0_q8_1_cm1_len, matmul_q4_0_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2490 if (!rdna4) { cm1_create_mmq({GGML_TYPE_Q4_1, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_q4_1_q8_1", matmul_q4_1_q8_1_cm1_len, matmul_q4_1_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); } 2491 cm1_create_mmq({GGML_TYPE_Q5_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_q5_0_q8_1", matmul_q5_0_q8_1_cm1_len, matmul_q5_0_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2492 if (!rdna4) { cm1_create_mmq({GGML_TYPE_Q5_1, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_q5_1_q8_1", matmul_q5_1_q8_1_cm1_len, matmul_q5_1_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); } 2493 cm1_create_mmq({GGML_TYPE_Q8_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_q8_0_q8_1", matmul_q8_0_q8_1_cm1_len, matmul_q8_0_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2494 cm1_create_mmq({GGML_TYPE_IQ4_NL, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_iq4_nl_q8_1", matmul_iq4_nl_q8_1_cm1_len, matmul_iq4_nl_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2495 cm1_create_mmq({GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_iq4_xs_q8_1", matmul_iq4_xs_q8_1_cm1_len, matmul_iq4_xs_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2496 cm1_create_mmq({GGML_TYPE_MXFP4, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_mxfp4_q8_1", matmul_mxfp4_q8_1_cm1_len, matmul_mxfp4_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2497 cm1_create_mmq({GGML_TYPE_Q3_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int_k, "matmul_q3_k_q8_1", matmul_q3_k_q8_1_cm1_len, matmul_q3_k_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2498 if (!rdna4) { cm1_create_mmq({GGML_TYPE_Q4_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_q4_k_q8_1", matmul_q4_k_q8_1_cm1_len, matmul_q4_k_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); } 2499 if (!rdna4) { cm1_create_mmq({GGML_TYPE_Q5_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int, "matmul_q5_k_q8_1", matmul_q5_k_q8_1_cm1_len, matmul_q5_k_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); } 2500 cm1_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int_k, "matmul_q6_k_q8_1", matmul_q6_k_q8_1_cm1_len, matmul_q6_k_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); 2501 if (!rdna4) { cm1_create_mmq({GGML_TYPE_NVFP4, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int_k, "matmul_nvfp4_q8_1", matmul_nvfp4_q8_1_cm1_len, matmul_nvfp4_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); } 2502 } 2503 2504 GGML_ASSERT(device->subgroup_ballot); 2505 2506 cm1_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_subgroup_f32_f32", matmul_id_subgroup_f32_f32_cm1_len, matmul_id_subgroup_f32_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2507 if (device->coopmat_acc_f16_support) { 2508 cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_mm, "matmul_id_subgroup_f16_f16acc", matmul_id_subgroup_f16_f16acc_cm1_len, matmul_id_subgroup_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2509 cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, true, true}, tc_mm, "matmul_id_subgroup_f16_f32_f16acc", matmul_id_subgroup_f16_f32_f16acc_cm1_len, matmul_id_subgroup_f16_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2510 } 2511 if (device->coopmat_acc_f32_support) { 2512 cm1_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_mm, "matmul_id_subgroup_f16", matmul_id_subgroup_f16_cm1_len, matmul_id_subgroup_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2513 cm1_create({GGML_TYPE_F16, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_subgroup_f16_f32", matmul_id_subgroup_f16_f32_cm1_len, matmul_id_subgroup_f16_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2514 } 2515 #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 2516 if (device->coopmat_bf16_support) { 2517 cm1_create({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_mm, "matmul_id_subgroup_bf16", matmul_id_subgroup_bf16_cm1_len, matmul_id_subgroup_bf16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2518 } 2519 #endif 2520 for (const auto type : non_lut_quant_types) { 2521 if (device->coopmat_acc_f16_support) { 2522 cm1_create_quant({type, GGML_TYPE_F32, true, true}, tc_mmq_id, "matmul_id_subgroup_quant_f32_f16acc", matmul_id_subgroup_quant_f32_f16acc_cm1_len, matmul_id_subgroup_quant_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2523 cm1_create_quant({type, GGML_TYPE_F16, true, true}, tc_mmq_id, "matmul_id_subgroup_quant_f16_f16acc", matmul_id_subgroup_quant_f16_f16acc_cm1_len, matmul_id_subgroup_quant_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2524 } 2525 if (device->coopmat_acc_f32_support) { 2526 cm1_create_quant({type, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_quant_f32", matmul_id_subgroup_quant_f32_cm1_len, matmul_id_subgroup_quant_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2527 cm1_create_quant({type, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_quant_f16", matmul_id_subgroup_quant_f16_cm1_len, matmul_id_subgroup_quant_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2528 } 2529 } 2530 // The _f16 variants provide the f16 B-type pipeline used when y_non_contig converts f32->f16. 2531 #define X_CM1_ID(TYPE, tstr) \ 2532 if (device->coopmat_acc_f16_support) { \ 2533 cm1_create({TYPE, GGML_TYPE_F32, true, true}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f32_f16acc", matmul_id_subgroup_##tstr##_f32_f16acc_cm1_len, matmul_id_subgroup_##tstr##_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2534 cm1_create({TYPE, GGML_TYPE_F16, true, true}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f16_f16acc", matmul_id_subgroup_##tstr##_f16_f16acc_cm1_len, matmul_id_subgroup_##tstr##_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2535 } \ 2536 if (device->coopmat_acc_f32_support) { \ 2537 cm1_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f32", matmul_id_subgroup_##tstr##_f32_cm1_len, matmul_id_subgroup_##tstr##_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2538 cm1_create({TYPE, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f16", matmul_id_subgroup_##tstr##_f16_cm1_len, matmul_id_subgroup_##tstr##_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2539 } 2540 FOR_EACH_LUT_TYPE_NONFP4(X_CM1_ID) 2541 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 2542 if (device->ocp_fp4) { 2543 #define X_CM1_ID_OCP(TYPE, tstr) \ 2544 if (device->coopmat_acc_f16_support) { \ 2545 cm1_create({TYPE, GGML_TYPE_F32, true, true}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f32_ocp_f16acc", matmul_id_subgroup_##tstr##_f32_ocp_f16acc_cm1_len, matmul_id_subgroup_##tstr##_f32_ocp_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2546 cm1_create({TYPE, GGML_TYPE_F16, true, true}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f16_ocp_f16acc", matmul_id_subgroup_##tstr##_f16_ocp_f16acc_cm1_len, matmul_id_subgroup_##tstr##_f16_ocp_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2547 } \ 2548 if (device->coopmat_acc_f32_support) { \ 2549 cm1_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f32_ocp", matmul_id_subgroup_##tstr##_f32_ocp_cm1_len, matmul_id_subgroup_##tstr##_f32_ocp_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2550 cm1_create({TYPE, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_" #tstr "_f16_ocp", matmul_id_subgroup_##tstr##_f16_ocp_cm1_len, matmul_id_subgroup_##tstr##_f16_ocp_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2551 } 2552 FOR_EACH_LUT_FP4_TYPE(X_CM1_ID_OCP) 2553 #undef X_CM1_ID_OCP 2554 } else 2555 #endif 2556 { 2557 FOR_EACH_LUT_FP4_TYPE(X_CM1_ID) 2558 } 2559 #undef X_CM1_ID 2560 2561 if (device->coopmat_int_support && (rdna3 || rdna4)) { 2562 cm1_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q4_0_q8_1", matmul_id_subgroup_q4_0_q8_1_cm1_len, matmul_id_subgroup_q4_0_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2563 cm1_create_mmq({GGML_TYPE_Q4_1, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q4_1_q8_1", matmul_id_subgroup_q4_1_q8_1_cm1_len, matmul_id_subgroup_q4_1_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2564 cm1_create_mmq({GGML_TYPE_Q5_0, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q5_0_q8_1", matmul_id_subgroup_q5_0_q8_1_cm1_len, matmul_id_subgroup_q5_0_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2565 cm1_create_mmq({GGML_TYPE_Q5_1, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q5_1_q8_1", matmul_id_subgroup_q5_1_q8_1_cm1_len, matmul_id_subgroup_q5_1_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2566 cm1_create_mmq({GGML_TYPE_Q8_0, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q8_0_q8_1", matmul_id_subgroup_q8_0_q8_1_cm1_len, matmul_id_subgroup_q8_0_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2567 cm1_create_mmq({GGML_TYPE_IQ4_NL, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_iq4_nl_q8_1", matmul_id_subgroup_iq4_nl_q8_1_cm1_len, matmul_id_subgroup_iq4_nl_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2568 cm1_create_mmq({GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_iq4_xs_q8_1", matmul_id_subgroup_iq4_xs_q8_1_cm1_len, matmul_id_subgroup_iq4_xs_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2569 cm1_create_mmq({GGML_TYPE_MXFP4, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_mxfp4_q8_1", matmul_id_subgroup_mxfp4_q8_1_cm1_len, matmul_id_subgroup_mxfp4_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2570 cm1_create_mmq({GGML_TYPE_Q3_K, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int_k, "matmul_id_subgroup_q3_k_q8_1", matmul_id_subgroup_q3_k_q8_1_cm1_len, matmul_id_subgroup_q3_k_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2571 cm1_create_mmq({GGML_TYPE_Q4_K, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q4_k_q8_1", matmul_id_subgroup_q4_k_q8_1_cm1_len, matmul_id_subgroup_q4_k_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2572 cm1_create_mmq({GGML_TYPE_Q5_K, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q5_k_q8_1", matmul_id_subgroup_q5_k_q8_1_cm1_len, matmul_id_subgroup_q5_k_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2573 cm1_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int_k, "matmul_id_subgroup_q6_k_q8_1", matmul_id_subgroup_q6_k_q8_1_cm1_len, matmul_id_subgroup_q6_k_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2574 if (!rdna4) { cm1_create_mmq({GGML_TYPE_NVFP4, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int_k, "matmul_id_subgroup_nvfp4_q8_1", matmul_id_subgroup_nvfp4_q8_1_cm1_len, matmul_id_subgroup_nvfp4_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); } 2575 } 2576 } else 2577 #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 2578 { 2579 // Helper for subgroup path with dot2 selection and filtering 2580 auto sg_create = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, 2581 const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc, 2582 uint32_t rsgs = 0) { 2583 auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id); 2584 if (!tc.empty()) create_mm_pipelines(key, tc, name, len, data, pc_size, pc, 2585 [&](const std::vector& wt, bool a) { return ggml_vk_mul_mm_spec(wt, a); }, 2586 false, rsgs > 0, rsgs); 2587 }; 2588 auto sg_create_quant = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, 2589 const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc, 2590 uint32_t rsgs = 0) { 2591 auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id); 2592 if (!tc.empty()) { 2593 spec_fn_t qs = [&, type_a=key.type_a](const std::vector& wt, bool a) { return ggml_vk_mul_mm_spec_quant(wt, a, (uint32_t)type_a); }; 2594 create_mm_pipelines(key, tc, name, len, data, pc_size, pc, qs, false, rsgs > 0, rsgs); 2595 } 2596 }; 2597 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 2598 auto sg_create_mmq = [&](vk_matmul_pipeline_key key, const std::vector& tc_base, 2599 const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc, 2600 uint32_t rsgs = 0) { 2601 auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id, true); 2602 if (!tc.empty()) { 2603 spec_fn_t identity = [](const std::vector& wt, bool) { return wt; }; 2604 create_mm_pipelines(key, tc, name, len, data, pc_size, pc, identity, false, rsgs > 0, rsgs, false); 2605 } 2606 }; 2607 #endif 2608 2609 std::vector tc_id = {{s_warptile_id, s_wg_denoms, s_align}, {m_warptile_id, m_wg_denoms, m_align}, {l_warptile_id, l_wg_denoms, l_align}}; 2610 std::vector tc_mmqid = {{s_warptile_mmqid, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid, l_mmq_wg_denoms, l_align}}; 2611 2612 if (device->fp16) { 2613 // FP16 subgroup path - with dot2 runtime selection 2614 #define SPV_DOT2(NAME) (device->dot2_f16 ? NAME ## _dot2_len : NAME ## _len), (device->dot2_f16 ? NAME ## _dot2_data : NAME ## _data) 2615 #define SPV_DOT2_F16ACC(NAME) (device->dot2_f16 ? NAME ## _dot2_f16acc_len : NAME ## _f16acc_len), (device->dot2_f16 ? NAME ## _dot2_f16acc_data : NAME ## _f16acc_data) 2616 2617 sg_create({GGML_TYPE_F32, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f32_f32", SPV_DOT2(matmul_f32_f32), sizeof(vk_mat_mat_push_constants), 3); 2618 sg_create({GGML_TYPE_F32, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f32_f16", SPV_DOT2(matmul_f32_f16), sizeof(vk_mat_mat_push_constants), 3); 2619 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, false, true}, tc_mm, "matmul_f16_f16acc", SPV_DOT2_F16ACC(matmul_f16), sizeof(vk_mat_mat_push_constants), 3); 2620 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", SPV_DOT2(matmul_f16), sizeof(vk_mat_mat_push_constants), 3); 2621 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, false, true}, tc_mm, "matmul_f16_f32_f16acc", SPV_DOT2_F16ACC(matmul_f16_f32), sizeof(vk_mat_mat_push_constants), 3); 2622 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f16_f32", SPV_DOT2(matmul_f16_f32), sizeof(vk_mat_mat_push_constants), 3); 2623 // BF16 - no dot2 2624 sg_create({GGML_TYPE_BF16, GGML_TYPE_BF16, false, false}, tc_mm, "matmul_bf16", matmul_bf16_len, matmul_bf16_data, sizeof(vk_mat_mat_push_constants), 3); 2625 2626 for (const auto type : non_lut_quant_types) { 2627 sg_create_quant({type, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_quant_f32_f16acc", SPV_DOT2_F16ACC(matmul_quant_f32), sizeof(vk_mat_mat_push_constants), 3); 2628 sg_create_quant({type, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_quant_f32", SPV_DOT2(matmul_quant_f32), sizeof(vk_mat_mat_push_constants), 3); 2629 } 2630 #define X_SG(TYPE, tstr) \ 2631 sg_create({TYPE, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_" #tstr "_f32_f16acc", SPV_DOT2_F16ACC(matmul_##tstr##_f32), sizeof(vk_mat_mat_push_constants), 3); \ 2632 sg_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", SPV_DOT2(matmul_##tstr##_f32), sizeof(vk_mat_mat_push_constants), 3); 2633 FOR_EACH_LUT_TYPE(X_SG) 2634 #undef X_SG 2635 2636 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 2637 if (device->integer_dot_product) { 2638 std::vector tc_mmq_int = {{s_warptile_mmq_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmq_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmq_int, l_mmq_wg_denoms, l_align}}; 2639 std::vector tc_mmq_int_k = {{s_warptile_mmq_int_k, s_mmq_wg_denoms, s_align}, {m_warptile_mmq_int_k, m_mmq_wg_denoms, m_align}, {l_warptile_mmq_int_k, l_mmq_wg_denoms, l_align}}; 2640 sg_create_mmq({GGML_TYPE_Q2_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q2_0_q8_1", matmul_q2_0_q8_1_len, matmul_q2_0_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2641 sg_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q4_0_q8_1", matmul_q4_0_q8_1_len, matmul_q4_0_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2642 sg_create_mmq({GGML_TYPE_Q4_1, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q4_1_q8_1", matmul_q4_1_q8_1_len, matmul_q4_1_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2643 sg_create_mmq({GGML_TYPE_Q5_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q5_0_q8_1", matmul_q5_0_q8_1_len, matmul_q5_0_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2644 sg_create_mmq({GGML_TYPE_Q5_1, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q5_1_q8_1", matmul_q5_1_q8_1_len, matmul_q5_1_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2645 sg_create_mmq({GGML_TYPE_Q8_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q8_0_q8_1", matmul_q8_0_q8_1_len, matmul_q8_0_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2646 sg_create_mmq({GGML_TYPE_MXFP4, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_mxfp4_q8_1", matmul_mxfp4_q8_1_len, matmul_mxfp4_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2647 sg_create_mmq({GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_iq4_xs_q8_1", matmul_iq4_xs_q8_1_len, matmul_iq4_xs_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2648 sg_create_mmq({GGML_TYPE_Q2_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q2_k_q8_1", matmul_q2_k_q8_1_len, matmul_q2_k_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2649 sg_create_mmq({GGML_TYPE_Q3_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q3_k_q8_1", matmul_q3_k_q8_1_len, matmul_q3_k_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2650 sg_create_mmq({GGML_TYPE_Q4_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q4_k_q8_1", matmul_q4_k_q8_1_len, matmul_q4_k_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2651 sg_create_mmq({GGML_TYPE_Q5_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q5_k_q8_1", matmul_q5_k_q8_1_len, matmul_q5_k_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2652 sg_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q6_k_q8_1", matmul_q6_k_q8_1_len, matmul_q6_k_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2653 sg_create_mmq({GGML_TYPE_IQ3_S, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_iq3_s_q8_1", matmul_iq3_s_q8_1_len, matmul_iq3_s_q8_1_data, sizeof(vk_mat_mat_push_constants), 3); 2654 } 2655 #endif 2656 2657 if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) { 2658 sg_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_id, "matmul_id_subgroup_f32_f32", SPV_DOT2(matmul_id_subgroup_f32_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2659 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_id, "matmul_id_subgroup_f16_f16acc", SPV_DOT2_F16ACC(matmul_id_subgroup_f16), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2660 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_id, "matmul_id_subgroup_f16", SPV_DOT2(matmul_id_subgroup_f16), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2661 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, true, true}, tc_id, "matmul_id_subgroup_f16_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_subgroup_f16_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2662 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, true, false}, tc_id, "matmul_id_subgroup_f16_f32", SPV_DOT2(matmul_id_subgroup_f16_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2663 // BF16 id - no dot2 2664 sg_create({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_id, "matmul_id_subgroup_bf16", matmul_id_subgroup_bf16_len, matmul_id_subgroup_bf16_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2665 for (const auto type : non_lut_quant_types) { 2666 sg_create_quant({type, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_subgroup_quant_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_subgroup_quant_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2667 sg_create_quant({type, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_quant_f32", SPV_DOT2(matmul_id_subgroup_quant_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2668 } 2669 #define X_SG_ID_SUB(TYPE, tstr) \ 2670 sg_create({TYPE, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_subgroup_" #tstr "_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_subgroup_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); \ 2671 sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_" #tstr "_f32", SPV_DOT2(matmul_id_subgroup_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2672 FOR_EACH_LUT_TYPE(X_SG_ID_SUB) 2673 #undef X_SG_ID_SUB 2674 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 2675 if (device->integer_dot_product) { 2676 std::vector tc_mmqid_int = {{s_warptile_mmqid_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int, l_mmq_wg_denoms, l_align}}; 2677 std::vector tc_mmqid_int_k = {{s_warptile_mmqid_int_k, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int_k, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int_k, l_mmq_wg_denoms, l_align}}; 2678 sg_create_mmq({GGML_TYPE_Q2_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_q2_0_q8_1", matmul_id_subgroup_q2_0_q8_1_len, matmul_id_subgroup_q2_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2679 sg_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_q4_0_q8_1", matmul_id_subgroup_q4_0_q8_1_len, matmul_id_subgroup_q4_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2680 sg_create_mmq({GGML_TYPE_Q4_1, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_q4_1_q8_1", matmul_id_subgroup_q4_1_q8_1_len, matmul_id_subgroup_q4_1_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2681 sg_create_mmq({GGML_TYPE_Q5_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_q5_0_q8_1", matmul_id_subgroup_q5_0_q8_1_len, matmul_id_subgroup_q5_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2682 sg_create_mmq({GGML_TYPE_Q5_1, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_q5_1_q8_1", matmul_id_subgroup_q5_1_q8_1_len, matmul_id_subgroup_q5_1_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2683 sg_create_mmq({GGML_TYPE_Q8_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_q8_0_q8_1", matmul_id_subgroup_q8_0_q8_1_len, matmul_id_subgroup_q8_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2684 sg_create_mmq({GGML_TYPE_MXFP4, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_mxfp4_q8_1", matmul_id_subgroup_mxfp4_q8_1_len, matmul_id_subgroup_mxfp4_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2685 sg_create_mmq({GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_subgroup_iq4_xs_q8_1", matmul_id_subgroup_iq4_xs_q8_1_len, matmul_id_subgroup_iq4_xs_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2686 sg_create_mmq({GGML_TYPE_Q2_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_subgroup_q2_k_q8_1", matmul_id_subgroup_q2_k_q8_1_len, matmul_id_subgroup_q2_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2687 sg_create_mmq({GGML_TYPE_Q3_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_subgroup_q3_k_q8_1", matmul_id_subgroup_q3_k_q8_1_len, matmul_id_subgroup_q3_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2688 sg_create_mmq({GGML_TYPE_Q4_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_subgroup_q4_k_q8_1", matmul_id_subgroup_q4_k_q8_1_len, matmul_id_subgroup_q4_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2689 sg_create_mmq({GGML_TYPE_Q5_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_subgroup_q5_k_q8_1", matmul_id_subgroup_q5_k_q8_1_len, matmul_id_subgroup_q5_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2690 sg_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_subgroup_q6_k_q8_1", matmul_id_subgroup_q6_k_q8_1_len, matmul_id_subgroup_q6_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2691 sg_create_mmq({GGML_TYPE_IQ3_S, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_subgroup_iq3_s_q8_1", matmul_id_subgroup_iq3_s_q8_1_len, matmul_id_subgroup_iq3_s_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2692 } 2693 #endif 2694 } else { 2695 sg_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_f32_f32", SPV_DOT2(matmul_id_f32_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2696 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_mm, "matmul_id_f16_f16acc", SPV_DOT2_F16ACC(matmul_id_f16), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2697 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_mm, "matmul_id_f16", SPV_DOT2(matmul_id_f16), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2698 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, true, true}, tc_mm, "matmul_id_f16_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_f16_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2699 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_f16_f32", SPV_DOT2(matmul_id_f16_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2700 // BF16 id - no dot2 2701 sg_create({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_mm, "matmul_id_bf16", matmul_id_bf16_len, matmul_id_bf16_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2702 for (const auto type : non_lut_quant_types) { 2703 sg_create_quant({type, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_quant_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_quant_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2704 sg_create_quant({type, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_quant_f32", SPV_DOT2(matmul_id_quant_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2705 } 2706 #define X_SG_ID(TYPE, tstr) \ 2707 sg_create({TYPE, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_" #tstr "_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); \ 2708 sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_" #tstr "_f32", SPV_DOT2(matmul_id_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2709 FOR_EACH_LUT_TYPE(X_SG_ID) 2710 #undef X_SG_ID 2711 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 2712 if (device->integer_dot_product) { 2713 std::vector tc_mmqid_int = {{s_warptile_mmqid_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int, l_mmq_wg_denoms, l_align}}; 2714 std::vector tc_mmqid_int_k = {{s_warptile_mmqid_int_k, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int_k, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int_k, l_mmq_wg_denoms, l_align}}; 2715 sg_create_mmq({GGML_TYPE_Q2_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_q2_0_q8_1", matmul_id_q2_0_q8_1_len, matmul_id_q2_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2716 sg_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_q4_0_q8_1", matmul_id_q4_0_q8_1_len, matmul_id_q4_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2717 sg_create_mmq({GGML_TYPE_Q4_1, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_q4_1_q8_1", matmul_id_q4_1_q8_1_len, matmul_id_q4_1_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2718 sg_create_mmq({GGML_TYPE_Q5_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_q5_0_q8_1", matmul_id_q5_0_q8_1_len, matmul_id_q5_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2719 sg_create_mmq({GGML_TYPE_Q5_1, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_q5_1_q8_1", matmul_id_q5_1_q8_1_len, matmul_id_q5_1_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2720 sg_create_mmq({GGML_TYPE_Q8_0, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_q8_0_q8_1", matmul_id_q8_0_q8_1_len, matmul_id_q8_0_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2721 sg_create_mmq({GGML_TYPE_MXFP4, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_mxfp4_q8_1", matmul_id_mxfp4_q8_1_len, matmul_id_mxfp4_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2722 sg_create_mmq({GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int, "matmul_id_iq4_xs_q8_1", matmul_id_iq4_xs_q8_1_len, matmul_id_iq4_xs_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2723 sg_create_mmq({GGML_TYPE_Q2_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_q2_k_q8_1", matmul_id_q2_k_q8_1_len, matmul_id_q2_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2724 sg_create_mmq({GGML_TYPE_Q3_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_q3_k_q8_1", matmul_id_q3_k_q8_1_len, matmul_id_q3_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2725 sg_create_mmq({GGML_TYPE_Q4_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_q4_k_q8_1", matmul_id_q4_k_q8_1_len, matmul_id_q4_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2726 sg_create_mmq({GGML_TYPE_Q5_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_q5_k_q8_1", matmul_id_q5_k_q8_1_len, matmul_id_q5_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2727 sg_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_q6_k_q8_1", matmul_id_q6_k_q8_1_len, matmul_id_q6_k_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2728 sg_create_mmq({GGML_TYPE_IQ3_S, GGML_TYPE_Q8_1, true, false}, tc_mmqid_int_k, "matmul_id_iq3_s_q8_1", matmul_id_iq3_s_q8_1_len, matmul_id_iq3_s_q8_1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2729 } 2730 #endif 2731 } 2732 #undef SPV_DOT2 2733 #undef SPV_DOT2_F16ACC 2734 } else { 2735 // FP32-only fallback path 2736 sg_create({GGML_TYPE_F32, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f32_f32", matmul_f32_f32_fp32_len, matmul_f32_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2737 sg_create({GGML_TYPE_F32, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f32_f16", matmul_f32_f16_fp32_len, matmul_f32_f16_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2738 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", matmul_f16_fp32_len, matmul_f16_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2739 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, false, false}, tc_mm, "matmul_f16_f32", matmul_f16_f32_fp32_len, matmul_f16_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2740 sg_create({GGML_TYPE_BF16, GGML_TYPE_BF16, false, false}, tc_mm, "matmul_bf16", matmul_bf16_fp32_len, matmul_bf16_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2741 2742 for (const auto type : non_lut_quant_types) { 2743 sg_create_quant({type, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_quant_f32", matmul_quant_f32_fp32_len, matmul_quant_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2744 } 2745 #define X_SG_FP32(TYPE, tstr) \ 2746 sg_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", matmul_##tstr##_f32_fp32_len, matmul_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2747 FOR_EACH_LUT_TYPE(X_SG_FP32) 2748 #undef X_SG_FP32 2749 2750 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 2751 if (device->integer_dot_product) { 2752 std::vector tc_mmq_int = {{s_warptile_mmq_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmq_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmq_int, l_mmq_wg_denoms, l_align}}; 2753 std::vector tc_mmq_int_k = {{s_warptile_mmq_int_k, s_mmq_wg_denoms, s_align}, {m_warptile_mmq_int_k, m_mmq_wg_denoms, m_align}, {l_warptile_mmq_int_k, l_mmq_wg_denoms, l_align}}; 2754 sg_create_mmq({GGML_TYPE_Q2_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q2_0_q8_1", matmul_q2_0_q8_1_fp32_len, matmul_q2_0_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2755 sg_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q4_0_q8_1", matmul_q4_0_q8_1_fp32_len, matmul_q4_0_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2756 sg_create_mmq({GGML_TYPE_Q4_1, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q4_1_q8_1", matmul_q4_1_q8_1_fp32_len, matmul_q4_1_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2757 sg_create_mmq({GGML_TYPE_Q5_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q5_0_q8_1", matmul_q5_0_q8_1_fp32_len, matmul_q5_0_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2758 sg_create_mmq({GGML_TYPE_Q5_1, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q5_1_q8_1", matmul_q5_1_q8_1_fp32_len, matmul_q5_1_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2759 sg_create_mmq({GGML_TYPE_Q8_0, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_q8_0_q8_1", matmul_q8_0_q8_1_fp32_len, matmul_q8_0_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2760 sg_create_mmq({GGML_TYPE_IQ4_XS, GGML_TYPE_Q8_1, false, false}, tc_mmq_int, "matmul_iq4_xs_q8_1", matmul_iq4_xs_q8_1_fp32_len, matmul_iq4_xs_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2761 sg_create_mmq({GGML_TYPE_Q2_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q2_k_q8_1", matmul_q2_k_q8_1_fp32_len, matmul_q2_k_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2762 sg_create_mmq({GGML_TYPE_Q3_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q3_k_q8_1", matmul_q3_k_q8_1_fp32_len, matmul_q3_k_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2763 sg_create_mmq({GGML_TYPE_Q4_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q4_k_q8_1", matmul_q4_k_q8_1_fp32_len, matmul_q4_k_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2764 sg_create_mmq({GGML_TYPE_Q5_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q5_k_q8_1", matmul_q5_k_q8_1_fp32_len, matmul_q5_k_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2765 sg_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_q6_k_q8_1", matmul_q6_k_q8_1_fp32_len, matmul_q6_k_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2766 sg_create_mmq({GGML_TYPE_IQ3_S, GGML_TYPE_Q8_1, false, false}, tc_mmq_int_k, "matmul_iq3_s_q8_1", matmul_iq3_s_q8_1_fp32_len, matmul_iq3_s_q8_1_fp32_data, sizeof(vk_mat_mat_push_constants), 3); 2767 } 2768 #endif 2769 2770 if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) { 2771 sg_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_id, "matmul_id_subgroup_f32_f32", matmul_id_subgroup_f32_f32_fp32_len, matmul_id_subgroup_f32_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2772 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_id, "matmul_id_subgroup_f16", matmul_id_subgroup_f16_fp32_len, matmul_id_subgroup_f16_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2773 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, true, false}, tc_id, "matmul_id_subgroup_f16_f32", matmul_id_subgroup_f16_f32_fp32_len, matmul_id_subgroup_f16_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2774 sg_create({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_id, "matmul_id_subgroup_bf16", matmul_id_subgroup_bf16_fp32_len, matmul_id_subgroup_bf16_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size_16); 2775 for (const auto type : non_lut_quant_types) { 2776 sg_create_quant({type, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_quant_f32", matmul_id_subgroup_quant_f32_fp32_len, matmul_id_subgroup_quant_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2777 } 2778 #define X_SG_ID_SUB_FP32(TYPE, tstr) \ 2779 sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_" #tstr "_f32", matmul_id_subgroup_##tstr##_f32_fp32_len, matmul_id_subgroup_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size); 2780 FOR_EACH_LUT_TYPE(X_SG_ID_SUB_FP32) 2781 #undef X_SG_ID_SUB_FP32 2782 } else { 2783 sg_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_f32_f32", matmul_id_f32_f32_fp32_len, matmul_id_f32_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2784 sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_mm, "matmul_id_f16", matmul_id_f16_fp32_len, matmul_id_f16_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2785 sg_create({GGML_TYPE_F16, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_f16_f32", matmul_id_f16_f32_fp32_len, matmul_id_f16_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2786 sg_create({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_mm, "matmul_id_bf16", matmul_id_bf16_fp32_len, matmul_id_bf16_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2787 for (const auto type : non_lut_quant_types) { 2788 sg_create_quant({type, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_quant_f32", matmul_id_quant_f32_fp32_len, matmul_id_quant_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2789 } 2790 #define X_SG_ID_FP32(TYPE, tstr) \ 2791 sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_" #tstr "_f32", matmul_id_##tstr##_f32_fp32_len, matmul_id_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count); 2792 FOR_EACH_LUT_TYPE(X_SG_ID_FP32) 2793 #undef X_SG_ID_FP32 2794 } 2795 } 2796 } 2797 #undef FOR_EACH_LUT_TYPE 2798 #undef FOR_EACH_LUT_TYPE_NONFP4 2799 #undef FOR_EACH_LUT_FP4_TYPE 2800 // BF16 fallback for coopmat devices without bf16 coopmat support 2801 if ((device->coopmat2 || device->coopmat_support) 2802 #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 2803 && !device->coopmat_bf16_support 2804 #endif 2805 ) { 2806 std::vector tc_bf16_fb = { 2807 {{ subgroup_size_32, 32, 32, 16, s_warptile_wm_8, 32, 2, 2, 2, 1, subgroup_size_8 }, {32, 32, 1}, s_align}, 2808 {{ 128, 64, 64, 16, mm_warp_8, 32, 2, 4, 2, 1, mm_warp_8 }, {64, 64, 1}, m_align}, 2809 {{ 128, 128, 128, 16, mm_warp_8 * 2, 64, 2, 4, 4, 1, mm_warp_8 }, {128, 128, 1}, l_align}, 2810 }; 2811 auto tc_bf16_filtered = filter_tc(tc_bf16_fb, GGML_TYPE_BF16, false); 2812 auto tc_bf16_id_filtered = filter_tc(tc_bf16_fb, GGML_TYPE_BF16, true); 2813 spec_fn_t bf16_spec = [&](const std::vector& wt, bool a) { return ggml_vk_mul_mm_spec(wt, a); }; 2814 if (!tc_bf16_filtered.empty()) { 2815 create_mm_pipelines({GGML_TYPE_BF16, GGML_TYPE_BF16, false, false}, tc_bf16_filtered, "matmul_bf16", matmul_bf16_fp32_len, matmul_bf16_fp32_data, sizeof(vk_mat_mat_push_constants), 3, bf16_spec); 2816 } 2817 if (!tc_bf16_id_filtered.empty()) { 2818 create_mm_pipelines({GGML_TYPE_BF16, GGML_TYPE_BF16, true, false}, tc_bf16_id_filtered, "matmul_id_bf16", matmul_id_bf16_fp32_len, matmul_id_bf16_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, bf16_spec); 2819 } 2820 } 2821 2822 // Set up tile selector functions 2823 if (device->coopmat2) { 2824 device->matmul_tile_selector = [](uint32_t m, uint32_t n, uint32_t /*k*/, uint32_t shader_core_count, 2825 const std::vector& configs) -> uint32_t { 2826 if (configs.size() <= 1) return 0; 2827 uint32_t last = (uint32_t)configs.size() - 1; 2828 if (configs.size() == 2) { 2829 uint32_t crossover = configs[0].unaligned->wg_denoms[1]; 2830 return (n > crossover) ? 1 : 0; 2831 } 2832 // 3+ configs: s=0, m=1, l=2 2833 const uint32_t tiles_l = CEIL_DIV(m, configs[last].unaligned->wg_denoms[0]) * CEIL_DIV(n, configs[last].unaligned->wg_denoms[1]); 2834 const uint32_t tiles_m = CEIL_DIV(m, configs[1].unaligned->wg_denoms[0]) * CEIL_DIV(n, configs[1].unaligned->wg_denoms[1]); 2835 uint32_t crossover_large = configs[1].unaligned->wg_denoms[1]; 2836 bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count || 2837 (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2); 2838 if (n > crossover_large && prefer_large) return last; 2839 uint32_t crossover_medium_m = configs[0].unaligned->wg_denoms[0]; 2840 uint32_t crossover_medium_n = configs[0].unaligned->wg_denoms[1]; 2841 if (m > crossover_medium_m && n > crossover_medium_n) return 1; 2842 return 0; 2843 }; 2844 device->matmul_id_tile_selector = [](uint32_t /*m*/, uint32_t n, uint32_t /*k*/, uint32_t /*shader_core_count*/, 2845 const std::vector& configs) -> uint32_t { 2846 if (configs.size() <= 1) return 0; 2847 uint32_t last = (uint32_t)configs.size() - 1; 2848 if (configs.size() == 2) { 2849 uint32_t crossover = configs[0].unaligned->wg_denoms[1]; 2850 return (n > crossover) ? 1 : 0; 2851 } 2852 uint32_t crossover_large = configs[1].unaligned->wg_denoms[1]; 2853 if (n > crossover_large) return last; 2854 uint32_t crossover_medium = configs[0].unaligned->wg_denoms[1]; 2855 if (n > crossover_medium) return 1; 2856 return 0; 2857 }; 2858 } else { 2859 device->matmul_tile_selector = [](uint32_t m, uint32_t n, uint32_t /*k*/, uint32_t /*shader_core_count*/, 2860 const std::vector& configs) -> uint32_t { 2861 if (configs.size() <= 1) return 0; 2862 if (m <= 32 || n <= 32) return 0; 2863 if (configs.size() == 2) return 1; 2864 if (m <= 64 || n <= 64) return 1; 2865 return (uint32_t)configs.size() - 1; 2866 }; 2867 device->matmul_id_tile_selector = device->matmul_tile_selector; 2868 } 2869 2870 // mul mat vec 2871 2872 // the number of rows computed per shader depends on GPU model and quant 2873 uint32_t rm_stdq = 1; 2874 uint32_t rm_kq = 2; 2875 uint32_t rm_stdq_int = 1; 2876 uint32_t rm_kq_int = 1; 2877 auto const &rm_iq_int = [](uint32_t i) { return i == 0 ? 8u : 4u; }; 2878 if (device->vendor_id == VK_VENDOR_ID_AMD) { 2879 if (device->architecture == AMD_GCN) { 2880 rm_stdq = 2; 2881 rm_kq = 4; 2882 rm_stdq_int = 4; 2883 } 2884 } else if (device->vendor_id == VK_VENDOR_ID_INTEL) { 2885 rm_stdq = 2; 2886 rm_stdq_int = 2; 2887 } 2888 // RDNA3/4: above four columns, static 4 rows for all types bench faster than the default 2889 const bool is_rdna3_or_4 = device->vendor_id == VK_VENDOR_ID_AMD && (device->architecture == AMD_RDNA3 || device->architecture == AMD_RDNA4); 2890 auto const &rm_int_n = [&](uint32_t rows, uint32_t i) { return (is_rdna3_or_4 && i >= 4) ? 4u : rows; }; 2891 // RDNA3/4 and NVIDIA except pre-Turing: use 4 rows for MUL_MAT_ID MMVQ. 2892 auto const &rm_id = [&](uint32_t rows) { 2893 if (device->vendor_id == VK_VENDOR_ID_NVIDIA && 2894 device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) { 2895 return 4u; 2896 } 2897 return is_rdna3_or_4 ? 4u : rows; 2898 }; 2899 uint32_t rm_iq = 2 * rm_kq; 2900 2901 const bool use_subgroups = device->subgroup_arithmetic; 2902 // The Imagination proprietary compiler rejects the subgroup-only dequant mul_mat_vec 2903 // shaders that require a subgroup size >= 16; fall back to shared-memory reduction. 2904 const bool is_imagination_proprietary = 2905 device->driver_id == vk::DriverId::eImaginationProprietary; 2906 // Ensure a subgroup size >= 16 is available 2907 const bool use_subgroups16 = use_subgroups && subgroup_min_size_16 && !is_imagination_proprietary; 2908 2909 const uint32_t subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && device->subgroup_min_size <= 16 && device->subgroup_max_size >= 16) ? 16 : device->subgroup_size; 2910 const uint32_t subgroup_size16 = std::max(subgroup_size, 16u); 2911 2912 const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0; 2913 const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0; 2914 static constexpr uint32_t mul_mat_vec_num_bindings = 5; 2915 static constexpr uint32_t mul_mat_vec_id_num_bindings = 6; 2916 2917 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 2918 #define OCP_DMMV_LEN(NAME, REDUC) (device->ocp_fp4 ? NAME ## _ocp_len[REDUC] : NAME ## _len[REDUC]) 2919 #define OCP_DMMV_DATA(NAME, REDUC) (device->ocp_fp4 ? NAME ## _ocp_data[REDUC] : NAME ## _data[REDUC]) 2920 #else 2921 #define OCP_DMMV_LEN(NAME, REDUC) NAME ## _len[REDUC] 2922 #define OCP_DMMV_DATA(NAME, REDUC) NAME ## _data[REDUC] 2923 #endif 2924 2925 for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) { 2926 const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4); 2927 const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4); 2928 2929 const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP : 2930 (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID : 2931 SHADER_REDUCTION_MODE_SHMEM; 2932 2933 const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP : 2934 (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID : 2935 SHADER_REDUCTION_MODE_SHMEM; 2936 2937 for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) { 2938 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size); 2939 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); 2940 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); 2941 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q1_0][i], "mul_mat_vec_q1_0_f32_f32", arr_dmmv_q1_0_f32_f32_len[reduc], arr_dmmv_q1_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2942 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_f32_f32", arr_dmmv_q2_0_f32_f32_len[reduc], arr_dmmv_q2_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2943 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2944 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2945 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2946 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2947 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2948 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2949 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2950 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2951 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2952 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2953 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_TQ1_0][i], "mul_mat_vec_tq1_0_f32_f32", arr_dmmv_tq1_0_f32_f32_len[reduc16], arr_dmmv_tq1_0_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2954 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_TQ2_0][i], "mul_mat_vec_tq2_0_f32_f32", arr_dmmv_tq2_0_f32_f32_len[reduc16], arr_dmmv_tq2_0_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2955 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2956 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2957 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2958 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2959 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2960 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2961 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2962 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2963 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2964 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2965 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2966 2967 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size); 2968 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); 2969 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size); 2970 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q1_0][i], "mul_mat_vec_q1_0_f16_f32", arr_dmmv_q1_0_f16_f32_len[reduc], arr_dmmv_q1_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2971 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_f16_f32", arr_dmmv_q2_0_f16_f32_len[reduc], arr_dmmv_q2_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2972 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2973 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2974 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2975 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2976 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size); 2977 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2978 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2979 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2980 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2981 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2982 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_TQ1_0][i], "mul_mat_vec_tq1_0_f16_f32", arr_dmmv_tq1_0_f16_f32_len[reduc16], arr_dmmv_tq1_0_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2983 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_TQ2_0][i], "mul_mat_vec_tq2_0_f16_f32", arr_dmmv_tq2_0_f16_f32_len[reduc16], arr_dmmv_tq2_0_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2984 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2985 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2986 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2987 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2988 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2989 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2990 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2991 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2992 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2993 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2994 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16); 2995 2996 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 2997 if (device->integer_dot_product) { 2998 const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size; 2999 const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4); 3000 3001 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_q8_1_f32", arr_dmmv_q2_0_q8_1_f32_len[reduc], arr_dmmv_q2_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3002 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3003 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3004 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3005 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3006 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3007 3008 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3009 3010 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3011 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3012 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3013 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3014 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3015 3016 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3017 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3018 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_q8_1_f32", arr_dmmv_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_iq4_xs_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); 3019 3020 } 3021 #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT 3022 } 3023 3024 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", arr_dmmv_id_f32_f32_f32_len[reduc], arr_dmmv_id_f32_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {wg_size_subgroup, 1}, 1, false, use_subgroups, force_subgroup_size); 3025 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", arr_dmmv_id_f16_f32_f32_len[reduc], arr_dmmv_id_f16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size); 3026 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", arr_dmmv_id_bf16_f32_f32_len[reduc], arr_dmmv_id_bf16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size); 3027 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q1_0], "mul_mat_vec_id_q1_0_f32", arr_dmmv_id_q1_0_f32_f32_len[reduc], arr_dmmv_id_q1_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); 3028 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_0], "mul_mat_vec_id_q2_0_f32", arr_dmmv_id_q2_0_f32_f32_len[reduc], arr_dmmv_id_q2_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); 3029 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", arr_dmmv_id_q4_0_f32_f32_len[reduc], arr_dmmv_id_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); 3030 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", arr_dmmv_id_q4_1_f32_f32_len[reduc], arr_dmmv_id_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); 3031 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", arr_dmmv_id_q5_0_f32_f32_len[reduc], arr_dmmv_id_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); 3032 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", arr_dmmv_id_q5_1_f32_f32_len[reduc], arr_dmmv_id_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); 3033 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", arr_dmmv_id_q8_0_f32_f32_len[reduc], arr_dmmv_id_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq}, 1, true, use_subgroups, force_subgroup_size); 3034 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", arr_dmmv_id_q2_k_f32_f32_len[reduc16], arr_dmmv_id_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); 3035 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", arr_dmmv_id_q3_k_f32_f32_len[reduc16], arr_dmmv_id_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); 3036 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", arr_dmmv_id_q4_k_f32_f32_len[reduc16], arr_dmmv_id_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); 3037 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", arr_dmmv_id_q5_k_f32_f32_len[reduc16], arr_dmmv_id_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); 3038 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", arr_dmmv_id_q6_k_f32_f32_len[reduc16], arr_dmmv_id_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); 3039 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_TQ1_0], "mul_mat_vec_id_tq1_0_f32", arr_dmmv_id_tq1_0_f32_f32_len[reduc16], arr_dmmv_id_tq1_0_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); 3040 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_TQ2_0], "mul_mat_vec_id_tq2_0_f32", arr_dmmv_id_tq2_0_f32_f32_len[reduc16], arr_dmmv_id_tq2_0_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16); 3041 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", arr_dmmv_id_iq1_s_f32_f32_len[reduc16], arr_dmmv_id_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3042 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", arr_dmmv_id_iq1_m_f32_f32_len[reduc16], arr_dmmv_id_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3043 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", arr_dmmv_id_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3044 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", arr_dmmv_id_iq2_xs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3045 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", arr_dmmv_id_iq2_s_f32_f32_len[reduc16], arr_dmmv_id_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3046 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", arr_dmmv_id_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3047 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", arr_dmmv_id_iq3_s_f32_f32_len[reduc16], arr_dmmv_id_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3048 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", arr_dmmv_id_iq4_xs_f32_f32_len[reduc16], arr_dmmv_id_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3049 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3050 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3051 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_NVFP4], "mul_mat_vec_id_nvfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16); 3052 3053 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 3054 if (device->integer_dot_product) { 3055 const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size; 3056 const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4); 3057 3058 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q2_0], "mul_mat_vec_id_q2_0_q8_1_f32", arr_dmmv_id_q2_0_q8_1_f32_len[reduc], arr_dmmv_id_q2_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(2*rm_kq_int), 1, 1}, {wg_size_subgroup_int, rm_id(2*rm_kq_int)}, 1, true, use_subgroups, subgroup_size_int); 3059 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_q8_1_f32", arr_dmmv_id_q4_0_q8_1_f32_len[reduc], arr_dmmv_id_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_stdq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_stdq_int)}, 1, true, use_subgroups, subgroup_size_int); 3060 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_q8_1_f32", arr_dmmv_id_q4_1_q8_1_f32_len[reduc], arr_dmmv_id_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_stdq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_stdq_int)}, 1, true, use_subgroups, subgroup_size_int); 3061 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_q8_1_f32", arr_dmmv_id_q5_0_q8_1_f32_len[reduc], arr_dmmv_id_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_stdq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_stdq_int)}, 1, true, use_subgroups, subgroup_size_int); 3062 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_q8_1_f32", arr_dmmv_id_q5_1_q8_1_f32_len[reduc], arr_dmmv_id_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_stdq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_stdq_int)}, 1, true, use_subgroups, subgroup_size_int); 3063 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_q8_1_f32", arr_dmmv_id_q8_0_q8_1_f32_len[reduc], arr_dmmv_id_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_stdq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_stdq_int)}, 1, true, use_subgroups, subgroup_size_int); 3064 3065 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_q8_1_f32", arr_dmmv_id_mxfp4_q8_1_f32_len[reduc], arr_dmmv_id_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(2*rm_stdq_int), 1, 1}, {wg_size_subgroup_int, rm_id(2*rm_stdq_int)}, 1, true, use_subgroups, subgroup_size_int); 3066 3067 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_q8_1_f32", arr_dmmv_id_q2_k_q8_1_f32_len[reduc], arr_dmmv_id_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(2*rm_kq_int), 1, 1}, {wg_size_subgroup_int, rm_id(2*rm_kq_int)}, 1, true, use_subgroups, subgroup_size_int); 3068 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_q8_1_f32", arr_dmmv_id_q3_k_q8_1_f32_len[reduc], arr_dmmv_id_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_kq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_kq_int)}, 1, true, use_subgroups, subgroup_size_int); 3069 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_q8_1_f32", arr_dmmv_id_q4_k_q8_1_f32_len[reduc], arr_dmmv_id_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_kq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_kq_int)}, 1, true, use_subgroups, subgroup_size_int); 3070 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_q8_1_f32", arr_dmmv_id_q5_k_q8_1_f32_len[reduc], arr_dmmv_id_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_kq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_kq_int)}, 1, true, use_subgroups, subgroup_size_int); 3071 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_q8_1_f32", arr_dmmv_id_q6_k_q8_1_f32_len[reduc], arr_dmmv_id_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_kq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_kq_int)}, 1, true, use_subgroups, subgroup_size_int); 3072 3073 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_q8_1_f32", arr_dmmv_id_iq1_s_q8_1_f32_len[reduc], arr_dmmv_id_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int); 3074 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_q8_1_f32", arr_dmmv_id_iq1_m_q8_1_f32_len[reduc], arr_dmmv_id_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int); 3075 ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_q8_1_f32", arr_dmmv_id_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_id_iq4_xs_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_id(1*rm_stdq_int), 1, 1}, {wg_size_subgroup_int, rm_id(1*rm_stdq_int)}, 1, true, use_subgroups, subgroup_size_int); 3076 } 3077 #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT 3078 } 3079 3080 #undef OCP_DMMV_DATA 3081 #undef OCP_DMMV_LEN 3082 3083 #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 3084 GGML_UNUSED(rm_stdq_int); 3085 GGML_UNUSED(rm_kq_int); 3086 GGML_UNUSED(is_rdna3_or_4); 3087 GGML_UNUSED(rm_int_n); 3088 GGML_UNUSED(rm_id); 3089 GGML_UNUSED(rm_iq_int); 3090 #endif 3091 3092 // dequant shaders 3093 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_F32 ], "f32_to_f16", dequant_f32_len, dequant_f32_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3094 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q1_0], "dequant_q1_0", dequant_q1_0_len, dequant_q1_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 8, 1, 1}, {}, 1); 3095 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q2_0], "dequant_q2_0", dequant_q2_0_len, dequant_q2_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1); 3096 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_0], "dequant_q4_0", dequant_q4_0_len, dequant_q4_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3097 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_1], "dequant_q4_1", dequant_q4_1_len, dequant_q4_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3098 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_0], "dequant_q5_0", dequant_q5_0_len, dequant_q5_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3099 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_1], "dequant_q5_1", dequant_q5_1_len, dequant_q5_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3100 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q8_0], "dequant_q8_0", dequant_q8_0_len, dequant_q8_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3101 ggml_vk_create_pipeline(device, device->pipeline_dequant_transpose[GGML_TYPE_Q8_0], "dequant_q8_0_transpose", dequant_q8_0_transpose_len, dequant_q8_0_transpose_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3102 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q2_K], "dequant_q2_k", dequant_q2_k_len, dequant_q2_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); 3103 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q3_K], "dequant_q3_k", dequant_q3_k_len, dequant_q3_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); 3104 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_k", dequant_q4_k_len, dequant_q4_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3105 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_K], "dequant_q5_k", dequant_q5_k_len, dequant_q5_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); 3106 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q6_K], "dequant_q6_k", dequant_q6_k_len, dequant_q6_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); 3107 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_TQ1_0], "dequant_tq1_0", dequant_tq1_0_len, dequant_tq1_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1); 3108 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_TQ2_0], "dequant_tq2_0", dequant_tq2_0_len, dequant_tq2_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1); 3109 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_S], "dequant_iq1_s", dequant_iq1_s_len, dequant_iq1_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3110 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_M], "dequant_iq1_m", dequant_iq1_m_len, dequant_iq1_m_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3111 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XXS], "dequant_iq2_xxs", dequant_iq2_xxs_len, dequant_iq2_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3112 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XS], "dequant_iq2_xs", dequant_iq2_xs_len, dequant_iq2_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3113 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_S], "dequant_iq2_s", dequant_iq2_s_len, dequant_iq2_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3114 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_XXS], "dequant_iq3_xxs", dequant_iq3_xxs_len, dequant_iq3_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3115 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_S], "dequant_iq3_s", dequant_iq3_s_len, dequant_iq3_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3116 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_XS], "dequant_iq4_xs", dequant_iq4_xs_len, dequant_iq4_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1); 3117 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_NL], "dequant_iq4_nl", dequant_iq4_nl_len, dequant_iq4_nl_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3118 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3119 ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_NVFP4], "dequant_nvfp4", dequant_nvfp4_len, dequant_nvfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1); 3120 3121 // get_rows 3122 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F32 ], "get_rows_f32", get_rows_f32_len, get_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1); 3123 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F16 ], "get_rows_f16", get_rows_f16_len, get_rows_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1); 3124 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_BF16], "get_rows_bf16", get_rows_bf16_len, get_rows_bf16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1); 3125 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q1_0], "get_rows_q1_0", get_rows_q1_0_len, get_rows_q1_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3126 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_0], "get_rows_q2_0", get_rows_q2_0_len, get_rows_q2_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3127 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_0], "get_rows_q4_0", get_rows_q4_0_len, get_rows_q4_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3128 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_1], "get_rows_q4_1", get_rows_q4_1_len, get_rows_q4_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3129 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_0], "get_rows_q5_0", get_rows_q5_0_len, get_rows_q5_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3130 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_1], "get_rows_q5_1", get_rows_q5_1_len, get_rows_q5_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3131 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q8_0], "get_rows_q8_0", get_rows_q8_0_len, get_rows_q8_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3132 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_K], "get_rows_q2_k", get_rows_q2_k_len, get_rows_q2_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3133 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q3_K], "get_rows_q3_k", get_rows_q3_k_len, get_rows_q3_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3134 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_K], "get_rows_q4_k", get_rows_q4_k_len, get_rows_q4_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3135 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_K], "get_rows_q5_k", get_rows_q5_k_len, get_rows_q5_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3136 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q6_K], "get_rows_q6_k", get_rows_q6_k_len, get_rows_q6_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3137 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_TQ1_0], "get_rows_tq1_0", get_rows_tq1_0_len, get_rows_tq1_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3138 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_TQ2_0], "get_rows_tq2_0", get_rows_tq2_0_len, get_rows_tq2_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3139 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_S], "get_rows_iq1_s", get_rows_iq1_s_len, get_rows_iq1_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3140 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_M], "get_rows_iq1_m", get_rows_iq1_m_len, get_rows_iq1_m_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3141 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs", get_rows_iq2_xxs_len, get_rows_iq2_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3142 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs", get_rows_iq2_xs_len, get_rows_iq2_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3143 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_S], "get_rows_iq2_s", get_rows_iq2_s_len, get_rows_iq2_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3144 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs", get_rows_iq3_xxs_len, get_rows_iq3_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3145 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_S], "get_rows_iq3_s", get_rows_iq3_s_len, get_rows_iq3_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3146 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs", get_rows_iq4_xs_len, get_rows_iq4_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3147 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl", get_rows_iq4_nl_len, get_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3148 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3149 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_NVFP4], "get_rows_nvfp4", get_rows_nvfp4_len, get_rows_nvfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3150 ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_I32], "get_rows_i32", get_rows_i32_len, get_rows_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3151 3152 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f32_f32", get_rows_f32_f32_len, get_rows_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1); 3153 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F16 ], "get_rows_f16_f32", get_rows_f16_f32_len, get_rows_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1); 3154 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_BF16], "get_rows_bf16_f32", get_rows_bf16_f32_len, get_rows_bf16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1); 3155 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q1_0], "get_rows_q1_0_f32", get_rows_q1_0_f32_len, get_rows_q1_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3156 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q2_0], "get_rows_q2_0_f32", get_rows_q2_0_f32_len, get_rows_q2_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3157 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_0], "get_rows_q4_0_f32", get_rows_q4_0_f32_len, get_rows_q4_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3158 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_1], "get_rows_q4_1_f32", get_rows_q4_1_f32_len, get_rows_q4_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3159 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_0], "get_rows_q5_0_f32", get_rows_q5_0_f32_len, get_rows_q5_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3160 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_1], "get_rows_q5_1_f32", get_rows_q5_1_f32_len, get_rows_q5_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3161 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q8_0], "get_rows_q8_0_f32", get_rows_q8_0_f32_len, get_rows_q8_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3162 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q2_K], "get_rows_q2_k_f32", get_rows_q2_k_f32_len, get_rows_q2_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3163 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q3_K], "get_rows_q3_k_f32", get_rows_q3_k_f32_len, get_rows_q3_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3164 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_K], "get_rows_q4_k_f32", get_rows_q4_k_f32_len, get_rows_q4_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3165 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_K], "get_rows_q5_k_f32", get_rows_q5_k_f32_len, get_rows_q5_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3166 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q6_K], "get_rows_q6_k_f32", get_rows_q6_k_f32_len, get_rows_q6_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3167 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_TQ1_0], "get_rows_tq1_0_f32", get_rows_tq1_0_f32_len, get_rows_tq1_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3168 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_TQ2_0], "get_rows_tq2_0_f32", get_rows_tq2_0_f32_len, get_rows_tq2_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3169 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_S], "get_rows_iq1_s_f32", get_rows_iq1_s_f32_len, get_rows_iq1_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3170 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_M], "get_rows_iq1_m_f32", get_rows_iq1_m_f32_len, get_rows_iq1_m_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3171 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs_f32", get_rows_iq2_xxs_f32_len, get_rows_iq2_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3172 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs_f32", get_rows_iq2_xs_f32_len, get_rows_iq2_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3173 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_S], "get_rows_iq2_s_f32", get_rows_iq2_s_f32_len, get_rows_iq2_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3174 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs_f32", get_rows_iq3_xxs_f32_len, get_rows_iq3_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3175 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_S], "get_rows_iq3_s_f32", get_rows_iq3_s_f32_len, get_rows_iq3_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3176 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs_f32", get_rows_iq4_xs_f32_len, get_rows_iq4_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3177 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl_f32", get_rows_iq4_nl_f32_len, get_rows_iq4_nl_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3178 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_MXFP4], "get_rows_mxfp4_f32", get_rows_mxfp4_f32_len, get_rows_mxfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3179 ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_NVFP4], "get_rows_nvfp4_f32", get_rows_nvfp4_f32_len, get_rows_nvfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1); 3180 ggml_vk_create_pipeline(device, device->pipeline_get_rows_back_f32, "get_rows_back_f32", get_rows_back_f32_len, get_rows_back_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {256, 1, 1}, {}, 1, true); 3181 3182 ggml_vk_create_pipeline(device, device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1); 3183 ggml_vk_create_pipeline(device, device->pipeline_flash_attn_split_k_reduce, "fa_split_k_reduce", fa_split_k_reduce_len, fa_split_k_reduce_data, "main", 3, sizeof(vk_op_flash_attn_split_k_reduce_push_constants), {1, device->subgroup_size, 1}, {device->subgroup_size}, 1, true); 3184 3185 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 3186 if (device->vendor_id == VK_VENDOR_ID_INTEL && (device->architecture == INTEL_XE2 || (device->architecture == INTEL_XE1 && device->coopmat_support && device->uma))) { 3187 auto upper_power_of_2 = [&](uint32_t in) { 3188 GGML_ASSERT(in != 0); 3189 if (in <= 1) return 1u; 3190 uint32_t ret = in - 1; 3191 ret |= ret >> 1; 3192 ret |= ret >> 2; 3193 ret |= ret >> 4; 3194 ret |= ret >> 8; 3195 ret |= ret >> 16; 3196 return ret + 1; 3197 }; 3198 3199 uint32_t xe_native_sub_group_size = 16; 3200 if (device->architecture == INTEL_XE1) { 3201 xe_native_sub_group_size = 8; 3202 } 3203 3204 for (auto& it : device->pipeline_xe_fa_decode_dual_phases) { 3205 const uint32_t split_p_chunk = 32; 3206 auto HdQk = it.first; 3207 auto& pipelines = it.second; 3208 uint32_t head_dim_qk = std::get<0>(HdQk); 3209 uint32_t head_dim_pv = std::get<1>(HdQk); 3210 uint32_t gqa_ratio = std::get<2>(HdQk); 3211 uint32_t q_len = std::get<3>(HdQk); 3212 const uint32_t out_dim_per_wg = gqa_ratio > 16 ? 8 : 16; 3213 uint32_t aligned_q_len = upper_power_of_2(q_len); 3214 uint32_t group_sz_ph1 = std::min(std::max(aligned_q_len * xe_native_sub_group_size, 64u), 256u); 3215 uint32_t out_per_wg_ph1 = std::min(q_len, 256u / xe_native_sub_group_size); 3216 uint32_t aligned_gqa_ratio = upper_power_of_2(gqa_ratio); 3217 uint32_t split_p_per_iter_ph2 = 256; 3218 uint32_t split_p_per_warp = 16; 3219 uint32_t group_sz_ph2 = (split_p_per_iter_ph2 / split_p_per_warp) * xe_native_sub_group_size; 3220 uint32_t out_per_wg_ph2 = std::min(std::max(16u / aligned_gqa_ratio, 1u), q_len); 3221 ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1", fa_decode_ph1_cm1_len, fa_decode_ph1_cm1_data, "main", 5, sizeof(vk_fa_xe_opt_push_constants), { 1, 32, 1 }, { group_sz_ph1, gqa_ratio, head_dim_qk, xe_native_sub_group_size, split_p_chunk, out_per_wg_ph1 }, 1, false, true, xe_native_sub_group_size); 3222 ggml_vk_create_pipeline(device, pipelines.second, "xe_fa_decode_ph2", fa_decode_ph2_cm1_len, fa_decode_ph2_cm1_data, "main", 5, sizeof(vk_fa_xe_opt_push_constants), { 1, 1, 1 }, { group_sz_ph2, gqa_ratio, head_dim_pv, out_per_wg_ph2, xe_native_sub_group_size, split_p_per_iter_ph2, split_p_chunk, out_dim_per_wg }, 1, false, true, xe_native_sub_group_size); 3223 } 3224 } 3225 #endif 3226 3227 for (auto &it : device->pipeline_fa_mask_opt) { 3228 auto BrBc = it.first; 3229 ggml_vk_create_pipeline(device, it.second, "fa_mask_opt", fa_mask_opt_len, fa_mask_opt_data, "main", 2, sizeof(vk_op_flash_attn_mask_opt_push_constants), {1, 1, 1}, {128, 128 / device->subgroup_size, BrBc.first, BrBc.second}, 1, true, true, device->subgroup_size); 3230 } 3231 3232 { 3233 // Large workgroup so the per-row KV scan parallelizes; capped to device limits. 3234 const uint32_t compact_max = std::min({1024u, device->properties.limits.maxComputeWorkGroupInvocations, device->properties.limits.maxComputeWorkGroupSize[0]}); 3235 3236 // Fast ballot prefix-sum path when the device supports full subgroups; otherwise 3237 // a shared-memory prefix-sum fallback. Both emit a deterministic ascending list. 3238 device->fa_sparse_compact_use_subgroups = device->subgroup_ballot && device->subgroup_require_full_support; 3239 if (device->fa_sparse_compact_use_subgroups) { 3240 const uint32_t compact_wg = std::max(device->subgroup_size, (compact_max / device->subgroup_size) * device->subgroup_size); 3241 const uint32_t compact_num_sg = compact_wg / device->subgroup_size; 3242 ggml_vk_create_pipeline(device, device->pipeline_fa_sparse_compact_subgroup, "fa_sparse_compact_subgroup", fa_sparse_compact_subgroup_len, fa_sparse_compact_subgroup_data, "main", 2, sizeof(vk_op_flash_attn_sparse_compact_push_constants), {1, 1, 1}, {compact_wg, compact_num_sg}, 1, true, true, device->subgroup_size); 3243 } else { 3244 ggml_vk_create_pipeline(device, device->pipeline_fa_sparse_compact, "fa_sparse_compact", fa_sparse_compact_len, fa_sparse_compact_data, "main", 2, sizeof(vk_op_flash_attn_sparse_compact_push_constants), {1, 1, 1}, {compact_max}, 1, true); 3245 } 3246 } 3247 3248 if (device->subgroup_clustered && device->subgroup_require_full_support) { 3249 ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, sizeof(vk_quantize_q8_1_push_constants), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true); 3250 } else { 3251 ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_len, quantize_q8_1_x4_data, "main", 2, sizeof(vk_quantize_q8_1_push_constants), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1); 3252 } 3253 3254 for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) { 3255 if (device->subgroup_arithmetic && device->subgroup_require_full_support) { 3256 ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true); 3257 } else { 3258 ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true); 3259 } 3260 } 3261 ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_nc_push_constants), {1, 1, 1}, {}, 1); 3262 3263 ggml_vk_create_pipeline(device, device->pipeline_norm_f32, "norm_f32", norm_f32_len, norm_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); 3264 ggml_vk_create_pipeline(device, device->pipeline_group_norm_f32, "group_norm_f32", group_norm_f32_len, group_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1); 3265 3266 const bool rms_subgroups = (device->vendor_id == VK_VENDOR_ID_INTEL || device->vendor_id == VK_VENDOR_ID_NVIDIA || device->vendor_id == VK_VENDOR_ID_AMD) && device->subgroup_arithmetic && device->subgroup_require_full_support; 3267 const uint32_t rms_set_rows_block_size = 128; 3268 #define RMS_SHADER(name) (rms_subgroups ? name##_subgroup_len : name##_len), (rms_subgroups ? name##_subgroup_data : name##_data) 3269 // 128/256/512 block sizes, picked by row length 3270 for (uint32_t i = 0; i < 3; ++i) { 3271 const uint32_t block_size = 128u << i; 3272 const std::string suffix = "_" + std::to_string(block_size); 3273 ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_f32[i], "rms_norm_f32" + suffix, RMS_SHADER(rms_norm_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, block_size}, 1, true, rms_subgroups); 3274 ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_mul_f32[i], "rms_norm_mul_f32" + suffix, RMS_SHADER(rms_norm_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 0, block_size}, 1, true, rms_subgroups); 3275 ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_mul_add_f32[i], "rms_norm_mul_add_f32" + suffix, RMS_SHADER(rms_norm_mul_add_f32), "main", 5, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 0, block_size}, 1, true, rms_subgroups); 3276 ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_mul_add_mul_f32[i], "rms_norm_mul_add_mul_f32" + suffix, RMS_SHADER(rms_norm_mul_add_f32), "main", 5, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 1, block_size}, 1, true, rms_subgroups); 3277 } 3278 ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_add_partials_f32, "rms_norm_mul_add_partials_f32", rms_norm_mul_add_partials_f32_len, rms_norm_mul_add_partials_f32_data, "main", 6, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 0}, 1, true); 3279 ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_add_mul_partials_f32, "rms_norm_mul_add_mul_partials_f32", rms_norm_mul_add_partials_f32_len, rms_norm_mul_add_partials_f32_data, "main", 6, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1, 1}, 1, true); 3280 ggml_vk_create_pipeline(device, device->pipeline_rms_norm_set_rows_f32_f32, "rms_norm_set_rows_f32_f32", RMS_SHADER(rms_norm_set_rows_f32_f32), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, rms_set_rows_block_size}, 1, true, rms_subgroups); 3281 ggml_vk_create_pipeline(device, device->pipeline_rms_norm_set_rows_f32_f16, "rms_norm_set_rows_f32_f16", RMS_SHADER(rms_norm_set_rows_f32_f16), "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0, 0, rms_set_rows_block_size}, 1, true, rms_subgroups); 3282 ggml_vk_create_pipeline(device, device->pipeline_rms_norm_partials_f32, "rms_norm_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true); 3283 ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_partials_f32, "rms_norm_mul_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true); 3284 3285 if (sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) { 3286 for (uint32_t i = 0; i < 3; ++i) { 3287 const uint32_t block_size = 128u << i; 3288 const std::string suffix = "_" + std::to_string(block_size); 3289 ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_mul_rope_f32_f32[i], "rms_norm_mul_rope_f32_f32" + suffix, RMS_SHADER(rms_norm_mul_rope_f32_f32), "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1, 0, block_size}, 1, true, rms_subgroups); 3290 ggml_vk_create_pipeline2(device, device->pipeline_rms_norm_mul_rope_f32_f16[i], "rms_norm_mul_rope_f32_f16" + suffix, RMS_SHADER(rms_norm_mul_rope_f32_f16), "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1, 0, block_size}, 1, true, rms_subgroups); 3291 } 3292 } 3293 #undef RMS_SHADER 3294 3295 ggml_vk_create_pipeline(device, device->pipeline_rms_norm_back_f32, "rms_norm_back_f32", rms_norm_back_f32_len, rms_norm_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1); 3296 ggml_vk_create_pipeline(device, device->pipeline_l2_norm_f32, "l2_norm_f32", l2_norm_f32_len, l2_norm_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); 3297 3298 ggml_vk_create_pipeline(device, device->pipeline_cpy_32, "cpy_32", cpy_32_len, cpy_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3299 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f16, "cpy_f32_f16", cpy_f32_f16_len, cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3300 ggml_vk_create_pipeline(device, device->pipeline_cpy_16, "cpy_16", cpy_16_len, cpy_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3301 ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f32, "cpy_f16_f32", cpy_f16_f32_len, cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3302 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3303 ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f32,"cpy_bf16_f32",cpy_bf16_f32_len,cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3304 ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f16,"cpy_bf16_f16",cpy_bf16_f16_len,cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3305 ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3306 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3307 3308 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_32, "contig_cpy_32", contig_cpy_32_len, contig_cpy_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3309 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f16, "contig_cpy_f32_f16", contig_cpy_f32_f16_len, contig_cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3310 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_16, "contig_cpy_16", contig_cpy_16_len, contig_cpy_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3311 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f32, "contig_cpy_f16_f32", contig_cpy_f16_f32_len, contig_cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3312 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3313 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f32,"contig_cpy_bf16_f32",contig_cpy_bf16_f32_len,contig_cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3314 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f16,"contig_cpy_bf16_f16",contig_cpy_bf16_f16_len,contig_cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3315 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3316 ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3317 3318 ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_32, "cpy_transpose_32", cpy_transpose_32_len, cpy_transpose_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); 3319 ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_16, "cpy_transpose_16", cpy_transpose_16_len, cpy_transpose_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); 3320 ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_02_32, "cpy_transpose_02_32", cpy_transpose_02_32_len, cpy_transpose_02_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); 3321 ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_02_16, "cpy_transpose_02_16", cpy_transpose_02_16_len, cpy_transpose_02_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1); 3322 3323 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q1_0], "cpy_f32_q1_0", cpy_f32_q1_0_len, cpy_f32_q1_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3324 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q2_0], "cpy_f32_q2_0", cpy_f32_q2_0_len, cpy_f32_q2_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3325 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_len, cpy_f32_q4_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3326 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_len, cpy_f32_q4_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3327 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_len, cpy_f32_q5_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3328 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_len, cpy_f32_q5_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3329 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_len, cpy_f32_q8_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3330 ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_len, cpy_f32_iq4_nl_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1); 3331 3332 #define SET_ROWS(src_idx, src, itype) \ 3333 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_F32], "set_rows_" #src "_f32" #itype, set_rows_ ## src ## _f32 ## itype ## _len, set_rows_ ## src ## _f32 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3334 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_F16], "set_rows_" #src "_f16" #itype, set_rows_ ## src ## _f16 ## itype ## _len, set_rows_ ## src ## _f16 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3335 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_BF16], "set_rows_" #src "_bf16" #itype, set_rows_ ## src ## _bf16 ## itype ## _len, set_rows_ ## src ## _bf16 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3336 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_Q1_0], "set_rows_" #src "_q1_0" #itype, set_rows_ ## src ## _q1_0 ## itype ## _len, set_rows_ ## src ## _q1_0 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3337 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_Q2_0], "set_rows_" #src "_q2_0" #itype, set_rows_ ## src ## _q2_0 ## itype ## _len, set_rows_ ## src ## _q2_0 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3338 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_Q4_0], "set_rows_" #src "_q4_0" #itype, set_rows_ ## src ## _q4_0 ## itype ## _len, set_rows_ ## src ## _q4_0 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3339 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_Q4_1], "set_rows_" #src "_q4_1" #itype, set_rows_ ## src ## _q4_1 ## itype ## _len, set_rows_ ## src ## _q4_1 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3340 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_Q5_0], "set_rows_" #src "_q5_0" #itype, set_rows_ ## src ## _q5_0 ## itype ## _len, set_rows_ ## src ## _q5_0 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3341 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_Q5_1], "set_rows_" #src "_q5_1" #itype, set_rows_ ## src ## _q5_1 ## itype ## _len, set_rows_ ## src ## _q5_1 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3342 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_Q8_0], "set_rows_" #src "_q8_0" #itype, set_rows_ ## src ## _q8_0 ## itype ## _len, set_rows_ ## src ## _q8_0 ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \ 3343 ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [src_idx][GGML_TYPE_IQ4_NL], "set_rows_" #src "_iq4_nl" #itype, set_rows_ ## src ## _iq4_nl ## itype ## _len, set_rows_ ## src ## _iq4_nl ## itype ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); 3344 3345 SET_ROWS(0, f32, _i32) 3346 SET_ROWS(0, f32, _i64) 3347 SET_ROWS(1, f16, _i32) 3348 SET_ROWS(1, f16, _i64) 3349 #undef SET_ROWS 3350 3351 3352 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q1_0], "cpy_q1_0_f32", cpy_q1_0_f32_len, cpy_q1_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q1_0), 1, 1}, {}, 1); 3353 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q2_0], "cpy_q2_0_f32", cpy_q2_0_f32_len, cpy_q2_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q2_0), 1, 1}, {}, 1); 3354 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_0], "cpy_q4_0_f32", cpy_q4_0_f32_len, cpy_q4_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_0), 1, 1}, {}, 1); 3355 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_1], "cpy_q4_1_f32", cpy_q4_1_f32_len, cpy_q4_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_1), 1, 1}, {}, 1); 3356 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_0], "cpy_q5_0_f32", cpy_q5_0_f32_len, cpy_q5_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_0), 1, 1}, {}, 1); 3357 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_1], "cpy_q5_1_f32", cpy_q5_1_f32_len, cpy_q5_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_1), 1, 1}, {}, 1); 3358 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q8_0], "cpy_q8_0_f32", cpy_q8_0_f32_len, cpy_q8_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q8_0), 1, 1}, {}, 1); 3359 ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_IQ4_NL], "cpy_iq4_nl_f32", cpy_iq4_nl_f32_len, cpy_iq4_nl_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_IQ4_NL), 1, 1}, {}, 1); 3360 3361 auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) { 3362 std::string s; 3363 s += std::string(src0_f16 ? "_f16" : "_f32"); 3364 s += std::string(src1_f16 ? "_f16" : "_f32"); 3365 s += std::string(dst_f16 ? "_f16" : "_f32"); 3366 return s; 3367 }; 3368 3369 #define CREATE_BINARY(name, namemod, spec, bindings) \ 3370 for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \ 3371 ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \ 3372 #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d], name ## _data[s0][s1][d], \ 3373 "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1); 3374 3375 CREATE_BINARY(add, , {0}, 4) 3376 CREATE_BINARY(add, _norepeat, {1}, 4) 3377 CREATE_BINARY(sub, , {0}, 3) 3378 CREATE_BINARY(sub, _norepeat, {1}, 3) 3379 CREATE_BINARY(mul, , {0}, 3) 3380 CREATE_BINARY(mul, _norepeat, {1}, 3) 3381 CREATE_BINARY(div, , {0}, 3) 3382 CREATE_BINARY(div, _norepeat, {1}, 3) 3383 CREATE_BINARY(add_rms, , {0}, 4) 3384 CREATE_BINARY(add_rms, _norepeat, {1}, 4) 3385 #undef CREATE_BINARY 3386 3387 if (device->multi_add) { 3388 for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) { 3389 ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1); 3390 ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1); 3391 } 3392 } 3393 3394 ggml_vk_create_pipeline(device, device->pipeline_add_id_f32, "add_id_f32", add_id_f32_len, add_id_f32_data, "main", 4, sizeof(vk_op_add_id_push_constants), {1, 1, 1}, {}, 1); 3395 3396 ggml_vk_create_pipeline(device, device->pipeline_acc_f32, "acc_f32", acc_f32_len, acc_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0, 1}, 1); 3397 ggml_vk_create_pipeline(device, device->pipeline_set_f32, "set_f32", acc_f32_len, acc_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0, 0}, 1); 3398 3399 ggml_vk_create_pipeline(device, device->pipeline_concat_i8, "concat_i8", concat_i8_len, concat_i8_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); 3400 ggml_vk_create_pipeline(device, device->pipeline_concat_i16, "concat_i16", concat_i16_len, concat_i16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); 3401 ggml_vk_create_pipeline(device, device->pipeline_concat_i32, "concat_i32", concat_i32_len, concat_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); 3402 ggml_vk_create_pipeline(device, device->pipeline_concat_i64, "concat_i64", concat_i64_len, concat_i64_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); 3403 3404 ggml_vk_create_pipeline(device, device->pipeline_upscale_nearest_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_NEAREST}, 1); 3405 ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR}, 1); 3406 ggml_vk_create_pipeline(device, device->pipeline_upscale_bicubic_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BICUBIC}, 1); 3407 ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_antialias_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS}, 1); 3408 3409 ggml_vk_create_pipeline(device, device->pipeline_scale_f32, "scale_f32", scale_f32_len, scale_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3410 3411 ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32", log_f32_len, log_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3412 ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16", log_f16_len, log_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3413 3414 ggml_vk_create_pipeline(device, device->pipeline_tri[0], "tri_f32", tri_f32_len, tri_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3415 ggml_vk_create_pipeline(device, device->pipeline_tri[1], "tri_f16", tri_f16_len, tri_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3416 3417 ggml_vk_create_pipeline(device, device->pipeline_diag[0], "diag_f32", diag_f32_len, diag_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3418 ggml_vk_create_pipeline(device, device->pipeline_diag[1], "diag_f16", diag_f16_len, diag_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3419 3420 ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1); 3421 ggml_vk_create_pipeline(device, device->pipeline_pad_reflect_1d_f32, "pad_reflect_1d_f32", pad_reflect_1d_f32_len, pad_reflect_1d_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3422 3423 ggml_vk_create_pipeline(device, device->pipeline_roll_f32, "roll_f32", roll_f32_len, roll_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3424 3425 ggml_vk_create_pipeline(device, device->pipeline_repeat_i32, "repeat_i32", repeat_i32_len, repeat_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3426 ggml_vk_create_pipeline(device, device->pipeline_repeat_back_f32, "repeat_back_f32", repeat_back_f32_len, repeat_back_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3427 3428 ggml_vk_create_pipeline(device, device->pipeline_repeat_i16, "repeat_i16", repeat_i16_len, repeat_i16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3429 3430 #define CREATE_UNARY(name) \ 3431 ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); \ 3432 ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1); 3433 3434 CREATE_UNARY(elu) 3435 CREATE_UNARY(gelu) 3436 CREATE_UNARY(gelu_erf) 3437 CREATE_UNARY(gelu_quick) 3438 CREATE_UNARY(silu) 3439 CREATE_UNARY(relu) 3440 CREATE_UNARY(sqr) 3441 CREATE_UNARY(sqrt) 3442 CREATE_UNARY(sin) 3443 CREATE_UNARY(cos) 3444 CREATE_UNARY(clamp) 3445 CREATE_UNARY(leaky_relu) 3446 CREATE_UNARY(xielu) 3447 CREATE_UNARY(neg) 3448 CREATE_UNARY(tanh) 3449 CREATE_UNARY(sigmoid) 3450 CREATE_UNARY(hardsigmoid) 3451 CREATE_UNARY(hardswish) 3452 CREATE_UNARY(abs) 3453 CREATE_UNARY(softplus) 3454 CREATE_UNARY(step) 3455 CREATE_UNARY(round) 3456 CREATE_UNARY(ceil) 3457 CREATE_UNARY(floor) 3458 CREATE_UNARY(trunc) 3459 CREATE_UNARY(sgn) 3460 CREATE_UNARY(exp) 3461 CREATE_UNARY(expm1) 3462 #undef CREATE_UNARY 3463 3464 // spec constants: {norepeat, op_on_b} 3465 #define CREATE_UNARY_MUL(name, idx) \ 3466 for (int dt = 0; dt < 2; ++dt) { \ 3467 const size_t len_ = dt ? name ## _mul_f16_len : name ## _mul_f32_len; \ 3468 const unsigned char * data_ = dt ? name ## _mul_f16_data : name ## _mul_f32_data; \ 3469 const std::string dts_ = dt ? "f16" : "f32"; \ 3470 for (int ob = 0; ob < 2; ++ob) \ 3471 for (int nr = 0; nr < 2; ++nr) \ 3472 ggml_vk_create_pipeline(device, device->pipeline_unary_mul[(idx)][dt][nr][ob], \ 3473 (#name "_mul" + std::string(ob ? "_b" : "") + "_" + dts_ + (nr ? "_norepeat" : "")).c_str(), \ 3474 len_, data_, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, \ 3475 { (uint32_t) nr, (uint32_t) ob }, 1); \ 3476 } 3477 3478 CREATE_UNARY_MUL(gelu, 0) 3479 CREATE_UNARY_MUL(sigmoid, 1) 3480 CREATE_UNARY_MUL(silu, 2) 3481 CREATE_UNARY_MUL(softplus, 3) 3482 #undef CREATE_UNARY_MUL 3483 3484 ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f16, "add1_f16_f16", add1_f16_f16_len, add1_f16_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); 3485 ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f32, "add1_f16_f32", add1_f16_f32_len, add1_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); 3486 ggml_vk_create_pipeline(device, device->pipeline_add1_f32_f32, "add1_f32_f32", add1_f32_f32_len, add1_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); 3487 3488 ggml_vk_create_pipeline(device, device->pipeline_arange_f32, "arange_f32", arange_f32_len, arange_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); 3489 3490 ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); 3491 ggml_vk_create_pipeline(device, device->pipeline_fill_f16, "fill_f16", fill_f16_len, fill_f16_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); 3492 3493 #define CREATE_GLU(name) \ 3494 ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \ 3495 ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); 3496 3497 CREATE_GLU(geglu) 3498 CREATE_GLU(reglu) 3499 CREATE_GLU(swiglu) 3500 CREATE_GLU(swiglu_oai) 3501 CREATE_GLU(swiglu_clamp) 3502 CREATE_GLU(geglu_erf) 3503 CREATE_GLU(geglu_quick) 3504 #undef CREATE_GLU 3505 3506 ggml_vk_create_pipeline(device, device->pipeline_silu_back_f32, "silu_back_f32", silu_back_f32_len, silu_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); 3507 3508 ggml_vk_create_pipeline(device, device->pipeline_diag_mask_inf_f32, "diag_mask_inf_f32", diag_mask_inf_f32_len, diag_mask_inf_f32_data, "main", 2, sizeof(vk_op_diag_mask_push_constants), {1, 512, 1}, {}, 1, true); 3509 3510 ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); 3511 ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1); 3512 ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); 3513 ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1); 3514 ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true); 3515 3516 ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32, "soft_max_large1_f32", soft_max_large1_f32_len, soft_max_large1_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); 3517 ggml_vk_create_pipeline(device, device->pipeline_soft_max_large2_f32, "soft_max_large2_f32", soft_max_large2_f32_len, soft_max_large2_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); 3518 ggml_vk_create_pipeline(device, device->pipeline_soft_max_large3_f32, "soft_max_large3_f32", soft_max_large3_f32_len, soft_max_large3_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); 3519 ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32_f16, "soft_max_large1_f32_f16", soft_max_large1_f32_f16_len, soft_max_large1_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); 3520 ggml_vk_create_pipeline(device, device->pipeline_soft_max_large2_f32_f16, "soft_max_large2_f32_f16", soft_max_large2_f32_f16_len, soft_max_large2_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); 3521 ggml_vk_create_pipeline(device, device->pipeline_soft_max_large3_f32_f16, "soft_max_large3_f32_f16", soft_max_large3_f32_f16_len, soft_max_large3_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); 3522 3523 ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3524 ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3525 ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32, "rope_multi_f32", rope_multi_f32_len, rope_multi_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3526 ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f32, "rope_vision_f32", rope_vision_f32_len, rope_vision_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3527 3528 ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3529 ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3530 ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_len, rope_multi_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3531 ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_len, rope_vision_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3532 3533 ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_len, rope_norm_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3534 ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_len, rope_neox_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3535 ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32_f16, "rope_multi_f32_f16", rope_multi_f32_f16_len, rope_multi_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1); 3536 3537 for (uint32_t i = 0; i < num_argsort_pipelines; ++i) { 3538 uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2); 3539 if (i <= device->max_workgroup_size_log2 && 3540 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) { 3541 const uint32_t NCOLS_PADDED_LOG2 = i; 3542 ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, NCOLS_PADDED_LOG2}, 1, true); 3543 } 3544 const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1; 3545 BLOCK_SIZE /= WG_UNROLL_FACTOR; 3546 ggml_vk_create_pipeline2(device, device->pipeline_argsort_large_f32[i], "argsort_large_f32_"+std::to_string(i), argsort_large_f32_len, argsort_large_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE * WG_UNROLL_FACTOR, 1, 1}, {BLOCK_SIZE, WG_UNROLL_FACTOR}, 1, true); 3547 } 3548 3549 for (uint32_t i = 0; i < num_topk_pipelines; ++i) { 3550 const uint32_t BLOCK_SIZE = 1u << i; 3551 const uint32_t NCOLS_PADDED_LOG2 = i; 3552 if (i <= device->max_workgroup_size_log2) { 3553 uint32_t nary_shmem = 2 * sizeof(int) * BLOCK_SIZE + 3554 sizeof(int) * device->subgroup_size + 3555 2 * sizeof(int) + 3556 2 * (BLOCK_SIZE / device->subgroup_size) * sizeof(int); 3557 if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_shuffle && device->subgroup_ballot && 3558 nary_shmem <= device->properties.limits.maxComputeSharedMemorySize) { 3559 ggml_vk_create_pipeline2(device, device->pipeline_topk_f32[i], "topk_f32_"+std::to_string(i), topk_nary_search_f32_len, topk_nary_search_f32_data, "main", 2, sizeof(vk_op_topk_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, device->subgroup_size, device->subgroup_size_log2}, 1, true, true, device->subgroup_size); 3560 } else if (2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) { 3561 ggml_vk_create_pipeline2(device, device->pipeline_topk_f32[i], "topk_f32_"+std::to_string(i), topk_argsort_f32_len, topk_argsort_f32_data, "main", 2, sizeof(vk_op_topk_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, NCOLS_PADDED_LOG2}, 1, true); 3562 } 3563 } 3564 } 3565 3566 // large-k fallback: one workgroup per row, radix-select instead of a full sort. The QSA 3567 // variant (spec constant 1) additionally gathers the qwen4 indexer input on the fly. 3568 { 3569 const uint32_t BLOCK_SIZE = 1u << std::min(10u, device->max_workgroup_size_log2); 3570 ggml_vk_create_pipeline2(device, device->pipeline_topk_radix_f32, "topk_radix_f32", topk_radix_select_f32_len, topk_radix_select_f32_data, "main", 5, sizeof(vk_op_topk_radix_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, 0}, 1, true); 3571 ggml_vk_create_pipeline2(device, device->pipeline_topk_radix_qsa, "topk_radix_qsa", topk_radix_select_f32_len, topk_radix_select_f32_data, "main", 5, sizeof(vk_op_topk_radix_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, 1}, 1, true); 3572 } 3573 3574 ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); 3575 3576 ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); 3577 ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32, "cross_entropy_loss_f32", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); 3578 ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32_wg512, "cross_entropy_loss_f32_wg512", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { 512 }, 1); 3579 ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_back_f32, "cross_entropy_loss_back_f32", cross_entropy_loss_back_f32_len, cross_entropy_loss_back_f32_data, "main", 4, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); 3580 ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_back_f32_wg512, "cross_entropy_loss_back_f32_wg512", cross_entropy_loss_back_f32_len, cross_entropy_loss_back_f32_data, "main", 4, sizeof(vk_op_push_constants), {1, 1, 1}, { 512 }, 1); 3581 // Intel Windows driver in range [32.0.101.8509, 32.0.101.8860) will crash when using fwht kernels so we gate that here 3582 const bool can_use_fwht = device->driver_id != vk::DriverId::eIntelProprietaryWindows || 3583 !ggml_vk_intel_windows_driver_in_range(device->properties.driverVersion, 101, 8509, 101, 8860); 3584 if (can_use_fwht && device->subgroup_basic && device->subgroup_shuffle) { 3585 int idx = 0; 3586 for (uint32_t n : {64, 128, 256, 512}) { 3587 if (device->subgroup_size <= n) { 3588 ggml_vk_create_pipeline(device, device->pipeline_fwht_f32[idx], "fwht_f32", fwht_f32_len, fwht_f32_data, "main", 2, sizeof(vk_op_fwht_push_constants), {1, 1, 1}, { device->subgroup_size, n }, 1, true, true, device->subgroup_size); 3589 } 3590 ++idx; 3591 } 3592 } else if (can_use_fwht) { 3593 int idx = 0; 3594 for (uint32_t n : {64, 128, 256, 512}) { 3595 const uint32_t block_size = std::min(device->subgroup_size, n); 3596 ggml_vk_create_pipeline(device, device->pipeline_fwht_f32[idx], "fwht_shmem_f32", fwht_shmem_f32_len, fwht_shmem_f32_data, "main", 2, sizeof(vk_op_fwht_push_constants), {1, 1, 1}, { block_size, n }, 1); 3597 ++idx; 3598 } 3599 } 3600 3601 const uint32_t cumsum_elem_per_thread = (device->vendor_id == VK_VENDOR_ID_AMD || device->vendor_id == VK_VENDOR_ID_INTEL) ? 2 : 4; 3602 ggml_vk_create_pipeline(device, device->pipeline_cumsum_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 256, device->subgroup_size, cumsum_elem_per_thread }, 1, true, true, device->subgroup_size); 3603 ggml_vk_create_pipeline(device, device->pipeline_cumsum_small_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 128, device->subgroup_size, 1 }, 1, true, true, device->subgroup_size); 3604 ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass1_f32, "cumsum_multipass1_f32", cumsum_multipass1_f32_len, cumsum_multipass1_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size); 3605 ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass2_f32, "cumsum_multipass2_f32", cumsum_multipass2_f32_len, cumsum_multipass2_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size); 3606 3607 ggml_vk_create_pipeline(device, device->pipeline_count_equal_i32, "count_equal_i32", count_equal_i32_len, count_equal_i32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, { device->subgroup_size }, 1); 3608 3609 if (device->subgroup_arithmetic && device->subgroup_vote && device->subgroup_require_full_support) { 3610 ggml_vk_create_pipeline(device, device->pipeline_count_experts, "count_experts", count_experts_subgroup_len, count_experts_subgroup_data, "main", 3, sizeof(vk_op_count_experts_push_constants), {1, 1, 1}, {}, 1, true, true); 3611 } else { 3612 ggml_vk_create_pipeline(device, device->pipeline_count_experts, "count_experts", count_experts_len, count_experts_data, "main", 3, sizeof(vk_op_count_experts_push_constants), {1, 1, 1}, {}, 1, true); 3613 } 3614 3615 // comb holds a token's 4x4 matrix in one 16-lane slice of a subgroup, so it 3616 // needs at least 16 lanes, pinned to a known size. 3617 if (device->subgroup_basic && device->subgroup_shuffle && device->subgroup_require_full_support && device->subgroup_size >= 16) { 3618 const uint32_t tokens_per_workgroup = 4 * (device->subgroup_size / 16); 3619 ggml_vk_create_pipeline(device, device->pipeline_dsv4_hc_comb_f32, "dsv4_hc_comb_f32", dsv4_hc_comb_f32_len, dsv4_hc_comb_f32_data, "main", 4, sizeof(vk_op_dsv4_hc_comb_push_constants), {tokens_per_workgroup, 1, 1}, { device->subgroup_size }, 1, true, true, device->subgroup_size); 3620 } 3621 3622 ggml_vk_create_pipeline(device, device->pipeline_dsv4_hc_pre_f32, "dsv4_hc_pre_f32", dsv4_hc_pre_f32_len, dsv4_hc_pre_f32_data, "main", 3, sizeof(vk_op_dsv4_hc_pre_push_constants), {256, 1, 1}, { 256, 0 }, 1); 3623 ggml_vk_create_pipeline(device, device->pipeline_dsv4_hc_pre_gated_f32, "dsv4_hc_pre_gated_f32", dsv4_hc_pre_f32_len, dsv4_hc_pre_f32_data, "main", 3, sizeof(vk_op_dsv4_hc_pre_push_constants), {256, 1, 1}, { 256, 1 }, 1); 3624 ggml_vk_create_pipeline(device, device->pipeline_dsv4_hc_post_f32, "dsv4_hc_post_f32", dsv4_hc_post_f32_len, dsv4_hc_post_f32_data, "main", 5, sizeof(vk_op_dsv4_hc_post_push_constants), {256, 1, 1}, { 256, 1 }, 1); 3625 ggml_vk_create_pipeline(device, device->pipeline_dsv4_hc_post_nocomb_f32,"dsv4_hc_post_nocomb_f32",dsv4_hc_post_f32_len, dsv4_hc_post_f32_data, "main", 5, sizeof(vk_op_dsv4_hc_post_push_constants), {256, 1, 1}, { 256, 0 }, 1); 3626 3627 for (auto &s : device->pipeline_solve_tri_f32) { 3628 const vk_solve_tri_pipeline_state &state = s.first; 3629 3630 // Max number of rows to load at a time, limited by shared memory 3631 const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((state.N + state.K) * sizeof(float)); 3632 // Need at least K invocations, and prefer a minimum of 128 to spread out loading shared memory 3633 const uint32_t block_size = std::max(128u, 1u << (uint32_t)ceilf(log2f(float(state.K)))); 3634 3635 ggml_vk_create_pipeline( 3636 device, s.second, "solve_tri_f32", 3637 solve_tri_f32_len, solve_tri_f32_data, "main", 3, 3638 sizeof(vk_op_binary_push_constants), {1, 1, 1}, { 0, state.N, state.K, batch_N, block_size }, 1, true); 3639 } 3640 3641 #define IM2COL(bda) \ 3642 ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32 ## bda ## _len, im2col_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \ 3643 ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32, "im2col_3d_f32", im2col_3d_f32 ## bda ## _len, im2col_3d_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \ 3644 ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16 ## bda ## _len, im2col_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \ 3645 ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16 ## bda ## _len, im2col_3d_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); 3646 if (device->shader_int64 && device->buffer_device_address) { 3647 IM2COL(_bda) 3648 } else { 3649 IM2COL() 3650 } 3651 3652 ggml_vk_create_pipeline(device, device->pipeline_timestep_embedding_f32, "timestep_embedding_f32", timestep_embedding_f32_len, timestep_embedding_f32_data, "main", 2, sizeof(vk_op_timestep_embedding_push_constants), {256, 1, 1}, {}, 1); 3653 3654 ggml_vk_create_pipeline(device, device->pipeline_conv_transpose_1d_f32, "conv_transpose_1d_f32", conv_transpose_1d_f32_len, conv_transpose_1d_f32_data, "main", 3, sizeof(vk_op_conv_transpose_1d_push_constants), {1, 1, 1}, {}, 1); 3655 ggml_vk_create_pipeline(device, device->pipeline_col2im_1d_f32, "col2im_1d_f32", col2im_1d_f32_len, col2im_1d_f32_data, "main", 2, sizeof(vk_op_col2im_1d_push_constants), {256, 1, 1}, {}, 1, true); 3656 ggml_vk_create_pipeline(device, device->pipeline_col2im_1d_f16, "col2im_1d_f16", col2im_1d_f16_len, col2im_1d_f16_data, "main", 2, sizeof(vk_op_col2im_1d_push_constants), {256, 1, 1}, {}, 1, true); 3657 ggml_vk_create_pipeline(device, device->pipeline_col2im_1d_bf16, "col2im_1d_bf16", col2im_1d_bf16_len, col2im_1d_bf16_data, "main", 2, sizeof(vk_op_col2im_1d_push_constants), {256, 1, 1}, {}, 1, true); 3658 3659 ggml_vk_create_pipeline(device, device->pipeline_out_prod_f32, "out_prod_f32", out_prod_f32_len, out_prod_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {256, 1, 1}, {}, 1); 3660 3661 ggml_vk_create_pipeline(device, device->pipeline_snake_f32, "snake_f32", snake_f32_len, snake_f32_data, "main", 4, sizeof(vk_op_snake_push_constants), {256, 1, 1}, {}, 1); 3662 ggml_vk_create_pipeline(device, device->pipeline_snake_f16, "snake_f16", snake_f16_len, snake_f16_data, "main", 4, sizeof(vk_op_snake_push_constants), {256, 1, 1}, {}, 1); 3663 ggml_vk_create_pipeline(device, device->pipeline_snake_bf16, "snake_bf16", snake_bf16_len, snake_bf16_data, "main", 4, sizeof(vk_op_snake_push_constants), {256, 1, 1}, {}, 1); 3664 3665 ggml_vk_create_pipeline(device, device->pipeline_pool1d_f32, "pool1d_f32", pool1d_f32_len, pool1d_f32_data, "main", 2, sizeof(vk_op_pool1d_push_constants), {512, 1, 1}, {}, 1); 3666 ggml_vk_create_pipeline(device, device->pipeline_pool2d_f32, "pool2d_f32", pool2d_f32_len, pool2d_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {1, 1, 1}, {512}, 1); 3667 if (device->subgroup_arithmetic && device->subgroup_require_full_support) { 3668 ggml_vk_create_pipeline(device, device->pipeline_pool2d_subgroup_f32, "pool2d_subgroup_f32", pool2d_subgroup_f32_len, pool2d_subgroup_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {1, 1, 1}, {128}, 1, false, true, device->subgroup_size); 3669 } 3670 3671 ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv6_f32, "rwkv_wkv6_f32", rwkv_wkv6_f32_len, rwkv_wkv6_f32_data, "main", 7, sizeof(vk_op_rwkv_wkv6_push_constants), {1, 1, 1}, {device->subgroup_size}, 1); 3672 3673 ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv7_f32, "rwkv_wkv7_f32", rwkv_wkv7_f32_len, rwkv_wkv7_f32_data, "main", 8, sizeof(vk_op_rwkv_wkv7_push_constants), {1, 1, 1}, {device->subgroup_size}, 1); 3674 3675 ggml_vk_create_pipeline(device, device->pipeline_gated_linear_attn_f32, "gated_linear_attn_f32", gated_linear_attn_f32_len, gated_linear_attn_f32_data, "main", 6, sizeof(vk_op_gated_linear_attn_push_constants), {1, 1, 1}, {}, 1); 3676 3677 for (ggml_type k_type : lightning_indexer_k_types) { 3678 const std::string name = "lightning_indexer_" + std::string(ggml_type_name(k_type)) + "_k_f32"; 3679 ggml_vk_create_pipeline(device, device->pipeline_lightning_indexer_f32[k_type], name.c_str(), lightning_indexer_f32_len, lightning_indexer_f32_data, "main", 5, sizeof(vk_op_lightning_indexer_push_constants), {1, 1, 1}, {(uint32_t)k_type, fa_block_bytes(k_type)}, 1, true); 3680 } 3681 3682 { 3683 const uint32_t gdn_sizes[] = {16, 32, 64, 128}; 3684 const char * gdn_names[][2] = { 3685 {"gated_delta_net_f32_d16", "gated_delta_net_f32_d16_kda"}, 3686 {"gated_delta_net_f32_d32", "gated_delta_net_f32_d32_kda"}, 3687 {"gated_delta_net_f32_d64", "gated_delta_net_f32_d64_kda"}, 3688 {"gated_delta_net_f32_d128", "gated_delta_net_f32_d128_kda"}, 3689 }; 3690 for (uint32_t si = 0; si < 4; si++) { 3691 const uint32_t S_V = gdn_sizes[si]; 3692 GGML_ASSERT(is_pow2(S_V)); 3693 3694 // Intel Xe regresses at SIMD32 for this scan; prefer a narrower subgroup. 3695 uint32_t gdn_subgroup_size = device->subgroup_size; 3696 if (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && 3697 device->subgroup_min_size <= 16u && device->subgroup_max_size >= 16u) { 3698 gdn_subgroup_size = 16u; 3699 } 3700 uint32_t lanes_per_column; 3701 if (device->vendor_id == VK_VENDOR_ID_INTEL) { 3702 // Intel Xe: full-width reduction (min rows/lane) ~10x over the COLS_PER_WG=8 rule. 3703 lanes_per_column = std::min(gdn_subgroup_size, S_V); 3704 } else if (S_V >= 128u && device->subgroup_clustered) { 3705 // COLS_PER_WG=8: measured optimum (Ampere sg32->4, Vega20 sg64->8). 3706 lanes_per_column = std::max(1u, gdn_subgroup_size / 8u); 3707 } else { 3708 // Use largest power-of-two that divides both S_V and subgroup_size so that 3709 // (1) S_V % lanes_per_column == 0 and (2) S_V % (subgroup_size / lanes_per_column) == 0. 3710 // This means we don't need extra bounds checking logic in the shader. 3711 lanes_per_column = std::min(S_V, gdn_subgroup_size); 3712 } 3713 3714 // gated_delta_net.comp relies on S_V % COLS_PER_WG == 0 and 3715 // S_V % LANES_PER_COLUMN == 0 to avoid bounds checks. 3716 while (lanes_per_column > 1u) { 3717 const bool valid_lanes = (gdn_subgroup_size % lanes_per_column) == 0 && 3718 (S_V % lanes_per_column) == 0; 3719 const uint32_t cols_per_wg = valid_lanes ? gdn_subgroup_size / lanes_per_column : 0; 3720 if (valid_lanes && cols_per_wg > 0 && (S_V % cols_per_wg) == 0) { 3721 break; 3722 } 3723 lanes_per_column >>= 1u; 3724 } 3725 3726 GGML_ASSERT((gdn_subgroup_size % lanes_per_column) == 0); 3727 GGML_ASSERT((S_V % lanes_per_column) == 0); 3728 GGML_ASSERT((S_V % (gdn_subgroup_size / lanes_per_column)) == 0); 3729 3730 const bool need_partial_subgroup_reduce = lanes_per_column != 1u && lanes_per_column < gdn_subgroup_size; 3731 const bool use_clustered_reduce = device->subgroup_arithmetic && device->subgroup_clustered && need_partial_subgroup_reduce; 3732 const bool use_subgroup_reduce = device->subgroup_arithmetic && !need_partial_subgroup_reduce; 3733 const bool use_subgroup_ops = use_clustered_reduce || use_subgroup_reduce; 3734 size_t gdn_len; 3735 const void * gdn_data; 3736 if (use_clustered_reduce) { 3737 gdn_len = gated_delta_net_f32_len; 3738 gdn_data = (const void *)gated_delta_net_f32_data; 3739 } else if (use_subgroup_reduce) { 3740 gdn_len = gated_delta_net_f32_nocluster_len; 3741 gdn_data = (const void *)gated_delta_net_f32_nocluster_data; 3742 } else { 3743 gdn_len = gated_delta_net_f32_shmem_len; 3744 gdn_data = (const void *)gated_delta_net_f32_shmem_data; 3745 } 3746 3747 const uint32_t cols_per_wg = gdn_subgroup_size / lanes_per_column; 3748 const std::array wg_denoms = {1u, 1u, cols_per_wg}; 3749 3750 for (uint32_t kda = 0; kda < 2; kda++) { 3751 ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda], 3752 gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants), 3753 wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column}, 1, true, use_subgroup_ops, gdn_subgroup_size); 3754 } 3755 } 3756 } 3757 3758 if (device->subgroup_arithmetic && device->subgroup_require_full_support) { 3759 ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size}, 1, true, true); 3760 ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size}, 1, true, true); 3761 } else { 3762 ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true); 3763 ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true); 3764 } 3765 3766 ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1); 3767 ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_f32, "ssm_conv_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 1}, 1); 3768 ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_bias_silu_f32, "ssm_conv_bias_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 1, 1}, 1); 3769 3770 ggml_vk_create_pipeline(device, device->pipeline_opt_step_adamw_f32, "opt_step_adamw_f32", opt_step_adamw_f32_len, opt_step_adamw_f32_data, "main", 5, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); 3771 3772 ggml_vk_create_pipeline(device, device->pipeline_opt_step_sgd_f32, "opt_step_sgd_f32", opt_step_sgd_f32_len, opt_step_sgd_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); 3773 3774 // conv2d, conv_transpose_2d, conv3d 3775 for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) { 3776 // smaller WG for the small-tile fallback gives more concurrent WGs per SM 3777 uint32_t conv2d_WG_SIZE = (s == CONV_SHAPE_64x32) ? 128 : 256; 3778 uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices. 3779 uint32_t conv2d_TS_K = (s == CONV_SHAPE_64x32) ? 4 : 8; 3780 uint32_t conv2d_SHMEM_PAD = 4; 3781 vk_conv_block_size conv2d_BS = vk_conv_block_sizes[s]; 3782 bool conv2d_UNROLL = true; 3783 3784 #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 3785 if (device->coopmat2) { 3786 conv2d_SHMEM_PAD = 8; // 8 float16_t 3787 } 3788 #endif 3789 3790 if (device->vendor_id == VK_VENDOR_ID_INTEL) { 3791 conv2d_SHMEM_PAD = 0; 3792 conv2d_UNROLL = false; 3793 } else if (device->vendor_id == VK_VENDOR_ID_AMD) { 3794 conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4; 3795 if (s == CONV_SHAPE_128x128 && device->architecture != vk_device_architecture::AMD_GCN) { 3796 conv2d_UNROLL = false; 3797 } 3798 } 3799 3800 // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math. 3801 bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA || 3802 device->architecture == vk_device_architecture::NVIDIA_PRE_TURING; 3803 bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD || 3804 device->architecture == vk_device_architecture::AMD_GCN; 3805 3806 if (device->subgroup_shuffle && 3807 device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316. 3808 allow_collectives_nv && 3809 allow_collectives_amd) { 3810 use_collectives = 1; 3811 conv2d_BS.CRS = std::min( 3812 device->subgroup_size, 3813 conv2d_BS.CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used. 3814 } 3815 3816 // cm1 is used only when cm2 is unavailable; capped at 64x128 (due to shared memory size). 3817 // Requires 16x16x16 f16-acc since that's the fragment shape hard-coded in the shader. 3818 // Subgroup size must be 32 or 64 (to keep WG_SIZE sane) and we need 3819 // subgroup_size_control to force the driver to actually use it. 3820 bool conv2d_use_cm1 = false; 3821 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 3822 conv2d_use_cm1 = !device->coopmat2 && 3823 device->coopmat_support && device->coopmat_support_16x16x16_f16acc && 3824 device->subgroup_size_control && 3825 (device->subgroup_size == 32 || device->subgroup_size == 64) && 3826 s != CONV_SHAPE_128x128; 3827 #endif 3828 3829 const uint32_t conv2d_cm1_shmem_pad = 8; 3830 3831 auto shmem_req = [&](uint32_t pad, bool csh_store, bool fp16_shmem) { 3832 const uint32_t elem_size = fp16_shmem ? (uint32_t)sizeof(uint16_t) : (uint32_t)sizeof(float); 3833 const uint32_t csh_elems = csh_store ? conv2d_BS.K * conv2d_BS.NPQ : (fp16_shmem ? 8u : 0u); 3834 return (conv2d_BS.K * (conv2d_BS.CRS + pad) + conv2d_BS.CRS * (conv2d_BS.NPQ + pad) + csh_elems) * elem_size; 3835 }; 3836 3837 // 2D, transpose-2D, and 3D conv use the same KxCRS @ CRSxNPQ shmem 3838 // layout. cm1 needs Csh for output, so check before applying cm1 params. 3839 if (conv2d_use_cm1 && device->properties.limits.maxComputeSharedMemorySize < shmem_req(conv2d_cm1_shmem_pad, true, true)) { 3840 conv2d_use_cm1 = false; 3841 } 3842 3843 uint32_t conv2d_WM = 16, conv2d_WN = 16; // cm1 subgroup tile, ignored otherwise 3844 if (conv2d_use_cm1) { 3845 conv2d_SHMEM_PAD = conv2d_cm1_shmem_pad; 3846 // 16x16x16 fragments; pick WM/WN to keep WG_SIZE at 256 3847 // (i.e. 8 subgroups for sg=32, 4 subgroups for sg=64). 3848 const bool sg64 = (device->subgroup_size == 64); 3849 switch (s) { 3850 case CONV_SHAPE_64x32: conv2d_WM = sg64 ? 32 : 16; conv2d_WN = 16; break; 3851 case CONV_SHAPE_64x128: conv2d_WM = 32; conv2d_WN = sg64 ? 64 : 32; break; 3852 case CONV_SHAPE_32x256: conv2d_WM = sg64 ? 16 : 32; conv2d_WN = sg64 ? 128 : 32; break; 3853 default: break; 3854 } 3855 const uint32_t warps_M = conv2d_BS.K / conv2d_WM; 3856 const uint32_t warps_N = conv2d_BS.NPQ / conv2d_WN; 3857 conv2d_WG_SIZE = warps_M * warps_N * device->subgroup_size; 3858 } 3859 3860 // stage cm2 accumulator through shmem for coalesced global stores; 3861 // skipped on large tiles where the extra Csh footprint hurts occupancy. 3862 // cm1 always uses the staged path. 3863 uint32_t conv2d_csh_store = (device->coopmat2 && s != CONV_SHAPE_128x128 && s != CONV_SHAPE_256x128) ? 1u : 0u; 3864 if (conv2d_use_cm1) { 3865 conv2d_csh_store = 1; 3866 } 3867 3868 // shmem is fp16 on cm2/cm1 (matches Csh), fp32 on scalar 3869 const bool conv2d_use_fp16_shmem = device->coopmat2 || conv2d_use_cm1; 3870 3871 // shrink CRS if the non-cm1 config still doesn't fit 3872 if (device->properties.limits.maxComputeSharedMemorySize < shmem_req(conv2d_SHMEM_PAD, conv2d_csh_store, conv2d_use_fp16_shmem)) { 3873 GGML_ASSERT(!conv2d_use_cm1); 3874 conv2d_BS.CRS = 8; 3875 if (use_collectives) { 3876 conv2d_BS.CRS = std::min(device->subgroup_size, conv2d_BS.CRS); 3877 } 3878 conv2d_csh_store = 0; 3879 } 3880 3881 std::array wg_denoms = { conv2d_BS.K, 1, 1 }; 3882 std::vector spec_constants = { conv2d_WG_SIZE, conv2d_BS.K, conv2d_BS.CRS, conv2d_BS.NPQ, conv2d_TS_K, use_collectives, conv2d_SHMEM_PAD }; 3883 3884 // cm1 needs a fixed subgroup width to match the WG_SIZE we computed 3885 const uint32_t conv2d_required_subgroup_size = conv2d_use_cm1 ? device->subgroup_size : 0; 3886 3887 #define CREATE_CONV(name, type_suffix, spv_suffix) \ 3888 for (auto &c : device->pipeline_##name##type_suffix[s]) { \ 3889 const vk_conv2d_pipeline_state &state = c.first; \ 3890 std::vector spec_constants_cpy = spec_constants; \ 3891 spec_constants_cpy.push_back(state.s0); \ 3892 spec_constants_cpy.push_back(state.s1); \ 3893 spec_constants_cpy.push_back(state.p0); \ 3894 spec_constants_cpy.push_back(state.p1); \ 3895 spec_constants_cpy.push_back(state.d0); \ 3896 spec_constants_cpy.push_back(state.d1); \ 3897 spec_constants_cpy.push_back(state.KW); \ 3898 spec_constants_cpy.push_back(state.KH); \ 3899 spec_constants_cpy.push_back(state.aligned); \ 3900 spec_constants_cpy.push_back(conv2d_csh_store); \ 3901 spec_constants_cpy.push_back(conv2d_WM); \ 3902 spec_constants_cpy.push_back(conv2d_WN); \ 3903 ggml_vk_create_pipeline( \ 3904 device, c.second, #name #type_suffix, \ 3905 name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \ 3906 sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives || conv2d_required_subgroup_size, conv2d_required_subgroup_size); \ 3907 } 3908 #define CREATE_CONVS(spv_suffix) \ 3909 CREATE_CONV(conv2d, _f32, spv_suffix) \ 3910 CREATE_CONV(conv2d, _f16_f32, spv_suffix) \ 3911 CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \ 3912 CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) 3913 #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 3914 if (device->coopmat2) { 3915 CREATE_CONVS(_cm2) 3916 } else 3917 #endif 3918 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 3919 if (conv2d_use_cm1) { 3920 CREATE_CONVS(_cm1) 3921 } else 3922 #endif 3923 if (conv2d_UNROLL) { 3924 CREATE_CONVS(_unroll) 3925 } else { 3926 CREATE_CONVS( ) 3927 } 3928 #undef CREATE_CONV 3929 #undef CREATE_CONVS 3930 3931 std::vector conv3d_spec_constants = { conv2d_WG_SIZE, conv2d_BS.K, conv2d_BS.CRS, conv2d_BS.NPQ, conv2d_TS_K, conv2d_SHMEM_PAD }; 3932 #define CREATE_CONV3D(type_suffix, spv_suffix) \ 3933 for (auto &c : device->pipeline_conv3d##type_suffix[s]) { \ 3934 const vk_conv3d_pipeline_state &state = c.first; \ 3935 std::vector spec_constants_cpy = conv3d_spec_constants; \ 3936 spec_constants_cpy.push_back(state.s0); \ 3937 spec_constants_cpy.push_back(state.s1); \ 3938 spec_constants_cpy.push_back(state.s2); \ 3939 spec_constants_cpy.push_back(state.p0); \ 3940 spec_constants_cpy.push_back(state.p1); \ 3941 spec_constants_cpy.push_back(state.p2); \ 3942 spec_constants_cpy.push_back(state.d0); \ 3943 spec_constants_cpy.push_back(state.d1); \ 3944 spec_constants_cpy.push_back(state.d2); \ 3945 spec_constants_cpy.push_back(state.KW); \ 3946 spec_constants_cpy.push_back(state.KH); \ 3947 spec_constants_cpy.push_back(state.KD); \ 3948 spec_constants_cpy.push_back(state.aligned); \ 3949 spec_constants_cpy.push_back(conv2d_csh_store); \ 3950 spec_constants_cpy.push_back(conv2d_WM); \ 3951 spec_constants_cpy.push_back(conv2d_WN); \ 3952 ggml_vk_create_pipeline( \ 3953 device, c.second, "conv3d" #type_suffix, \ 3954 conv3d##type_suffix##spv_suffix##_len, conv3d##type_suffix##spv_suffix##_data, "main", 3, \ 3955 sizeof(vk_op_conv3d_push_constants), wg_denoms, spec_constants_cpy, 1, true, conv2d_required_subgroup_size != 0, conv2d_required_subgroup_size); \ 3956 } 3957 #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 3958 if (device->coopmat2) { 3959 CREATE_CONV3D(_f32, _cm2) 3960 CREATE_CONV3D(_f16_f32, _cm2) 3961 } else 3962 #endif 3963 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 3964 if (conv2d_use_cm1) { 3965 CREATE_CONV3D(_f32, _cm1) 3966 CREATE_CONV3D(_f16_f32, _cm1) 3967 } else 3968 #endif 3969 if (conv2d_UNROLL) { 3970 CREATE_CONV3D(_f32, _unroll) 3971 CREATE_CONV3D(_f16_f32, _unroll) 3972 } else { 3973 CREATE_CONV3D(_f32, ) 3974 CREATE_CONV3D(_f16_f32, ) 3975 } 3976 #undef CREATE_CONV3D 3977 } 3978 3979 ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f32, "conv2d_dw_whcn_f32", conv2d_dw_whcn_f32_len, conv2d_dw_whcn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1); 3980 ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f32, "conv2d_dw_cwhn_f32", conv2d_dw_cwhn_f32_len, conv2d_dw_cwhn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1); 3981 ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f16_f32, "conv2d_dw_whcn_f16_f32", conv2d_dw_whcn_f16_f32_len, conv2d_dw_whcn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1); 3982 ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f16_f32, "conv2d_dw_cwhn_f16_f32", conv2d_dw_cwhn_f16_f32_len, conv2d_dw_cwhn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1); 3983 3984 for (uint32_t use_push = 0; use_push < 2; ++use_push) { 3985 for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) { 3986 ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][use_push], "topk_moe_f32_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 4, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<subgroup_size); 3987 } 3988 } 3989 3990 // Drop compile_mutex so other threads can walk while we compile. 3991 compile_lock.unlock(); 3992 3993 // Compile what we claimed; create_pipeline_func reacquires compile_mutex 3994 // at the end to flip compile_pending/compiled and notify waiters. 3995 if (has_claimed_task) { 3996 auto & task = claimed_task; 3997 ggml_vk_create_pipeline_func(device, task.pipeline, task.spv_size, task.spv_data, 3998 task.entrypoint, task.parameter_count, task.wg_denoms, 3999 task.specialization_constants, task.disable_robustness, 4000 task.require_full_subgroups, task.required_subgroup_size); 4001 } 4002 4003 // Another thread may be compiling the pipeline we need; block on it here. 4004 if (wait_pipeline) { 4005 std::unique_lock wait_lock(device->compile_mutex); 4006 device->compile_cv.wait(wait_lock, [&] { 4007 return wait_pipeline->compiled.load(); 4008 }); 4009 } 4010 } 4011 4012 static bool ggml_vk_external_memory_host_usable(vk::DriverId driver_id) { 4013 // Disable external_memory_host until https://github.com/KhronosGroup/MoltenVK/pull/2622 4014 // is available in the Vulkan SDK. 4015 return driver_id != vk::DriverId::eMoltenvk; 4016 } 4017 4018 static bool ggml_vk_host_buffer_import_usable(uint32_t vendor_id) { 4019 // amdgpu re-faults all pages of every imported host allocation on each submission 4020 return vendor_id != VK_VENDOR_ID_AMD; 4021 } 4022 4023 vk_device ggml_vk_get_device(size_t idx) { 4024 VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")"); 4025 4026 static std::mutex mutex; 4027 std::lock_guard lock(mutex); 4028 4029 if (vk_instance.devices[idx] == nullptr) { 4030 VK_LOG_DEBUG("Initializing new vk_device"); 4031 vk_device device = std::make_shared(); 4032 4033 device->memory_logger = std::unique_ptr(new vk_memory_logger()); 4034 4035 size_t dev_num = vk_instance.device_indices[idx]; 4036 4037 std::vector physical_devices = vk_instance.instance.enumeratePhysicalDevices(); 4038 4039 if (dev_num >= physical_devices.size()) { 4040 std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl; 4041 throw std::runtime_error("Device not found"); 4042 } 4043 4044 device->physical_device = physical_devices[dev_num]; 4045 const std::vector ext_props = device->physical_device.enumerateDeviceExtensionProperties(); 4046 4047 device->architecture = get_device_architecture(device->physical_device); 4048 4049 const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY"); 4050 device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr; 4051 4052 const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM"); 4053 device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr; 4054 4055 const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK"); 4056 device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr; 4057 4058 const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE"); 4059 device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr; 4060 4061 bool fp16_storage = false; 4062 bool fp16_compute = false; 4063 bool maintenance4_support = false; 4064 bool sm_builtins = false; 4065 bool amd_shader_core_properties2 = false; 4066 bool pipeline_robustness = false; 4067 bool coopmat2_support = false; 4068 bool coopmat2_decode_vector_support = false; 4069 bool pipeline_executable_properties_support = false; 4070 bool internally_sync_support = false; 4071 device->coopmat_support = false; 4072 device->integer_dot_product = false; 4073 device->shader_64b_indexing = false; 4074 bool bfloat16_support = false; 4075 bool dot2_f16_support = false; 4076 bool ocp_microscaling_extension = false; 4077 bool shader_float8_extension = false; 4078 4079 for (const auto& properties : ext_props) { 4080 if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) { 4081 maintenance4_support = true; 4082 } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) { 4083 fp16_storage = true; 4084 } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) { 4085 fp16_compute = true; 4086 } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) { 4087 sm_builtins = true; 4088 } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) { 4089 amd_shader_core_properties2 = true; 4090 } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) { 4091 pipeline_robustness = true; 4092 } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) { 4093 device->subgroup_size_control = true; 4094 #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 4095 } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 && 4096 !getenv("GGML_VK_DISABLE_COOPMAT")) { 4097 device->coopmat_support = true; 4098 device->coopmat_m = 0; 4099 device->coopmat_n = 0; 4100 device->coopmat_k = 0; 4101 #endif 4102 #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 4103 } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && 4104 !getenv("GGML_VK_DISABLE_COOPMAT2")) { 4105 coopmat2_support = true; 4106 #endif 4107 } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && 4108 !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { 4109 coopmat2_decode_vector_support = true; 4110 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 4111 } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 && 4112 !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) { 4113 device->integer_dot_product = true; 4114 #endif 4115 #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 4116 } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 && 4117 !getenv("GGML_VK_DISABLE_BFLOAT16")) { 4118 bfloat16_support = true; 4119 #endif 4120 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) 4121 } else if (strcmp(VK_EXT_SHADER_OCP_MICROSCALING_TYPES_EXTENSION_NAME, properties.extensionName) == 0) { 4122 ocp_microscaling_extension = true; 4123 #endif 4124 #if defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 4125 } else if (strcmp(VK_EXT_SHADER_FLOAT8_EXTENSION_NAME, properties.extensionName) == 0) { 4126 shader_float8_extension = true; 4127 #endif 4128 } else if (strcmp("VK_VALVE_shader_mixed_float_dot_product", properties.extensionName) == 0 && 4129 !getenv("GGML_VK_DISABLE_DOT2")) { 4130 dot2_f16_support = true; 4131 } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) { 4132 pipeline_executable_properties_support = true; 4133 } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 && 4134 getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) { 4135 device->memory_priority = true; 4136 } else if (strcmp("VK_EXT_external_memory_host", properties.extensionName) == 0) { 4137 device->external_memory_host = true; 4138 } else if (strcmp("VK_KHR_external_semaphore_fd", properties.extensionName) == 0) { 4139 device->external_semaphore = true; 4140 #if defined(VK_EXT_shader_64bit_indexing) 4141 } else if (strcmp("VK_EXT_shader_64bit_indexing", properties.extensionName) == 0) { 4142 device->shader_64b_indexing = true; 4143 #endif 4144 } else if (strcmp(VK_KHR_INTERNALLY_SYNCHRONIZED_QUEUES_EXTENSION_NAME, properties.extensionName) == 0) { 4145 internally_sync_support = true; 4146 } else if (strcmp("VK_EXT_device_fault", properties.extensionName) == 0) { 4147 device->device_fault = true; 4148 } 4149 } 4150 4151 vk::PhysicalDeviceProperties2 props2; 4152 vk::PhysicalDeviceMaintenance3Properties props3; 4153 vk::PhysicalDeviceMaintenance4Properties props4; 4154 vk::PhysicalDeviceSubgroupProperties subgroup_props; 4155 vk::PhysicalDeviceDriverProperties driver_props; 4156 vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props; 4157 vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props; 4158 vk::PhysicalDeviceVulkan11Properties vk11_props; 4159 vk::PhysicalDeviceVulkan12Properties vk12_props; 4160 vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props; 4161 vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props; 4162 vk::PhysicalDeviceExternalMemoryHostPropertiesEXT external_memory_host_props; 4163 4164 props2.pNext = &props3; 4165 props3.pNext = &subgroup_props; 4166 subgroup_props.pNext = &driver_props; 4167 driver_props.pNext = &vk11_props; 4168 vk11_props.pNext = &vk12_props; 4169 4170 VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props; 4171 4172 if (maintenance4_support) { 4173 last_struct->pNext = (VkBaseOutStructure *)&props4; 4174 last_struct = (VkBaseOutStructure *)&props4; 4175 } 4176 if (sm_builtins) { 4177 last_struct->pNext = (VkBaseOutStructure *)&sm_props; 4178 last_struct = (VkBaseOutStructure *)&sm_props; 4179 } 4180 if (amd_shader_core_properties2) { 4181 last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props; 4182 last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props; 4183 } 4184 if (device->subgroup_size_control) { 4185 last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props; 4186 last_struct = (VkBaseOutStructure *)&subgroup_size_control_props; 4187 } 4188 4189 #if defined(VK_NV_cooperative_matrix2) 4190 vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props; 4191 if (coopmat2_support) { 4192 last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props; 4193 last_struct = (VkBaseOutStructure *)&coopmat2_props; 4194 } 4195 #endif 4196 4197 if (device->integer_dot_product) { 4198 last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props; 4199 last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props; 4200 } 4201 4202 if (device->external_memory_host) { 4203 last_struct->pNext = (VkBaseOutStructure *)&external_memory_host_props; 4204 last_struct = (VkBaseOutStructure *)&external_memory_host_props; 4205 } 4206 4207 device->physical_device.getProperties2(&props2); 4208 device->properties = props2.properties; 4209 device->vendor_id = device->properties.vendorID; 4210 device->driver_id = driver_props.driverID; 4211 4212 device->external_memory_host = device->external_memory_host && ggml_vk_external_memory_host_usable(device->driver_id); 4213 4214 // Implementing the async backend interfaces seems broken on older Intel HW, 4215 // see https://github.com/ggml-org/llama.cpp/issues/17302. 4216 device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL || 4217 std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) && 4218 getenv("GGML_VK_DISABLE_ASYNC") == nullptr; 4219 4220 if (!device->support_async) { 4221 GGML_LOG_DEBUG("ggml_vulkan: WARNING: Async execution disabled on certain Intel devices.\n"); 4222 } 4223 4224 const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE"); 4225 4226 if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) { 4227 device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE); 4228 } else if (maintenance4_support) { 4229 device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize); 4230 } else { 4231 device->max_memory_allocation_size = props3.maxMemoryAllocationSize; 4232 } 4233 4234 const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE"); 4235 4236 if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) { 4237 device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE); 4238 } else if (maintenance4_support) { 4239 device->max_buffer_size = props4.maxBufferSize; 4240 } else { 4241 device->max_buffer_size = device->max_memory_allocation_size; 4242 } 4243 4244 const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE"); 4245 4246 if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) { 4247 device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE); 4248 } else { 4249 // Limit batching of allocations to 1GB by default to avoid fragmentation issues 4250 device->suballocation_block_size = 1024*1024*1024; 4251 } 4252 device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size); 4253 4254 device->subgroup_size = subgroup_props.subgroupSize; 4255 device->subgroup_size_log2 = uint32_t(log2f(float(device->subgroup_size))); 4256 device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu; 4257 if (sm_builtins) { 4258 device->shader_core_count = sm_props.shaderSMCount; 4259 } else if (amd_shader_core_properties2) { 4260 device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount; 4261 } else if (device->vendor_id == VK_VENDOR_ID_INTEL) { 4262 device->shader_core_count = ggml_vk_intel_shader_core_count(device->physical_device); 4263 } else { 4264 device->shader_core_count = 0; 4265 } 4266 device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16; 4267 device->float_controls_denorm_preserve_fp16 = vk12_props.shaderDenormPreserveFloat16; 4268 4269 device->subgroup_basic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && 4270 (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBasic); 4271 device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && 4272 (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic); 4273 #ifdef __APPLE__ 4274 // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846) 4275 if (device->vendor_id == VK_VENDOR_ID_AMD) { 4276 device->subgroup_arithmetic = false; 4277 } 4278 #endif 4279 device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && 4280 (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle); 4281 #ifdef __APPLE__ 4282 if (device->vendor_id == VK_VENDOR_ID_AMD) { 4283 device->subgroup_shuffle = false; 4284 } 4285 #endif 4286 device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && 4287 (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered); 4288 4289 device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && 4290 (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot); 4291 4292 device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && 4293 (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote); 4294 4295 // Submit at least every 100 nodes, in case there are workloads without as much matmul. 4296 device->max_nodes_per_submit = 100; 4297 const char* GGML_VK_MAX_NODES_PER_SUBMIT = getenv("GGML_VK_MAX_NODES_PER_SUBMIT"); 4298 if (GGML_VK_MAX_NODES_PER_SUBMIT != nullptr) { 4299 uint32_t max_nodes_per_submit = std::stoul(GGML_VK_MAX_NODES_PER_SUBMIT); 4300 device->max_nodes_per_submit = std::max(max_nodes_per_submit, 1u); 4301 } 4302 4303 const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr; 4304 4305 device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute; 4306 4307 if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) { 4308 device->coopmat_support = false; 4309 } 4310 4311 device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated; 4312 4313 device->min_imported_host_pointer_alignment = external_memory_host_props.minImportedHostPointerAlignment; 4314 4315 device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations))); 4316 4317 std::vector queue_family_props = device->physical_device.getQueueFamilyProperties(); 4318 4319 // Try to find a non-graphics compute queue and transfer-focused queues 4320 // Allow overriding avoiding the graphics queue because it can increase performance on RADV 4321 const bool allow_graphics_queue = (getenv("GGML_VK_ALLOW_GRAPHICS_QUEUE") != nullptr); 4322 const vk::QueueFlagBits graphics_flag = allow_graphics_queue ? (vk::QueueFlagBits)0 : vk::QueueFlagBits::eGraphics; 4323 const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, graphics_flag, -1, 1); 4324 const uint32_t transfer_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eTransfer, vk::QueueFlagBits::eCompute | graphics_flag, compute_queue_family_index, 1); 4325 4326 const float priorities[] = { 1.0f, 1.0f }; 4327 device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1; 4328 4329 std::vector device_queue_create_infos; 4330 vk::DeviceCreateInfo device_create_info{}; 4331 std::vector device_extensions; 4332 vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures(); 4333 4334 VkPhysicalDeviceFeatures2 device_features2; 4335 device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; 4336 device_features2.pNext = nullptr; 4337 device_features2.features = (VkPhysicalDeviceFeatures)device_features; 4338 4339 VkPhysicalDeviceVulkan11Features vk11_features; 4340 vk11_features.pNext = nullptr; 4341 vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; 4342 device_features2.pNext = &vk11_features; 4343 4344 VkPhysicalDeviceVulkan12Features vk12_features; 4345 vk12_features.pNext = nullptr; 4346 vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; 4347 vk11_features.pNext = &vk12_features; 4348 4349 last_struct = (VkBaseOutStructure *)&vk12_features; 4350 4351 VkPhysicalDeviceInternallySynchronizedQueuesFeaturesKHR internally_synchronized_queues_features{}; 4352 internally_synchronized_queues_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INTERNALLY_SYNCHRONIZED_QUEUES_FEATURES_KHR; 4353 internally_synchronized_queues_features.pNext = nullptr; 4354 internally_synchronized_queues_features.internallySynchronizedQueues = VK_FALSE; 4355 4356 if (internally_sync_support) { 4357 last_struct->pNext = (VkBaseOutStructure *)&internally_synchronized_queues_features; 4358 last_struct = (VkBaseOutStructure *)&internally_synchronized_queues_features; 4359 device_extensions.push_back(VK_KHR_INTERNALLY_SYNCHRONIZED_QUEUES_EXTENSION_NAME); 4360 } 4361 4362 VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features; 4363 pl_robustness_features.pNext = nullptr; 4364 pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT; 4365 pl_robustness_features.pipelineRobustness = VK_FALSE; 4366 4367 if (pipeline_robustness) { 4368 last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features; 4369 last_struct = (VkBaseOutStructure *)&pl_robustness_features; 4370 device_extensions.push_back("VK_EXT_pipeline_robustness"); 4371 } 4372 4373 VkPhysicalDeviceMemoryPriorityFeaturesEXT memory_priority_features; 4374 memory_priority_features.pNext = nullptr; 4375 memory_priority_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT; 4376 memory_priority_features.memoryPriority = VK_FALSE; 4377 if (device->memory_priority) { 4378 last_struct->pNext = (VkBaseOutStructure *)&memory_priority_features; 4379 last_struct = (VkBaseOutStructure *)&memory_priority_features; 4380 device_extensions.push_back("VK_EXT_memory_priority"); 4381 } 4382 4383 VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features; 4384 subgroup_size_control_features.pNext = nullptr; 4385 subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT; 4386 subgroup_size_control_features.computeFullSubgroups = false; 4387 subgroup_size_control_features.subgroupSizeControl = false; 4388 4389 if (device->subgroup_size_control) { 4390 last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features; 4391 last_struct = (VkBaseOutStructure *)&subgroup_size_control_features; 4392 } 4393 4394 #if defined(VK_KHR_cooperative_matrix) 4395 VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features; 4396 coopmat_features.pNext = nullptr; 4397 coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR; 4398 coopmat_features.cooperativeMatrix = VK_FALSE; 4399 4400 if (device->coopmat_support) { 4401 last_struct->pNext = (VkBaseOutStructure *)&coopmat_features; 4402 last_struct = (VkBaseOutStructure *)&coopmat_features; 4403 } 4404 #endif 4405 4406 #if defined(VK_NV_cooperative_matrix2) 4407 VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {}; 4408 coopmat2_features.pNext = nullptr; 4409 coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV; 4410 if (coopmat2_support) { 4411 last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features; 4412 last_struct = (VkBaseOutStructure *)&coopmat2_features; 4413 device_extensions.push_back("VK_NV_cooperative_matrix2"); 4414 } 4415 #endif 4416 4417 VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV coopmat2_decode_vector_features {}; 4418 coopmat2_decode_vector_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_DECODE_VECTOR_FEATURES_NV; 4419 if (coopmat2_decode_vector_support) { 4420 last_struct->pNext = (VkBaseOutStructure *)&coopmat2_decode_vector_features; 4421 last_struct = (VkBaseOutStructure *)&coopmat2_decode_vector_features; 4422 device_extensions.push_back(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME); 4423 } 4424 4425 #if defined(VK_KHR_shader_bfloat16) 4426 VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {}; 4427 bfloat16_features.pNext = nullptr; 4428 bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR; 4429 if (bfloat16_support) { 4430 last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features; 4431 last_struct = (VkBaseOutStructure *)&bfloat16_features; 4432 device_extensions.push_back("VK_KHR_shader_bfloat16"); 4433 } 4434 #endif 4435 4436 VkPhysicalDeviceShaderOCPMicroscalingTypesFeaturesEXT ocp_microscaling_features {}; 4437 ocp_microscaling_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OCP_MICROSCALING_TYPES_FEATURES_EXT; 4438 if (ocp_microscaling_extension) { 4439 last_struct->pNext = (VkBaseOutStructure *)&ocp_microscaling_features; 4440 last_struct = (VkBaseOutStructure *)&ocp_microscaling_features; 4441 device_extensions.push_back(VK_EXT_SHADER_OCP_MICROSCALING_TYPES_EXTENSION_NAME); 4442 } 4443 4444 VkPhysicalDeviceShaderFloat8FeaturesEXT shader_float8_features {}; 4445 shader_float8_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT8_FEATURES_EXT; 4446 if (shader_float8_extension) { 4447 last_struct->pNext = (VkBaseOutStructure *)&shader_float8_features; 4448 last_struct = (VkBaseOutStructure *)&shader_float8_features; 4449 device_extensions.push_back(VK_EXT_SHADER_FLOAT8_EXTENSION_NAME); 4450 } 4451 4452 VkPhysicalDeviceMaintenance4Features maint4_features {}; 4453 maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES; 4454 if (maintenance4_support) { 4455 last_struct->pNext = (VkBaseOutStructure *)&maint4_features; 4456 last_struct = (VkBaseOutStructure *)&maint4_features; 4457 device_extensions.push_back("VK_KHR_maintenance4"); 4458 } 4459 4460 VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {}; 4461 shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR; 4462 if (device->integer_dot_product) { 4463 last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features; 4464 last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features; 4465 device_extensions.push_back("VK_KHR_shader_integer_dot_product"); 4466 } 4467 4468 VkPhysicalDeviceShaderMixedFloatDotProductFeaturesVALVE dot2_features {}; 4469 dot2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MIXED_FLOAT_DOT_PRODUCT_FEATURES_VALVE; 4470 if (dot2_f16_support) { 4471 last_struct->pNext = (VkBaseOutStructure *)&dot2_features; 4472 last_struct = (VkBaseOutStructure *)&dot2_features; 4473 device_extensions.push_back("VK_VALVE_shader_mixed_float_dot_product"); 4474 } 4475 4476 VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {}; 4477 pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR; 4478 if (pipeline_executable_properties_support) { 4479 last_struct->pNext = (VkBaseOutStructure *)&pep_features; 4480 last_struct = (VkBaseOutStructure *)&pep_features; 4481 device_extensions.push_back("VK_KHR_pipeline_executable_properties"); 4482 } 4483 4484 if (device->external_memory_host) { 4485 device_extensions.push_back("VK_EXT_external_memory_host"); 4486 } 4487 if (device->external_semaphore) { 4488 device_extensions.push_back("VK_KHR_external_semaphore_fd"); 4489 } 4490 4491 #if defined(VK_EXT_shader_64bit_indexing) 4492 VkPhysicalDeviceShader64BitIndexingFeaturesEXT shader_64bit_indexing_features {}; 4493 shader_64bit_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_64_BIT_INDEXING_FEATURES_EXT; 4494 if (device->shader_64b_indexing) { 4495 last_struct->pNext = (VkBaseOutStructure *)&shader_64bit_indexing_features; 4496 last_struct = (VkBaseOutStructure *)&shader_64bit_indexing_features; 4497 device_extensions.push_back("VK_EXT_shader_64bit_indexing"); 4498 } 4499 #endif 4500 4501 VkPhysicalDeviceFaultFeaturesEXT fault_features {}; 4502 fault_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT; 4503 if (device->device_fault) { 4504 last_struct->pNext = (VkBaseOutStructure *)&fault_features; 4505 last_struct = (VkBaseOutStructure *)&fault_features; 4506 device_extensions.push_back("VK_EXT_device_fault"); 4507 } 4508 4509 vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2); 4510 4511 device->device_fault = device->device_fault && fault_features.deviceFault; 4512 4513 device->has_internally_synchronized_queues = internally_synchronized_queues_features.internallySynchronizedQueues; 4514 4515 // Build queue create infos only after querying whether internally synchronized queues are enabled. 4516 // getQueue2() later uses the same flag, so creation/retrieval must stay consistent. 4517 vk::DeviceQueueCreateFlags queue_flags = device->has_internally_synchronized_queues ? 4518 eInternallySynchronizedKHR : 4519 vk::DeviceQueueCreateFlags(); 4520 4521 if (compute_queue_family_index != transfer_queue_family_index) { 4522 device_queue_create_infos.push_back({queue_flags, compute_queue_family_index, 1, priorities}); 4523 device_queue_create_infos.push_back({queue_flags, transfer_queue_family_index, 1, priorities + 1}); 4524 } else if(!device->single_queue) { 4525 device_queue_create_infos.push_back({queue_flags, compute_queue_family_index, 2, priorities}); 4526 } else { 4527 device_queue_create_infos.push_back({queue_flags, compute_queue_family_index, 1, priorities}); 4528 } 4529 4530 device->pipeline_executable_properties_support = pipeline_executable_properties_support; 4531 4532 device->fp16 = device->fp16 && vk12_features.shaderFloat16; 4533 4534 #if defined(VK_KHR_shader_bfloat16) 4535 device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type; 4536 #else 4537 device->bf16 = false; 4538 #endif 4539 4540 device->dot2_f16 = dot2_f16_support && dot2_features.shaderMixedFloatDotProductFloat16AccFloat32; 4541 device->ocp_fp4 = ocp_microscaling_extension && ocp_microscaling_features.shaderFloat4 && 4542 shader_float8_extension && shader_float8_features.shaderFloat8 && 4543 !getenv("GGML_VK_DISABLE_OCP_FP4"); 4544 4545 device->pipeline_robustness = pl_robustness_features.pipelineRobustness; 4546 4547 device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 && 4548 device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) && 4549 getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr; 4550 4551 device->shader_int64 = device_features2.features.shaderInt64; 4552 device->buffer_device_address = vk12_features.bufferDeviceAddress; 4553 device->vulkan_memory_model = vk12_features.vulkanMemoryModel; 4554 4555 if (device->subgroup_size_control) { 4556 device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize; 4557 device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize; 4558 device_extensions.push_back("VK_EXT_subgroup_size_control"); 4559 } 4560 4561 device->subgroup_size_control = device->subgroup_size_control && 4562 (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) && 4563 subgroup_size_control_features.subgroupSizeControl; 4564 4565 device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups; 4566 4567 #if defined(VK_KHR_cooperative_matrix) 4568 device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix; 4569 device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support; 4570 #endif 4571 4572 if (coopmat2_support) { 4573 #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 4574 if (coopmat2_features.cooperativeMatrixWorkgroupScope && 4575 coopmat2_features.cooperativeMatrixFlexibleDimensions && 4576 coopmat2_features.cooperativeMatrixReductions && 4577 coopmat2_features.cooperativeMatrixConversions && 4578 coopmat2_features.cooperativeMatrixPerElementOperations && 4579 coopmat2_features.cooperativeMatrixTensorAddressing && 4580 coopmat2_features.cooperativeMatrixBlockLoads && 4581 vk12_features.bufferDeviceAddress) { 4582 4583 std::vector flexible_dimensions; 4584 uint32_t count = 0; 4585 4586 PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV 4587 _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV = 4588 (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV) 4589 vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV"); 4590 4591 _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr); 4592 4593 VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {}; 4594 empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV; 4595 flexible_dimensions.resize(count, empty_prop); 4596 4597 _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data()); 4598 4599 bool found_fp16_128 = false, 4600 found_fp16_256 = false, 4601 found_fp32_128 = false, 4602 found_fp32_256 = false; 4603 bool found_bf16_128 = false, 4604 found_bf16_256 = false; 4605 // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128 4606 // with 32x16x16 and 256 with 32x32x16. 4607 for (auto &prop : flexible_dimensions) { 4608 if (prop.saturatingAccumulation == VK_FALSE && 4609 prop.scope == VK_SCOPE_WORKGROUP_KHR) { 4610 4611 if (prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR && 4612 prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) { 4613 4614 if (prop.workgroupInvocations == 128 && 4615 prop.MGranularity <= 32 && 4616 prop.NGranularity <= 16 && 4617 prop.KGranularity <= 16) { 4618 if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR && 4619 prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) { 4620 found_fp16_128 = true; 4621 } 4622 if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR && 4623 prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) { 4624 found_fp32_128 = true; 4625 } 4626 } 4627 if (prop.workgroupInvocations == 256 && 4628 prop.MGranularity <= 32 && 4629 prop.NGranularity <= 32 && 4630 prop.KGranularity <= 16) { 4631 if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR && 4632 prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) { 4633 found_fp16_256 = true; 4634 } 4635 if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR && 4636 prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) { 4637 found_fp32_256 = true; 4638 } 4639 } 4640 } 4641 4642 #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 4643 if (bfloat16_support && 4644 prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR && 4645 prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR && 4646 prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR && 4647 prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) { 4648 4649 if (prop.workgroupInvocations == 128 && 4650 prop.MGranularity <= 32 && 4651 prop.NGranularity <= 16 && 4652 prop.KGranularity <= 16) { 4653 found_bf16_128 = true; 4654 } 4655 if (prop.workgroupInvocations == 256 && 4656 prop.MGranularity <= 32 && 4657 prop.NGranularity <= 32 && 4658 prop.KGranularity <= 16) { 4659 found_bf16_256 = true; 4660 } 4661 } 4662 #endif 4663 } 4664 } 4665 if (found_fp16_128 && found_fp16_256 && 4666 found_fp32_128 && found_fp32_256 && 4667 coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) { 4668 device->coopmat2 = true; 4669 device->coopmat2_bf16_support = found_bf16_128 && found_bf16_256; 4670 device->coopmat2_decode_vector = coopmat2_decode_vector_support && coopmat2_decode_vector_features.cooperativeMatrixDecodeVector; 4671 } 4672 } 4673 #endif 4674 } 4675 4676 if (!vk11_features.storageBuffer16BitAccess) { 4677 std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl; 4678 throw std::runtime_error("Unsupported device"); 4679 } 4680 4681 device_extensions.push_back("VK_KHR_16bit_storage"); 4682 4683 #ifdef GGML_VULKAN_VALIDATE 4684 device_extensions.push_back("VK_KHR_shader_non_semantic_info"); 4685 #endif 4686 4687 if (device->fp16) { 4688 device_extensions.push_back("VK_KHR_shader_float16_int8"); 4689 } 4690 4691 #if defined(VK_KHR_cooperative_matrix) 4692 if (device->coopmat_support) { 4693 // Query supported shapes 4694 std::vector cm_props; 4695 4696 PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR = 4697 (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR"); 4698 4699 uint32_t cm_props_num; 4700 4701 pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr); 4702 4703 cm_props.resize(cm_props_num); 4704 4705 for (auto& prop : cm_props) { 4706 prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR; 4707 } 4708 4709 pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data()); 4710 4711 VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size()); 4712 4713 for (auto& prop : cm_props) { 4714 VK_LOG_DEBUG("ggml_vulkan: M: " << prop.MSize << " N: " << prop.NSize << " K: " << prop.KSize << " A: " << vk::to_string((vk::ComponentTypeKHR)prop.AType) << " B: " << vk::to_string((vk::ComponentTypeKHR)prop.BType) << " C: " << vk::to_string((vk::ComponentTypeKHR)prop.CType) << " Result: " << vk::to_string((vk::ComponentTypeKHR)prop.ResultType) << " saturatingAccumulation: " << prop.saturatingAccumulation << " scope: " << vk::to_string((vk::ScopeKHR)prop.scope)); 4715 4716 if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 && 4717 (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 && 4718 (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup 4719 ) { 4720 if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 && 4721 (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) { 4722 // coopmat sizes not set yet 4723 if (device->coopmat_m == 0) { 4724 device->coopmat_acc_f32_support = true; 4725 device->coopmat_m = prop.MSize; 4726 device->coopmat_n = prop.NSize; 4727 device->coopmat_k = prop.KSize; 4728 } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) { 4729 // Only enable if shape is identical 4730 device->coopmat_acc_f32_support = true; 4731 } 4732 if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) { 4733 device->coopmat_support_16x16x16_f32acc = true; 4734 } 4735 } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 && 4736 (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) { 4737 // coopmat sizes not set yet 4738 if (device->coopmat_m == 0) { 4739 device->coopmat_acc_f16_support = true; 4740 device->coopmat_m = prop.MSize; 4741 device->coopmat_n = prop.NSize; 4742 device->coopmat_k = prop.KSize; 4743 } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) { 4744 // Only enable if shape is identical 4745 device->coopmat_acc_f16_support = true; 4746 } 4747 if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) { 4748 device->coopmat_support_16x16x16_f16acc = true; 4749 } 4750 } 4751 } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 && 4752 (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 && 4753 (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 && 4754 (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 && 4755 (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup && 4756 device->coopmat_int_m == 0 4757 ) { 4758 device->coopmat_int_support = true; 4759 device->coopmat_int_m = prop.MSize; 4760 device->coopmat_int_n = prop.NSize; 4761 device->coopmat_int_k = prop.KSize; 4762 } 4763 #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 4764 if (bfloat16_support && 4765 prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR && 4766 prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR && 4767 prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR && 4768 prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR && 4769 (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup 4770 ) { 4771 // coopmat sizes not set yet 4772 if (device->coopmat_m == 0) { 4773 device->coopmat_bf16_support = true; 4774 device->coopmat_m = prop.MSize; 4775 device->coopmat_n = prop.NSize; 4776 device->coopmat_k = prop.KSize; 4777 } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) { 4778 // Only enable if shape is identical 4779 device->coopmat_bf16_support = true; 4780 } 4781 } 4782 #endif 4783 } 4784 4785 if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) { 4786 // No suitable matmul mode found 4787 GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n"); 4788 device->coopmat_support = false; 4789 } 4790 } 4791 4792 if (device->coopmat_support) { 4793 device_extensions.push_back("VK_KHR_cooperative_matrix"); 4794 } 4795 #endif 4796 device->name = GGML_VK_NAME + std::to_string(idx); 4797 4798 device_create_info 4799 .setFlags(vk::DeviceCreateFlags()) 4800 .setQueueCreateInfos(device_queue_create_infos) 4801 .setPEnabledExtensionNames(device_extensions); 4802 device_create_info.setPNext(&device_features2); 4803 device->device = device->physical_device.createDevice(device_create_info); 4804 4805 if (device->device_fault) { 4806 device->pfn_vkGetDeviceFaultInfoEXT = (PFN_vkGetDeviceFaultInfoEXT) 4807 vkGetDeviceProcAddr(device->device, "vkGetDeviceFaultInfoEXT"); 4808 } 4809 4810 // Queues 4811 device->compute_queue = ggml_vk_create_queue(device, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false); 4812 4813 // Shaders 4814 // Disable matmul tile sizes early if performance low or not supported 4815 for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) { 4816 switch (device->vendor_id) { 4817 #ifndef GGML_VULKAN_RUN_TESTS 4818 case VK_VENDOR_ID_AMD: 4819 device->mul_mat_l[i] = device->coopmat_support && device->driver_id != vk::DriverId::eAmdProprietary; 4820 device->mul_mat_m[i] = true; 4821 device->mul_mat_s[i] = true; 4822 device->mul_mat_id_l[i] = false; 4823 device->mul_mat_id_m[i] = true; 4824 device->mul_mat_id_s[i] = true; 4825 break; 4826 case VK_VENDOR_ID_INTEL: { 4827 // Current Windows driver does not expose BF16 support. 4828 // We only want to use l_warptile if coopmat is available 4829 const bool use_l_warptile = (i == GGML_TYPE_BF16) ? (device->coopmat_bf16_support && device->coopmat_support) : device->coopmat_support; 4830 device->mul_mat_l[i] = use_l_warptile; 4831 device->mul_mat_id_l[i] = use_l_warptile; 4832 device->mul_mat_m[i] = true; 4833 device->mul_mat_s[i] = true; 4834 device->mul_mat_id_m[i] = true; 4835 device->mul_mat_id_s[i] = true; 4836 break; 4837 } 4838 case VK_VENDOR_ID_APPLE: 4839 device->mul_mat_l[i] = false; 4840 device->mul_mat_m[i] = true; 4841 device->mul_mat_s[i] = false; 4842 device->mul_mat_id_l[i] = false; 4843 device->mul_mat_id_m[i] = true; 4844 device->mul_mat_id_s[i] = false; 4845 break; 4846 case VK_VENDOR_ID_QUALCOMM: 4847 device->mul_mat_l[i] = false; 4848 device->mul_mat_m[i] = true; 4849 device->mul_mat_s[i] = !device->coopmat_support; 4850 device->mul_mat_id_l[i] = false; 4851 device->mul_mat_id_m[i] = true; 4852 device->mul_mat_id_s[i] = !device->coopmat_support; 4853 break; 4854 case VK_VENDOR_ID_SAMSUNG: 4855 device->mul_mat_l[i] = false; 4856 device->mul_mat_m[i] = true; 4857 device->mul_mat_s[i] = true; 4858 device->mul_mat_id_l[i] = false; 4859 device->mul_mat_id_m[i] = true; 4860 device->mul_mat_id_s[i] = true; 4861 break; 4862 #endif 4863 default: 4864 device->mul_mat_l[i] = true; 4865 device->mul_mat_m[i] = true; 4866 device->mul_mat_s[i] = true; 4867 device->mul_mat_id_l[i] = true; 4868 device->mul_mat_id_m[i] = true; 4869 device->mul_mat_id_s[i] = true; 4870 break; 4871 } 4872 4873 #if VK_HEADER_VERSION >= 287 4874 // Honeykrisp driver for Asahi Linux doesn't report VK_VENDOR_ID_APPLE. 4875 // Check for Honeykrisp driver and force same configuration as the VK_VENDOR_ID_APPLE case. 4876 if (device->driver_id == vk::DriverId::eMesaHoneykrisp) { 4877 device->mul_mat_l[i] = false; 4878 device->mul_mat_m[i] = true; 4879 device->mul_mat_s[i] = false; 4880 device->mul_mat_id_l[i] = false; 4881 device->mul_mat_id_m[i] = true; 4882 device->mul_mat_id_s[i] = false; 4883 } 4884 #endif 4885 4886 device->mul_mat_l_int[i] = device->mul_mat_l[i]; 4887 device->mul_mat_m_int[i] = device->mul_mat_m[i]; 4888 device->mul_mat_s_int[i] = device->mul_mat_s[i]; 4889 device->mul_mat_id_l_int[i] = device->mul_mat_id_l[i]; 4890 device->mul_mat_id_m_int[i] = device->mul_mat_id_m[i]; 4891 device->mul_mat_id_s_int[i] = device->mul_mat_id_s[i]; 4892 } 4893 4894 4895 std::vector dsl_binding; 4896 std::vector dsl_binding_flags; 4897 for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) { 4898 dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute}); 4899 dsl_binding_flags.push_back({}); 4900 } 4901 4902 vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags }; 4903 4904 vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info( 4905 {}, 4906 dsl_binding); 4907 descriptor_set_layout_create_info.setPNext(&dslbfci); 4908 device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info); 4909 4910 ggml_vk_load_shaders(device); 4911 4912 // Prefer a dedicated transfer queue on AMD dGPUs (non-GCN) when graphics queue use is disabled. 4913 const bool prefers_transfer_queue = 4914 device->vendor_id == VK_VENDOR_ID_AMD && 4915 device->architecture != AMD_GCN && 4916 !device->uma && 4917 !allow_graphics_queue; 4918 4919 if (!device->single_queue) { 4920 const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0; 4921 device->transfer_queue = ggml_vk_create_queue(device, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true); 4922 4923 device->async_use_transfer_queue = prefers_transfer_queue || (getenv("GGML_VK_ASYNC_USE_TRANSFER_QUEUE") != nullptr); 4924 } else { 4925 device->transfer_queue = ggml_vk_create_aliased_queue(device, device->compute_queue); 4926 4927 device->async_use_transfer_queue = false; 4928 } 4929 4930 device->fence = device->device.createFence({}); 4931 4932 device->buffer_type = { 4933 /* .iface = */ ggml_backend_vk_buffer_type_interface, 4934 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx), 4935 /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device }, 4936 }; 4937 4938 device->idx = idx; 4939 4940 device->serialize_submissions = getenv("GGML_VK_SERIALIZE_SUBMISSIONS") != nullptr; 4941 4942 device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr; 4943 4944 device->disable_descriptor_reuse = getenv("GGML_VK_DISABLE_DESCRIPTOR_REUSE") != nullptr; 4945 4946 device->add_rms_fusion = !device->disable_fusion && 4947 device->subgroup_arithmetic && 4948 device->vendor_id != VK_VENDOR_ID_INTEL; 4949 device->partials_binding_alignment = 4950 std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment); 4951 4952 device->mmvq_mode = 0; 4953 if (getenv("GGML_VK_DISABLE_MMVQ")) { 4954 device->mmvq_mode = -1; 4955 } else if (getenv("GGML_VK_FORCE_MMVQ")) { 4956 device->mmvq_mode = 1; 4957 } 4958 4959 // publish the device only when it is fully built 4960 vk_instance.devices[idx] = device; 4961 4962 return device; 4963 } 4964 4965 return vk_instance.devices[idx]; 4966 } 4967 4968 static void ggml_vk_print_gpu_info(size_t idx) { 4969 GGML_ASSERT(idx < vk_instance.device_indices.size()); 4970 size_t dev_num = vk_instance.device_indices[idx]; 4971 VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")"); 4972 GGML_ASSERT(vk_instance_initialized); 4973 4974 std::vector devices = vk_instance.instance.enumeratePhysicalDevices(); 4975 4976 if (dev_num >= devices.size()) { 4977 std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl; 4978 throw std::runtime_error("Device not found"); 4979 } 4980 4981 vk::PhysicalDevice physical_device = devices[dev_num]; 4982 std::vector ext_props = physical_device.enumerateDeviceExtensionProperties(); 4983 4984 bool fp16_storage = false; 4985 bool fp16_compute = false; 4986 bool coopmat_support = false; 4987 bool coopmat2_support = false; 4988 bool coopmat2_decode_vector_support = false; 4989 bool integer_dot_product = false; 4990 bool bfloat16_support = false; 4991 bool dot2_f16_support = false; 4992 bool ocp_microscaling_extension = false; 4993 bool shader_float8_extension = false; 4994 4995 for (auto properties : ext_props) { 4996 if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) { 4997 fp16_storage = true; 4998 } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) { 4999 fp16_compute = true; 5000 #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 5001 } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 && 5002 !getenv("GGML_VK_DISABLE_COOPMAT")) { 5003 coopmat_support = true; 5004 #endif 5005 #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 5006 } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && 5007 !getenv("GGML_VK_DISABLE_COOPMAT2")) { 5008 coopmat2_support = true; 5009 #endif 5010 } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && 5011 !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { 5012 coopmat2_decode_vector_support = true; 5013 #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) 5014 } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 && 5015 !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) { 5016 integer_dot_product = true; 5017 #endif 5018 #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) 5019 } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 && 5020 !getenv("GGML_VK_DISABLE_BFLOAT16")) { 5021 bfloat16_support = true; 5022 #endif 5023 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) 5024 } else if (strcmp(VK_EXT_SHADER_OCP_MICROSCALING_TYPES_EXTENSION_NAME, properties.extensionName) == 0) { 5025 ocp_microscaling_extension = true; 5026 #endif 5027 #if defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 5028 } else if (strcmp(VK_EXT_SHADER_FLOAT8_EXTENSION_NAME, properties.extensionName) == 0) { 5029 shader_float8_extension = true; 5030 #endif 5031 } else if (strcmp("VK_VALVE_shader_mixed_float_dot_product", properties.extensionName) == 0 && 5032 !getenv("GGML_VK_DISABLE_DOT2")) { 5033 dot2_f16_support = true; 5034 } 5035 } 5036 5037 const vk_device_architecture device_architecture = get_device_architecture(physical_device); 5038 5039 const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16"); 5040 bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr; 5041 5042 bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute; 5043 5044 vk::PhysicalDeviceProperties2 props2; 5045 vk::PhysicalDeviceMaintenance3Properties props3; 5046 vk::PhysicalDeviceSubgroupProperties subgroup_props; 5047 vk::PhysicalDeviceDriverProperties driver_props; 5048 vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props; 5049 props2.pNext = &props3; 5050 props3.pNext = &subgroup_props; 5051 subgroup_props.pNext = &driver_props; 5052 5053 // Pointer to the last chain element 5054 VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props; 5055 5056 if (integer_dot_product) { 5057 last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props; 5058 last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props; 5059 } 5060 5061 physical_device.getProperties2(&props2); 5062 5063 VkPhysicalDeviceFeatures2 device_features2; 5064 device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; 5065 device_features2.pNext = nullptr; 5066 5067 VkPhysicalDeviceVulkan11Features vk11_features; 5068 vk11_features.pNext = nullptr; 5069 vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; 5070 device_features2.pNext = &vk11_features; 5071 5072 VkPhysicalDeviceVulkan12Features vk12_features; 5073 vk12_features.pNext = nullptr; 5074 vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; 5075 vk11_features.pNext = &vk12_features; 5076 5077 // Pointer to the last chain element 5078 last_struct = (VkBaseOutStructure *)&vk12_features; 5079 5080 #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 5081 VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features; 5082 coopmat_features.pNext = nullptr; 5083 coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR; 5084 coopmat_features.cooperativeMatrix = VK_FALSE; 5085 5086 if (coopmat_support) { 5087 last_struct->pNext = (VkBaseOutStructure *)&coopmat_features; 5088 last_struct = (VkBaseOutStructure *)&coopmat_features; 5089 } 5090 #endif 5091 5092 VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {}; 5093 shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR; 5094 if (integer_dot_product) { 5095 last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features; 5096 last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features; 5097 } 5098 5099 #if defined(VK_KHR_shader_bfloat16) 5100 VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {}; 5101 bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR; 5102 if (bfloat16_support) { 5103 last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features; 5104 last_struct = (VkBaseOutStructure *)&bfloat16_features; 5105 } 5106 #endif 5107 5108 #if defined(VK_NV_cooperative_matrix2) 5109 VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {}; 5110 coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV; 5111 if (coopmat2_support) { 5112 last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features; 5113 last_struct = (VkBaseOutStructure *)&coopmat2_features; 5114 } 5115 #endif 5116 5117 VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV coopmat2_decode_vector_features {}; 5118 coopmat2_decode_vector_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_DECODE_VECTOR_FEATURES_NV; 5119 if (coopmat2_decode_vector_support) { 5120 last_struct->pNext = (VkBaseOutStructure *)&coopmat2_decode_vector_features; 5121 last_struct = (VkBaseOutStructure *)&coopmat2_decode_vector_features; 5122 } 5123 5124 VkPhysicalDeviceShaderMixedFloatDotProductFeaturesVALVE dot2_features {}; 5125 dot2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MIXED_FLOAT_DOT_PRODUCT_FEATURES_VALVE; 5126 if (dot2_f16_support) { 5127 last_struct->pNext = (VkBaseOutStructure *)&dot2_features; 5128 last_struct = (VkBaseOutStructure *)&dot2_features; 5129 } 5130 5131 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 5132 VkPhysicalDeviceShaderOCPMicroscalingTypesFeaturesEXT ocp_microscaling_features {}; 5133 ocp_microscaling_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OCP_MICROSCALING_TYPES_FEATURES_EXT; 5134 VkPhysicalDeviceShaderFloat8FeaturesEXT shader_float8_features {}; 5135 shader_float8_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT8_FEATURES_EXT; 5136 if (ocp_microscaling_extension) { 5137 last_struct->pNext = (VkBaseOutStructure *)&ocp_microscaling_features; 5138 last_struct = (VkBaseOutStructure *)&ocp_microscaling_features; 5139 } 5140 if (shader_float8_extension) { 5141 last_struct->pNext = (VkBaseOutStructure *)&shader_float8_features; 5142 last_struct = (VkBaseOutStructure *)&shader_float8_features; 5143 } 5144 #endif 5145 5146 vkGetPhysicalDeviceFeatures2(physical_device, &device_features2); 5147 5148 fp16 = fp16 && vk12_features.shaderFloat16; 5149 5150 #if defined(VK_KHR_shader_bfloat16) 5151 bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type; 5152 #else 5153 bool bf16 = false; 5154 #endif 5155 5156 uint32_t default_subgroup_size = get_subgroup_size("", device_architecture); 5157 const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize; 5158 const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu; 5159 5160 integer_dot_product = integer_dot_product 5161 && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated 5162 && shader_integer_dot_product_features.shaderIntegerDotProduct; 5163 5164 coopmat_support = coopmat_support 5165 #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 5166 && coopmat_features.cooperativeMatrix 5167 #endif 5168 && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture); 5169 5170 #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) 5171 coopmat2_support = coopmat2_support && 5172 coopmat2_features.cooperativeMatrixWorkgroupScope && 5173 coopmat2_features.cooperativeMatrixFlexibleDimensions && 5174 coopmat2_features.cooperativeMatrixReductions && 5175 coopmat2_features.cooperativeMatrixConversions && 5176 coopmat2_features.cooperativeMatrixPerElementOperations && 5177 coopmat2_features.cooperativeMatrixTensorAddressing && 5178 coopmat2_features.cooperativeMatrixBlockLoads; 5179 #else 5180 coopmat2_support = false; 5181 #endif 5182 5183 coopmat2_decode_vector_support = coopmat2_decode_vector_support && coopmat2_decode_vector_features.cooperativeMatrixDecodeVector; 5184 #if !defined(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) 5185 coopmat2_decode_vector_support = false; 5186 #endif 5187 5188 std::string matrix_cores = coopmat2_support ? (coopmat2_decode_vector_support ? "NV_coopmat2v" : "NV_coopmat2") 5189 : coopmat_support ? "KHR_coopmat" 5190 : "none"; 5191 5192 bool dot2_f16 = dot2_f16_support && dot2_features.shaderMixedFloatDotProductFloat16AccFloat32; 5193 const char *fp16_str = fp16 ? (dot2_f16 ? "dot2" : "1") : "0"; 5194 #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) 5195 const bool fp4 = ocp_microscaling_extension && ocp_microscaling_features.shaderFloat4 && 5196 shader_float8_extension && shader_float8_features.shaderFloat8 && 5197 !getenv("GGML_VK_DISABLE_OCP_FP4"); 5198 #else 5199 GGML_UNUSED(ocp_microscaling_extension); 5200 GGML_UNUSED(shader_float8_extension); 5201 const bool fp4 = false; 5202 #endif 5203 5204 std::string device_name = props2.properties.deviceName.data(); 5205 GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %s | bf16: %d | fp4: %d | warp size: %zu | shared memory: %d | int dot: %d | matrix cores: %s\n", 5206 idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16_str, bf16, fp4, subgroup_size, 5207 props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str()); 5208 5209 if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) { 5210 GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n"); 5211 } 5212 } 5213 5214 static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance; 5215 5216 DispatchLoaderDynamic & ggml_vk_default_dispatcher() { 5217 return ggml_vk_default_dispatcher_instance; 5218 } 5219 5220 void ggml_vk_instance_init() { 5221 if (vk_instance_initialized) { 5222 return; 5223 } 5224 VK_LOG_DEBUG("ggml_vk_instance_init()"); 5225 5226 // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers- 5227 ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr); 5228 5229 // vkEnumerateInstanceVersion is Vulkan 1.1. A null value indicated Vulkan 1.0. 5230 if (ggml_vk_default_dispatcher_instance.vkEnumerateInstanceVersion == nullptr) { 5231 GGML_LOG_ERROR("ggml_vulkan: Error: Vulkan 1.2 required."); 5232 throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required"); 5233 } 5234 5235 uint32_t api_version = vk::enumerateInstanceVersion(); 5236 5237 if (api_version < VK_API_VERSION_1_2) { 5238 GGML_LOG_ERROR("ggml_vulkan: Error: Vulkan 1.2 required."); 5239 throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required"); 5240 } 5241 5242 vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version }; 5243 5244 const std::vector instance_extensions = vk::enumerateInstanceExtensionProperties(); 5245 const bool layer_settings = ggml_vk_instance_layer_settings_available(); 5246 #ifdef __APPLE__ 5247 const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions); 5248 #endif 5249 const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr; 5250 std::vector layers; 5251 5252 if (layer_settings) { 5253 layers.push_back("VK_LAYER_KHRONOS_validation"); 5254 } 5255 std::vector extensions; 5256 if (layer_settings) { 5257 extensions.push_back("VK_EXT_layer_settings"); 5258 } 5259 #ifdef __APPLE__ 5260 if (portability_enumeration_ext) { 5261 extensions.push_back("VK_KHR_portability_enumeration"); 5262 } 5263 #endif 5264 if (debug_utils_ext) { 5265 extensions.push_back("VK_EXT_debug_utils"); 5266 } 5267 VkBool32 enable_best_practice = layer_settings; 5268 std::vector settings = { 5269 { 5270 "VK_LAYER_KHRONOS_validation", 5271 "validate_best_practices", 5272 vk::LayerSettingTypeEXT::eBool32, 5273 1, 5274 &enable_best_practice 5275 }, 5276 }; 5277 vk::LayerSettingsCreateInfoEXT layer_setting_info(settings); 5278 vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions, &layer_setting_info); 5279 #ifdef __APPLE__ 5280 if (portability_enumeration_ext) { 5281 instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR; 5282 } 5283 #endif 5284 5285 vk_instance.instance = vk::createInstance(instance_create_info); 5286 vk_instance_initialized = true; 5287 5288 if (debug_utils_ext) { 5289 vk_instance.debug_utils_support = true; 5290 vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT"); 5291 vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT"); 5292 vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT"); 5293 vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT"); 5294 vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT"); 5295 vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT"); 5296 } 5297 5298 vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr; 5299 vk_perf_logger_concurrent = getenv("GGML_VK_PERF_LOGGER_CONCURRENT") != nullptr; 5300 vk_enable_sync_logger = getenv("GGML_VK_SYNC_LOGGER") != nullptr; 5301 vk_memory_logger_enabled = getenv("GGML_VK_MEMORY_LOGGER") != nullptr; 5302 vk_instance.allreduce_disabled = getenv("GGML_VK_DISABLE_ALLREDUCE") != nullptr; 5303 const char* GGML_VK_PIPELINE_STATS = getenv("GGML_VK_PIPELINE_STATS"); 5304 if (GGML_VK_PIPELINE_STATS != nullptr) { 5305 vk_pipeline_stats_filter = GGML_VK_PIPELINE_STATS; 5306 } 5307 const char* GGML_VK_PERF_LOGGER_FREQUENCY = getenv("GGML_VK_PERF_LOGGER_FREQUENCY"); 5308 5309 if (GGML_VK_PERF_LOGGER_FREQUENCY != nullptr) { 5310 vk_perf_logger_frequency = std::stoul(GGML_VK_PERF_LOGGER_FREQUENCY); 5311 } 5312 5313 // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers- 5314 VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance); 5315 5316 std::vector devices = vk_instance.instance.enumeratePhysicalDevices(); 5317 5318 // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan 5319 char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES"); 5320 if (devices_env != nullptr) { 5321 size_t num_available_devices = devices.size(); 5322 5323 std::string devices(devices_env); 5324 std::replace(devices.begin(), devices.end(), ',', ' '); 5325 5326 std::stringstream ss(devices); 5327 size_t tmp; 5328 while (ss >> tmp) { 5329 if(tmp >= num_available_devices) { 5330 std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl; 5331 throw std::runtime_error("Invalid Vulkan device index"); 5332 } 5333 vk_instance.device_indices.push_back(tmp); 5334 } 5335 } else { 5336 // If no vulkan devices are found, return early 5337 if (devices.empty()) { 5338 GGML_LOG_INFO("ggml_vulkan: No devices found.\n"); 5339 return; 5340 } 5341 5342 // Default to using all dedicated GPUs 5343 for (size_t i = 0; i < devices.size(); i++) { 5344 vk::PhysicalDeviceProperties2 new_props; 5345 vk::PhysicalDeviceDriverProperties new_driver; 5346 vk::PhysicalDeviceIDProperties new_id; 5347 new_props.pNext = &new_driver; 5348 new_driver.pNext = &new_id; 5349 devices[i].getProperties2(&new_props); 5350 5351 if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) { 5352 // Check if there are two physical devices corresponding to the same GPU 5353 // This handles the case where the same GPU appears with different drivers (e.g., RADV + AMDVLK on Linux), 5354 // see https://github.com/ggml-org/llama.cpp/pull/7582 for original deduplication. 5355 // MoltenVK on macOS may report the same UUID for distinct GPUs on multi-GPU cards, 5356 // see https://github.com/KhronosGroup/MoltenVK/issues/2683. Skip when both old/new 5357 // driver is MoltenVK 5358 auto old_device = std::find_if( 5359 vk_instance.device_indices.begin(), 5360 vk_instance.device_indices.end(), 5361 [&devices, &new_id, &new_driver](const size_t k){ 5362 vk::PhysicalDeviceProperties2 old_props; 5363 vk::PhysicalDeviceDriverProperties old_driver; 5364 vk::PhysicalDeviceIDProperties old_id; 5365 old_props.pNext = &old_driver; 5366 old_driver.pNext = &old_id; 5367 devices[k].getProperties2(&old_props); 5368 5369 bool same_uuid = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID)); 5370 same_uuid = same_uuid || ( 5371 old_id.deviceLUIDValid && new_id.deviceLUIDValid && 5372 std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID)) 5373 ); 5374 bool both_molten_vk = (new_driver.driverID == vk::DriverId::eMoltenvk && old_driver.driverID == vk::DriverId::eMoltenvk); 5375 5376 return same_uuid && !both_molten_vk; 5377 } 5378 ); 5379 if (old_device == vk_instance.device_indices.end()) { 5380 vk_instance.device_indices.push_back(i); 5381 } else { 5382 // There can be two physical devices corresponding to the same GPU if there are 2 different drivers 5383 // This can cause error when splitting layers aross the devices, need to keep only 1 5384 VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID"); 5385 5386 vk::PhysicalDeviceProperties2 old_props; 5387 vk::PhysicalDeviceDriverProperties old_driver; 5388 old_props.pNext = &old_driver; 5389 devices[*old_device].getProperties2(&old_props); 5390 5391 std::map driver_priorities {}; 5392 int old_priority = std::numeric_limits::max(); 5393 int new_priority = std::numeric_limits::max(); 5394 5395 // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id 5396 // Smaller number -> higher priority 5397 switch (old_props.properties.vendorID) { 5398 case VK_VENDOR_ID_AMD: 5399 driver_priorities[vk::DriverId::eMesaRadv] = 1; 5400 driver_priorities[vk::DriverId::eAmdOpenSource] = 2; 5401 driver_priorities[vk::DriverId::eAmdProprietary] = 3; 5402 break; 5403 case VK_VENDOR_ID_INTEL: 5404 driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1; 5405 driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2; 5406 break; 5407 case VK_VENDOR_ID_NVIDIA: 5408 driver_priorities[vk::DriverId::eNvidiaProprietary] = 1; 5409 #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235 5410 driver_priorities[vk::DriverId::eMesaNvk] = 2; 5411 #endif 5412 break; 5413 case VK_VENDOR_ID_QUALCOMM: 5414 driver_priorities[vk::DriverId::eQualcommProprietary] = 1; 5415 driver_priorities[vk::DriverId::eMesaTurnip] = 2; 5416 break; 5417 } 5418 driver_priorities[vk::DriverId::eMesaDozen] = 100; 5419 5420 if (driver_priorities.count(old_driver.driverID)) { 5421 old_priority = driver_priorities[old_driver.driverID]; 5422 } 5423 if (driver_priorities.count(new_driver.driverID)) { 5424 new_priority = driver_priorities[new_driver.driverID]; 5425 } 5426 5427 if (new_priority < old_priority) { 5428 auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device); 5429 vk_instance.device_indices.erase(r, vk_instance.device_indices.end()); 5430 vk_instance.device_indices.push_back(i); 5431 5432 VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName); 5433 } 5434 else { 5435 VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl); 5436 } 5437 } 5438 } 5439 } 5440 5441 // If no GPUs found, fall back to the first non-CPU device. 5442 // If only CPU devices are available, return without devices. 5443 if (vk_instance.device_indices.empty()) { 5444 for (size_t i = 0; i < devices.size(); i++) { 5445 if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) { 5446 vk_instance.device_indices.push_back(i); 5447 break; 5448 } 5449 } 5450 } 5451 5452 if (vk_instance.device_indices.empty()) { 5453 GGML_LOG_INFO("ggml_vulkan: No devices found.\n"); 5454 return; 5455 } 5456 } 5457 GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size()); 5458 5459 size_t host_buffer_import_count = 0; 5460 for (size_t i = 0; i < vk_instance.device_indices.size(); i++) { 5461 vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]]; 5462 std::vector extensionprops = vkdev.enumerateDeviceExtensionProperties(); 5463 5464 bool membudget_supported = false; 5465 bool external_memory_host_supported = false; 5466 for (const auto & ext : extensionprops) { 5467 if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) { 5468 membudget_supported = true; 5469 } else if (strcmp("VK_EXT_external_memory_host", ext.extensionName) == 0) { 5470 external_memory_host_supported = true; 5471 } 5472 } 5473 5474 vk_instance.device_supports_membudget.push_back(membudget_supported); 5475 5476 bool host_buffer_import = false; 5477 if (external_memory_host_supported) { 5478 vk::PhysicalDeviceProperties2 props2; 5479 vk::PhysicalDeviceDriverProperties driver_props; 5480 vk::PhysicalDeviceExternalMemoryHostPropertiesEXT ext_props; 5481 props2.pNext = &driver_props; 5482 driver_props.pNext = &ext_props; 5483 vkdev.getProperties2(&props2); 5484 host_buffer_import = ggml_vk_external_memory_host_usable(driver_props.driverID) && 5485 ggml_vk_host_buffer_import_usable(props2.properties.vendorID); 5486 if (host_buffer_import) { 5487 vk_instance.host_import_alignment = std::max(vk_instance.host_import_alignment, ext_props.minImportedHostPointerAlignment); 5488 host_buffer_import_count++; 5489 } 5490 } 5491 vk_instance.device_host_buffer_import.push_back(host_buffer_import); 5492 5493 ggml_vk_print_gpu_info(i); 5494 } 5495 5496 vk_instance.multi_device = host_buffer_import_count > 1 && vk_instance.device_host_buffer_import[0]; 5497 } 5498 5499 void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) { 5500 VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")"); 5501 ggml_vk_instance_init(); 5502 GGML_ASSERT(idx < vk_instance.device_indices.size()); 5503 5504 ctx->name = GGML_VK_NAME + std::to_string(idx); 5505 5506 ctx->device = ggml_vk_get_device(idx); 5507 5508 ctx->semaphore_idx = 0; 5509 ctx->binary_semaphore_idx = 0; 5510 ctx->event_idx = 0; 5511 5512 ctx->prealloc_size_x = 0; 5513 ctx->prealloc_size_y = 0; 5514 ctx->prealloc_size_split_k = 0; 5515 // Fixed size of 1KB, for deterministic behavior 5516 ctx->prealloc_size_add_rms_partials = 1024; 5517 5518 ctx->fence = ctx->device->device.createFence({}); 5519 ctx->almost_ready_fence = ctx->device->device.createFence({}); 5520 5521 ctx->compute_cmd_pool.init(ctx->device, ctx->device->compute_queue.get()); 5522 if (ctx->device->async_use_transfer_queue) { 5523 vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 }; 5524 vk::SemaphoreCreateInfo ci{}; 5525 ci.setPNext(&tci); 5526 ctx->transfer_semaphore.s = ctx->device->device.createSemaphore(ci); 5527 ctx->transfer_semaphore.value = 0; 5528 5529 ctx->transfer_cmd_pool.init(ctx->device, ctx->device->transfer_queue.get()); 5530 } 5531 5532 if (vk_perf_logger_enabled) { 5533 ctx->perf_logger = std::unique_ptr(new vk_perf_logger()); 5534 } 5535 5536 #ifdef GGML_VULKAN_CHECK_RESULTS 5537 const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS"); 5538 vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks)); 5539 const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR"); 5540 vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor)); 5541 #endif 5542 } 5543 5544 vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) { 5545 VK_LOG_DEBUG("ggml_vk_get_to_fp16()"); 5546 switch (type) { 5547 case GGML_TYPE_F32: 5548 case GGML_TYPE_Q1_0: 5549 case GGML_TYPE_Q2_0: 5550 case GGML_TYPE_Q4_0: 5551 case GGML_TYPE_Q4_1: 5552 case GGML_TYPE_Q5_0: 5553 case GGML_TYPE_Q5_1: 5554 case GGML_TYPE_Q8_0: 5555 case GGML_TYPE_Q2_K: 5556 case GGML_TYPE_Q3_K: 5557 case GGML_TYPE_Q4_K: 5558 case GGML_TYPE_Q5_K: 5559 case GGML_TYPE_Q6_K: 5560 case GGML_TYPE_IQ1_S: 5561 case GGML_TYPE_IQ1_M: 5562 case GGML_TYPE_IQ2_XXS: 5563 case GGML_TYPE_IQ2_XS: 5564 case GGML_TYPE_IQ2_S: 5565 case GGML_TYPE_IQ3_XXS: 5566 case GGML_TYPE_IQ3_S: 5567 case GGML_TYPE_IQ4_XS: 5568 case GGML_TYPE_IQ4_NL: 5569 case GGML_TYPE_MXFP4: 5570 case GGML_TYPE_NVFP4: 5571 case GGML_TYPE_TQ1_0: 5572 case GGML_TYPE_TQ2_0: 5573 break; 5574 default: 5575 return nullptr; 5576 } 5577 5578 return ctx->device->pipeline_dequant[type]; 5579 } 5580 5581 static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols, uint32_t m, uint32_t k) { 5582 VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()"); 5583 GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1); 5584 GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols); 5585 5586 if (b_type == GGML_TYPE_Q8_1) { 5587 switch (a_type) { 5588 case GGML_TYPE_Q2_0: 5589 case GGML_TYPE_Q4_0: 5590 case GGML_TYPE_Q4_1: 5591 case GGML_TYPE_Q5_0: 5592 case GGML_TYPE_Q5_1: 5593 case GGML_TYPE_Q8_0: 5594 case GGML_TYPE_MXFP4: 5595 case GGML_TYPE_Q2_K: 5596 case GGML_TYPE_Q3_K: 5597 case GGML_TYPE_Q4_K: 5598 case GGML_TYPE_Q5_K: 5599 case GGML_TYPE_Q6_K: 5600 case GGML_TYPE_IQ1_S: 5601 case GGML_TYPE_IQ1_M: 5602 case GGML_TYPE_IQ4_XS: 5603 break; 5604 default: 5605 return nullptr; 5606 } 5607 } 5608 5609 switch (a_type) { 5610 case GGML_TYPE_F32: 5611 case GGML_TYPE_F16: 5612 case GGML_TYPE_BF16: 5613 case GGML_TYPE_Q1_0: 5614 case GGML_TYPE_Q2_0: 5615 case GGML_TYPE_Q4_0: 5616 case GGML_TYPE_Q4_1: 5617 case GGML_TYPE_Q5_0: 5618 case GGML_TYPE_Q5_1: 5619 case GGML_TYPE_Q8_0: 5620 case GGML_TYPE_Q2_K: 5621 case GGML_TYPE_Q3_K: 5622 case GGML_TYPE_Q4_K: 5623 case GGML_TYPE_Q5_K: 5624 case GGML_TYPE_Q6_K: 5625 case GGML_TYPE_IQ1_S: 5626 case GGML_TYPE_IQ1_M: 5627 case GGML_TYPE_IQ2_XXS: 5628 case GGML_TYPE_IQ2_XS: 5629 case GGML_TYPE_IQ2_S: 5630 case GGML_TYPE_IQ3_XXS: 5631 case GGML_TYPE_IQ3_S: 5632 case GGML_TYPE_IQ4_XS: 5633 case GGML_TYPE_IQ4_NL: 5634 case GGML_TYPE_MXFP4: 5635 case GGML_TYPE_NVFP4: 5636 case GGML_TYPE_TQ1_0: 5637 case GGML_TYPE_TQ2_0: 5638 break; 5639 default: 5640 return nullptr; 5641 } 5642 5643 // heuristic to choose workgroup size 5644 uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP; 5645 if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { 5646 // Prefer larger workgroups when M is small, to spread the work out more 5647 // and keep more SMs busy. 5648 // q6_k seems to prefer small workgroup size even for "medium" values of M. 5649 if (a_type == GGML_TYPE_Q6_K) { 5650 if (m < 4096 && k >= 1024) { 5651 dmmv_wg = DMMV_WG_SIZE_LARGE; 5652 } 5653 } else { 5654 if (m <= 8192 && k >= 1024) { 5655 dmmv_wg = DMMV_WG_SIZE_LARGE; 5656 } 5657 } 5658 } 5659 5660 if (b_type == GGML_TYPE_Q8_1) { 5661 if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { 5662 dmmv_wg = DMMV_WG_SIZE_SUBGROUP; 5663 } 5664 return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1]; 5665 } 5666 5667 return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[dmmv_wg][a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[dmmv_wg][a_type][num_cols-1]; 5668 } 5669 5670 static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t m, uint32_t k) { 5671 VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()"); 5672 GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1); 5673 5674 if (b_type == GGML_TYPE_Q8_1) { 5675 switch (a_type) { 5676 case GGML_TYPE_Q2_0: 5677 case GGML_TYPE_Q4_0: 5678 case GGML_TYPE_Q4_1: 5679 case GGML_TYPE_Q5_0: 5680 case GGML_TYPE_Q5_1: 5681 case GGML_TYPE_Q8_0: 5682 case GGML_TYPE_MXFP4: 5683 case GGML_TYPE_Q2_K: 5684 case GGML_TYPE_Q3_K: 5685 case GGML_TYPE_Q4_K: 5686 case GGML_TYPE_Q5_K: 5687 case GGML_TYPE_Q6_K: 5688 case GGML_TYPE_IQ1_S: 5689 case GGML_TYPE_IQ1_M: 5690 case GGML_TYPE_IQ4_XS: 5691 break; 5692 default: 5693 return nullptr; 5694 } 5695 } 5696 5697 switch (a_type) { 5698 case GGML_TYPE_F32: 5699 case GGML_TYPE_F16: 5700 case GGML_TYPE_BF16: 5701 case GGML_TYPE_Q1_0: 5702 case GGML_TYPE_Q2_0: 5703 case GGML_TYPE_Q4_0: 5704 case GGML_TYPE_Q4_1: 5705 case GGML_TYPE_Q5_0: 5706 case GGML_TYPE_Q5_1: 5707 case GGML_TYPE_Q8_0: 5708 case GGML_TYPE_Q2_K: 5709 case GGML_TYPE_Q3_K: 5710 case GGML_TYPE_Q4_K: 5711 case GGML_TYPE_Q5_K: 5712 case GGML_TYPE_Q6_K: 5713 case GGML_TYPE_IQ1_S: 5714 case GGML_TYPE_IQ1_M: 5715 case GGML_TYPE_IQ2_XXS: 5716 case GGML_TYPE_IQ2_XS: 5717 case GGML_TYPE_IQ2_S: 5718 case GGML_TYPE_IQ3_XXS: 5719 case GGML_TYPE_IQ3_S: 5720 case GGML_TYPE_IQ4_XS: 5721 case GGML_TYPE_IQ4_NL: 5722 case GGML_TYPE_MXFP4: 5723 case GGML_TYPE_NVFP4: 5724 case GGML_TYPE_TQ1_0: 5725 case GGML_TYPE_TQ2_0: 5726 break; 5727 default: 5728 return nullptr; 5729 } 5730 5731 // heuristic to choose workgroup size 5732 uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP; 5733 if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { 5734 // Prefer larger workgroups when M is small, to spread the work out more 5735 // and keep more SMs busy. 5736 // q6_k seems to prefer small workgroup size even for "medium" values of M. 5737 if (a_type == GGML_TYPE_Q6_K) { 5738 if (m < 4096 && k >= 1024) { 5739 dmmv_wg = DMMV_WG_SIZE_LARGE; 5740 } 5741 } else { 5742 if (m <= 8192 && k >= 1024) { 5743 dmmv_wg = DMMV_WG_SIZE_LARGE; 5744 } 5745 } 5746 } 5747 5748 if (b_type == GGML_TYPE_Q8_1) { 5749 if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) { 5750 dmmv_wg = DMMV_WG_SIZE_SUBGROUP; 5751 } 5752 return ctx->device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[dmmv_wg][a_type]; 5753 } 5754 5755 return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type]; 5756 } 5757 5758 vk_subbuffer ggml_vk_tensor_subbuffer( 5759 const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign) { 5760 5761 vk_buffer buffer = nullptr; 5762 size_t offset = 0; 5763 if (ctx->device->uma) { 5764 ggml_vk_host_get(ctx->device, tensor->data, buffer, offset); 5765 } 5766 if (!buffer) { 5767 auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context; 5768 buffer = buf_ctx->dev_buffer; 5769 offset = vk_tensor_offset(tensor) + tensor->view_offs; 5770 } 5771 GGML_ASSERT(buffer != nullptr); 5772 5773 size_t size = ggml_nbytes(tensor); 5774 5775 const size_t descriptor_offset = ggml_vk_descriptor_offset( 5776 offset, ctx->device->properties.limits.minStorageBufferOffsetAlignment, ggml_type_size(tensor->type)); 5777 const size_t misalign_bytes = offset - descriptor_offset; 5778 // The shader must support misaligned offsets when indexing into the buffer 5779 GGML_ASSERT(allow_misalign || misalign_bytes == 0); 5780 offset = descriptor_offset; 5781 size += misalign_bytes; 5782 5783 return vk_subbuffer{buffer, offset, size}; 5784 } 5785 5786 static vk_command_buffer* ggml_vk_get_or_create_cmd_buffer(vk_device& device, vk_command_pool& pool) { 5787 for (auto& cmd_buffer : pool.cmd_buffers) { 5788 if (!cmd_buffer.in_use) { 5789 cmd_buffer.use_counter++; 5790 cmd_buffer.in_use = true; 5791 return &cmd_buffer; 5792 } 5793 } 5794 return ggml_vk_create_cmd_buffer(device, pool); 5795 } 5796 5797 static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) { 5798 vk_submission s; 5799 s.buffer = ggml_vk_get_or_create_cmd_buffer(device, p); 5800 if (one_time) { 5801 s.buffer->buf.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit }); 5802 } else { 5803 s.buffer->buf.begin({ vk::CommandBufferUsageFlags{} }); 5804 } 5805 5806 return s; 5807 } 5808 5809 void ggml_vk_cmd_label_begin(vk::CommandBuffer buf, const char * name) { 5810 vk::DebugUtilsLabelEXT label = {}; 5811 label.pLabelName = name; 5812 label.color = std::array{1.0f, 1.0f, 1.0f, 1.0f}; 5813 vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT(buf, reinterpret_cast(&label)); 5814 } 5815 5816 void ggml_vk_ctx_end(vk_context& ctx) { 5817 VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")"); 5818 if (ctx->s == nullptr) { 5819 return; 5820 } 5821 5822 // close open labels so this buffer is balanced; reopened in ggml_vk_ctx_begin 5823 if (vk_instance.debug_utils_support) { 5824 for (size_t i = 0; i < ctx->debug_labels.size(); i++) { 5825 vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT(ctx->s->buffer->buf); 5826 } 5827 // the enclosing per-command-buffer region 5828 vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT(ctx->s->buffer->buf); 5829 } 5830 5831 ctx->s->buffer->buf.end(); 5832 ctx->s = nullptr; 5833 } 5834 5835 void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) { 5836 VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")"); 5837 if (subctx->s != nullptr) { 5838 ggml_vk_ctx_end(subctx); 5839 } 5840 5841 subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) }); 5842 subctx->s = subctx->seqs[subctx->seqs.size() - 1].data(); 5843 5844 if (vk_instance.debug_utils_support) { 5845 // outermost region, one per command buffer, so the gaps between submits stand out 5846 const std::string name = "submit " + std::to_string(device->debug_cmdbuf_idx++); 5847 ggml_vk_cmd_label_begin(subctx->s->buffer->buf, name.c_str()); 5848 5849 // reopen labels left open when the previous command buffer was submitted 5850 for (const std::string & label : subctx->debug_labels) { 5851 ggml_vk_cmd_label_begin(subctx->s->buffer->buf, label.c_str()); 5852 } 5853 } 5854 } 5855 5856 vk_context ggml_vk_get_compute_ctx(ggml_backend_vk_context * ctx) { 5857 vk_context result; 5858 if (!ctx->compute_ctx.expired()) { 5859 result = ctx->compute_ctx.lock(); 5860 } else { 5861 result = ggml_vk_create_context(ctx, ctx->compute_cmd_pool); 5862 5863 ctx->compute_ctx = result; 5864 ggml_vk_ctx_begin(ctx->device, result); 5865 } 5866 5867 if (ctx->device->async_use_transfer_queue && ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value) { 5868 result->s->wait_semaphores.push_back(ctx->transfer_semaphore); 5869 ctx->transfer_semaphore_last_submitted = ctx->transfer_semaphore.value; 5870 } 5871 5872 return result; 5873 } 5874 5875 vk_context ggml_vk_get_transfer_ctx(ggml_backend_vk_context * ctx) { 5876 vk_context result; 5877 if (!ctx->transfer_ctx.expired()) { 5878 result = ctx->transfer_ctx.lock(); 5879 } else { 5880 result = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool); 5881 5882 ctx->transfer_ctx = result; 5883 ggml_vk_ctx_begin(ctx->device, result); 5884 } 5885 5886 return result; 5887 } 5888 5889 bool ggml_vk_submit_transfer_ctx(ggml_backend_vk_context * ctx) { 5890 if (!ctx->device->async_use_transfer_queue || ctx->transfer_ctx.expired()) { 5891 return false; 5892 } 5893 5894 vk_context cpy_ctx = ctx->transfer_ctx.lock(); 5895 ggml_vk_ctx_end(cpy_ctx); 5896 5897 for (auto& cpy : cpy_ctx->in_memcpys) { 5898 memcpy(cpy.dst, cpy.src, cpy.n); 5899 } 5900 5901 ctx->transfer_semaphore.value++; 5902 cpy_ctx->seqs.back().back().signal_semaphores.push_back(ctx->transfer_semaphore); 5903 5904 ggml_vk_submit(cpy_ctx, {}); 5905 ctx->transfer_ctx.reset(); 5906 return true; 5907 } 5908 5909 size_t ggml_vk_align_size(size_t width, size_t align) { 5910 VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")"); 5911 return CEIL_DIV(width, align) * align; 5912 } 5913 5914 void deferred_memcpy(void * dst, const void * src, size_t size, std::vector* memcpys) { 5915 if (memcpys == nullptr) { 5916 memcpy(dst, src, size); 5917 } else { 5918 memcpys->emplace_back(dst, src, size); 5919 } 5920 } 5921 5922 void deferred_memset(void * dst, uint32_t val, size_t size, std::vector* memsets) { 5923 if (memsets == nullptr) { 5924 memset(dst, val, size); 5925 } else { 5926 memsets->emplace_back(dst, val, size); 5927 } 5928 } 5929 5930 static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, bool disable_split_k, const vk_pipeline& pipeline) { 5931 VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")"); 5932 5933 if (disable_split_k) { 5934 return 1; 5935 } 5936 5937 const bool rdna = ctx->device->architecture == AMD_RDNA3 || ctx->device->architecture == AMD_RDNA4; 5938 uint32_t split_k = 1; 5939 if (rdna && ctx->device->shader_core_count != 0 && k >= 2048 && n <= 32) { 5940 // Small n gives too few workgroups to hide latency, aim for 8 per CU. Small tiles are one subgroup each. 5941 const uint32_t tiles = CEIL_DIV(m, pipeline->wg_denoms[0]) * CEIL_DIV(n, pipeline->wg_denoms[1]); 5942 if (tiles < 4 * ctx->device->shader_core_count) { 5943 split_k = std::min(8u, CEIL_DIV(8 * ctx->device->shader_core_count, tiles)); 5944 } 5945 } 5946 5947 // On RDNA, also split when n <= 64 only partly fills one tile column. 5948 if (split_k == 1 && ctx->device->shader_core_count != 0 && (n >= pipeline->wg_denoms[1] || (rdna && n <= 64))) { 5949 // If k is 'large' and the SMs will fill less than halfway, use split_k. 5950 uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]); 5951 uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]); 5952 5953 if (k >= 2048) { 5954 if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) { 5955 split_k = ctx->device->shader_core_count / (m_tiles * n_tiles); 5956 } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) { 5957 split_k = 3; 5958 } 5959 // Cap the split at 8x. Unless k is huge this is a lot of overhead. 5960 split_k = std::min(split_k, 8u); 5961 } 5962 } 5963 5964 // ggml_vk_matmul will align the splits to be a multiple of 256. 5965 // If this rounded up size would cause the last split to be empty, 5966 // then reduce the split count. 5967 while (true) { 5968 if (split_k == 1) { 5969 break; 5970 } 5971 uint32_t k_split = CEIL_DIV(k, split_k); 5972 k_split = ROUNDUP_POW2(k_split, 256); 5973 if (k_split * (split_k - 1) < k) { 5974 break; 5975 } 5976 split_k--; 5977 } 5978 5979 return split_k; 5980 } 5981 5982 void ggml_vk_matmul( 5983 ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline, 5984 vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer, 5985 uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d, 5986 uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d, 5987 uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3, 5988 uint32_t padded_n, uint64_t b_col_bytes, uint64_t d_col_bytes) { 5989 VK_LOG_DEBUG("ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << (split_k_buffer.buffer != nullptr ? split_k_buffer.buffer->buffer : VK_NULL_HANDLE) << ", " << split_k_buffer.offset << ", " << split_k_buffer.size << "), m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ", padded_n: " << padded_n << ")"); 5990 if (split_k == 1) { 5991 // a small tile can still produce more workgroups than the device allows on the n axis: 5992 // split the dispatch into n-chunks, shifting the B and D column windows 5993 const uint64_t max_n = (uint64_t)ctx->device->properties.limits.maxComputeWorkGroupCount[1] * pipeline->wg_denoms[1]; 5994 const uint64_t n_chunks = CEIL_DIV(n, max_n); 5995 ggml_pipeline_request_descriptor_sets(ctx, pipeline, n_chunks * CEIL_DIV(batch, ctx->device->properties.limits.maxComputeWorkGroupCount[2])); 5996 5997 for (uint64_t n_base = 0; n_base < n; n_base += max_n) { 5998 const uint32_t n_chunk = (uint32_t) std::min(n - n_base, max_n); 5999 GGML_ASSERT(n_base * b_col_bytes < b.size && n_base * d_col_bytes < d.size); 6000 GGML_ASSERT(b.size != VK_WHOLE_SIZE && d.size != VK_WHOLE_SIZE); 6001 vk_subbuffer b_chunk = b; 6002 vk_subbuffer d_chunk = d; 6003 b_chunk.offset += n_base * b_col_bytes; 6004 b_chunk.size -= n_base * b_col_bytes; 6005 d_chunk.offset += n_base * d_col_bytes; 6006 d_chunk.size -= n_base * d_col_bytes; 6007 6008 uint32_t base_work_group_z = 0; 6009 while (base_work_group_z < batch) { 6010 uint32_t groups_z = std::min(batch - base_work_group_z, ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 6011 6012 const vk_mat_mat_push_constants pc = { m, n_chunk, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, base_work_group_z, batch, k, ne02, ne12, broadcast2, broadcast3, uint32_t(padded_n - n_base) }; 6013 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b_chunk, d_chunk }, pc, { m, n_chunk, groups_z }); 6014 base_work_group_z += groups_z; 6015 } 6016 } 6017 return; 6018 } 6019 6020 if (ctx->prealloc_split_k_need_sync) { 6021 ggml_vk_sync_buffers(ctx, subctx); 6022 } 6023 6024 GGML_ASSERT(batch_stride_d == m * n); 6025 6026 // Round the split size up to a multiple of 256 (k-quant alignment) 6027 uint32_t k_split = CEIL_DIV(k, split_k); 6028 k_split = ROUNDUP_POW2(k_split, 256); 6029 6030 ggml_pipeline_request_descriptor_sets(ctx, pipeline, CEIL_DIV(batch, ctx->device->properties.limits.maxComputeWorkGroupCount[2])); 6031 6032 uint32_t base_work_group_z = 0; 6033 while (base_work_group_z < batch) { 6034 uint32_t groups_z = std::min(batch - base_work_group_z, ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 6035 6036 const vk_mat_mat_push_constants pc1 = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, base_work_group_z, batch, k_split, ne02, ne12, broadcast2, broadcast3, padded_n }; 6037 // Make sure enough workgroups get assigned for split k to work 6038 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, groups_z }); 6039 base_work_group_z += groups_z; 6040 } 6041 ggml_vk_sync_buffers(ctx, subctx); 6042 const std::array pc2 = { (uint32_t)(m * n * batch), split_k }; 6043 ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 }); 6044 ctx->prealloc_split_k_need_sync = true; 6045 } 6046 6047 static bool ggml_vk_src1_prec_allows_q8(const ggml_tensor * dst) { 6048 switch (ggml_prec_get_src(dst, 1)) { 6049 case GGML_PREC_UNDEFINED: 6050 case GGML_PREC_Q8: 6051 case GGML_PREC_Q4: 6052 return true; 6053 case GGML_PREC_F32: 6054 case GGML_PREC_BF16: 6055 case GGML_PREC_F16: 6056 return false; 6057 } 6058 return false; 6059 } 6060 6061 static bool ggml_vk_prec_allows_f16acc(ggml_prec prec) { 6062 switch (prec) { 6063 case GGML_PREC_F32: 6064 case GGML_PREC_BF16: 6065 return false; 6066 case GGML_PREC_UNDEFINED: 6067 case GGML_PREC_F16: 6068 case GGML_PREC_Q8: 6069 case GGML_PREC_Q4: 6070 return true; 6071 } 6072 return false; 6073 } 6074 6075 static bool ggml_vk_get_mul_mat_mat_f16acc(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec acc_prec) { 6076 if (src0_type == GGML_TYPE_F32 || src0_type == GGML_TYPE_BF16) return false; 6077 if (src1_type == GGML_TYPE_Q8_1) return false; 6078 const bool prec_allows_f16 = ggml_vk_prec_allows_f16acc(acc_prec); 6079 if (src0_type == GGML_TYPE_F16) { 6080 return prec_allows_f16 && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support); 6081 } 6082 // quant types 6083 if (ctx->device->coopmat2) { 6084 return prec_allows_f16; 6085 } 6086 if (ctx->device->coopmat_support) { 6087 return ctx->device->fp16 && ctx->device->coopmat_acc_f16_support && prec_allows_f16; 6088 } 6089 return ctx->device->fp16 && prec_allows_f16; 6090 } 6091 6092 static const std::vector* ggml_vk_get_mul_mat_mat_pipeline_map( 6093 ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec, bool mul_mat_id = false) { 6094 bool f16acc = ggml_vk_get_mul_mat_mat_f16acc(ctx, src0_type, src1_type, prec); 6095 vk_matmul_pipeline_key key{src0_type, src1_type, mul_mat_id, f16acc}; 6096 auto it = ctx->device->pipeline_matmul.find(key); 6097 if (it == ctx->device->pipeline_matmul.end() || it->second.empty()) { 6098 // Try without f16acc 6099 if (f16acc) { 6100 key.f16acc = false; 6101 it = ctx->device->pipeline_matmul.find(key); 6102 if (it != ctx->device->pipeline_matmul.end() && !it->second.empty()) return &it->second; 6103 } 6104 return nullptr; 6105 } 6106 return &it->second; 6107 } 6108 6109 static vk_pipeline ggml_vk_guess_matmul_pipeline_map(ggml_backend_vk_context * ctx, 6110 const std::vector& configs, 6111 uint32_t m, uint32_t n, bool aligned, bool mul_mat_id) { 6112 auto& selector = mul_mat_id ? ctx->device->matmul_id_tile_selector : ctx->device->matmul_tile_selector; 6113 uint32_t idx = selector(m, n, 0, ctx->device->shader_core_count, configs); 6114 if (idx >= configs.size()) idx = (uint32_t)configs.size() - 1; 6115 return (aligned && configs[idx].aligned) ? configs[idx].aligned : configs[idx].unaligned; 6116 } 6117 6118 static uint32_t ggml_vk_guess_matmul_pipeline_align_map(ggml_backend_vk_context * ctx, 6119 const std::vector& configs, 6120 uint32_t m, uint32_t n, bool mul_mat_id) { 6121 auto& selector = mul_mat_id ? ctx->device->matmul_id_tile_selector : ctx->device->matmul_tile_selector; 6122 uint32_t idx = selector(m, n, 0, ctx->device->shader_core_count, configs); 6123 if (idx >= configs.size()) idx = (uint32_t)configs.size() - 1; 6124 return configs[idx].align; 6125 } 6126 6127 static uint64_t ggml_vk_mul_mat_id_max_tiles(uint64_t n_experts, uint64_t n_rows, uint32_t bn) { 6128 // Each nonempty expert can add at most one partial tile to the combined grid. 6129 return std::min(n_rows, CEIL_DIV(n_rows, bn) + std::min(n_experts, n_rows) - 1); 6130 } 6131 6132 static void ggml_vk_matmul_id( 6133 ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline, 6134 vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids, const vk_subbuffer & expert_count_buf, 6135 uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d, 6136 uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d, 6137 uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11, 6138 uint32_t row_ids_offset, uint32_t max_tiles) { 6139 VK_LOG_DEBUG("ggml_vk_matmul_id(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), ids: (" << ids.buffer->buffer << ", " << ids.offset << ", " << ids.size << "), expert_count: (" << expert_count_buf.buffer->buffer << ", " << expert_count_buf.offset << ", " << expert_count_buf.size << "), " << 6140 "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " << 6141 "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " << 6142 "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")"); 6143 const vk_mat_mat_id_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, 6144 nei0, nei1, nbi1, ne11, n_as, row_ids_offset }; 6145 const uint32_t tiles_y = std::min(max_tiles, ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 6146 const std::array elements = { m, tiles_y * pipeline->wg_denoms[1], uint32_t(CEIL_DIV(max_tiles, tiles_y)) }; 6147 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids, expert_count_buf }, pc, elements); 6148 } 6149 6150 bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) { 6151 return 6152 tensor->nb[0] == ggml_type_size(tensor->type) && 6153 tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) && 6154 (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]); 6155 } 6156 6157 // Batch stride in elements of a tensor read in place. 6158 static uint32_t ggml_vk_batch_stride(const ggml_tensor * tensor) { 6159 return (uint32_t)(tensor->nb[2] / ggml_type_size(tensor->type) * ggml_blck_size(tensor->type)); 6160 } 6161 6162 vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) { 6163 6164 // Choose "contiguous copy" shader if src/dst are contiguous 6165 bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst)); 6166 6167 // Use optimized "transpose" shader if src dim1 is the innermost dimension. 6168 bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src); 6169 6170 if (transpose && src->type == to) { 6171 if (ggml_type_size(to) == 4) { 6172 return ctx->device->pipeline_cpy_transpose_32; 6173 } else if (ggml_type_size(to) == 2) { 6174 return ctx->device->pipeline_cpy_transpose_16; 6175 } 6176 } 6177 6178 // Same, for a 0<->2 swap: src dim2 is the innermost dimension. 6179 bool transpose02 = dst && !contig && src->nb[2] == ggml_type_size(to) && 6180 ggml_is_contiguous(dst) && ggml_are_same_shape(dst, src); 6181 6182 if (transpose02 && src->type == to) { 6183 if (ggml_type_size(to) == 4) { 6184 return ctx->device->pipeline_cpy_transpose_02_32; 6185 } else if (ggml_type_size(to) == 2) { 6186 return ctx->device->pipeline_cpy_transpose_02_16; 6187 } 6188 } 6189 6190 if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) { 6191 if (contig) { 6192 return ctx->device->pipeline_contig_cpy_f32_f16; 6193 } else { 6194 return ctx->device->pipeline_cpy_f32_f16; 6195 } 6196 } 6197 if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) { 6198 if (contig) { 6199 return ctx->device->pipeline_contig_cpy_f16_f32; 6200 } else { 6201 return ctx->device->pipeline_cpy_f16_f32; 6202 } 6203 } 6204 if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) { 6205 if (contig) { 6206 return ctx->device->pipeline_contig_cpy_f32_bf16; 6207 } else { 6208 return ctx->device->pipeline_cpy_f32_bf16; 6209 } 6210 } 6211 if (src->type == GGML_TYPE_BF16 && to == GGML_TYPE_F32) { 6212 if (contig) { 6213 return ctx->device->pipeline_contig_cpy_bf16_f32; 6214 } else { 6215 return ctx->device->pipeline_cpy_bf16_f32; 6216 } 6217 } 6218 if (src->type == GGML_TYPE_BF16 && to == GGML_TYPE_F16) { 6219 if (contig) { 6220 return ctx->device->pipeline_contig_cpy_bf16_f16; 6221 } else { 6222 return ctx->device->pipeline_cpy_bf16_f16; 6223 } 6224 } 6225 if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) { 6226 if (contig) { 6227 return ctx->device->pipeline_contig_cpy_f32_i32; 6228 } else { 6229 return ctx->device->pipeline_cpy_f32_i32; 6230 } 6231 } 6232 if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) { 6233 if (contig) { 6234 return ctx->device->pipeline_contig_cpy_i32_f32; 6235 } else { 6236 return ctx->device->pipeline_cpy_i32_f32; 6237 } 6238 } 6239 if (src->type == GGML_TYPE_F32) { 6240 switch (to) { 6241 case GGML_TYPE_Q1_0: 6242 case GGML_TYPE_Q2_0: 6243 case GGML_TYPE_Q4_0: 6244 case GGML_TYPE_Q4_1: 6245 case GGML_TYPE_Q5_0: 6246 case GGML_TYPE_Q5_1: 6247 case GGML_TYPE_Q8_0: 6248 case GGML_TYPE_IQ4_NL: 6249 return ctx->device->pipeline_cpy_f32_quant[to]; 6250 default: 6251 break; 6252 } 6253 } 6254 6255 if (to == GGML_TYPE_F32) { 6256 switch (src->type) { 6257 case GGML_TYPE_Q1_0: 6258 case GGML_TYPE_Q2_0: 6259 case GGML_TYPE_Q4_0: 6260 case GGML_TYPE_Q4_1: 6261 case GGML_TYPE_Q5_0: 6262 case GGML_TYPE_Q5_1: 6263 case GGML_TYPE_Q8_0: 6264 case GGML_TYPE_IQ4_NL: 6265 return ctx->device->pipeline_cpy_quant_f32[src->type]; 6266 default: 6267 break; 6268 } 6269 } 6270 6271 if (src->type == to) { 6272 // Copy two or four bytes at a time, depending on block size. 6273 // For quantized types, we scale by block size/type size. But 6274 // this path is also used for bf16->bf16 for example, where the 6275 // type size must be exactly 2 or 4. 6276 GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4); 6277 if ((ggml_type_size(src->type) % 4) == 0) { 6278 if (contig) { 6279 return ctx->device->pipeline_contig_cpy_32; 6280 } else { 6281 return ctx->device->pipeline_cpy_32; 6282 } 6283 } else { 6284 if (contig) { 6285 return ctx->device->pipeline_contig_cpy_16; 6286 } else { 6287 return ctx->device->pipeline_cpy_16; 6288 } 6289 } 6290 } 6291 6292 std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl; 6293 GGML_ABORT("fatal error"); 6294 } 6295 6296 void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, const vk_subbuffer & in, const vk_subbuffer & out) { 6297 VK_LOG_DEBUG("ggml_vk_cpy_to_contiguous((" << tensor << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << "), "; 6298 std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")"); 6299 6300 const uint32_t ne = ggml_nelements(tensor); 6301 std::array elements; 6302 6303 if (ne > 262144) { 6304 elements = { 512, 512, CEIL_DIV(ne, 262144) }; 6305 } else if (ne > 512) { 6306 elements = { 512, CEIL_DIV(ne, 512), 1 }; 6307 } else { 6308 elements = { ne, 1, 1 }; 6309 } 6310 6311 vk_op_unary_push_constants pc = vk_op_unary_push_constants_init(tensor, tensor, ne); 6312 pc.nb10 = 1; 6313 pc.nb11 = (uint32_t)tensor->ne[0]; 6314 pc.nb12 = (uint32_t)(tensor->ne[0] * tensor->ne[1]); 6315 pc.nb13 = (uint32_t)(tensor->ne[0] * tensor->ne[1] * tensor->ne[2]); 6316 init_pushconst_fastdiv(pc); 6317 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements); 6318 ggml_vk_sync_buffers(ctx, subctx); 6319 } 6320 6321 static void ggml_vk_cpy_to_strided( 6322 ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, 6323 const vk_subbuffer & in, const vk_subbuffer & out, 6324 uint32_t nb10, uint32_t nb11, uint32_t nb12, uint32_t nb13) { 6325 VK_LOG_DEBUG("ggml_vk_cpy_to_strided((" << tensor << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << "), "; 6326 std::cerr << "dst_nb=(" << nb10 << ", " << nb11 << ", " << nb12 << ", " << nb13 << "), buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")"); 6327 6328 const uint32_t ne = ggml_nelements(tensor); 6329 std::array elements; 6330 6331 if (ne > 262144) { 6332 elements = { 512, 512, CEIL_DIV(ne, 262144) }; 6333 } else if (ne > 512) { 6334 elements = { 512, CEIL_DIV(ne, 512), 1 }; 6335 } else { 6336 elements = { ne, 1, 1 }; 6337 } 6338 6339 vk_op_unary_push_constants pc = vk_op_unary_push_constants_init(tensor, tensor, ne); 6340 pc.nb10 = nb10; 6341 pc.nb11 = nb11; 6342 pc.nb12 = nb12; 6343 pc.nb13 = nb13; 6344 init_pushconst_fastdiv(pc); 6345 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements); 6346 ggml_vk_sync_buffers(ctx, subctx); 6347 } 6348 6349 vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) { 6350 switch(type) { 6351 case GGML_TYPE_Q8_1: 6352 return ctx->device->pipeline_quantize_q8_1_x4; 6353 default: 6354 std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl; 6355 GGML_ABORT("fatal error"); 6356 } 6357 } 6358 6359 void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer & in, const vk_subbuffer & out, uint32_t ne) { 6360 VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")"); 6361 6362 vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1); 6363 6364 const uint32_t num_blocks = CEIL_DIV(ne, pipeline->wg_denoms[0]); 6365 // clamp the number of elements to the max workgroup count. The shader will iterate over the total number of blocks. 6366 const uint64_t max_elements = std::min(uint64_t{ctx->device->properties.limits.maxComputeWorkGroupCount[0]} * pipeline->wg_denoms[0], std::numeric_limits::max()); 6367 const uint32_t elements = std::min(ne, static_cast(max_elements)); 6368 6369 const vk_quantize_q8_1_push_constants pc = { 6370 ne, 6371 num_blocks, 6372 }; 6373 6374 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, { elements, 1, 1 }); 6375 ggml_vk_sync_buffers(ctx, subctx); 6376 } 6377 6378 static vk_pipeline ggml_vk_get_64b_indexing_pipeline(ggml_backend_vk_context * ctx, vk_pipeline &pipeline) { 6379 GGML_UNUSED(ctx); 6380 #if defined(VK_EXT_shader_64bit_indexing) 6381 vk_pipeline *ptr = &pipeline; 6382 while (*ptr) { 6383 if ((*ptr)->is_64b_indexing) { 6384 return *ptr; 6385 } 6386 ptr = &(*ptr)->next; 6387 } 6388 #endif 6389 return pipeline; 6390 } 6391 6392 // perf-heuristic for choosing mul_mat b type, based on shader availability 6393 static ggml_type ggml_vk_mul_mat_b_type( 6394 ggml_backend_vk_context * ctx, ggml_type src0_type, const ggml_tensor * src1, 6395 ggml_type f16_type, ggml_prec prec, bool mul_mat_id, bool can_quantize_y, bool prefer_f16_b) { 6396 auto available = [&](ggml_type b) { 6397 return ggml_vk_get_mul_mat_mat_pipeline_map(ctx, src0_type, b, prec, mul_mat_id) != nullptr; 6398 }; 6399 if (can_quantize_y && available(GGML_TYPE_Q8_1)) return GGML_TYPE_Q8_1; 6400 if (prefer_f16_b && available(f16_type)) return f16_type; 6401 if (ggml_vk_dim01_contiguous(src1) && available(src1->type)) return src1->type; 6402 if (src1->type == GGML_TYPE_BF16 && available(GGML_TYPE_F32)) return GGML_TYPE_F32; 6403 return f16_type; 6404 } 6405 6406 static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool disable_split_k) { 6407 VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << ggml_type_name(src0->type) << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; 6408 std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(src1->type) << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; 6409 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(dst->type) << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; 6410 std::cerr << "))"); 6411 GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT 6412 GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT 6413 6414 const uint64_t ne00 = src0->ne[0]; 6415 const uint64_t ne01 = src0->ne[1]; 6416 const uint64_t ne02 = src0->ne[2]; 6417 const uint64_t ne03 = src0->ne[3]; 6418 6419 const uint64_t ne10 = src1->ne[0]; 6420 const uint64_t ne11 = src1->ne[1]; 6421 const uint64_t ne12 = src1->ne[2]; 6422 const uint64_t ne13 = src1->ne[3]; 6423 6424 const uint64_t ne21 = dst->ne[1]; 6425 const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type); 6426 const uint32_t stride_batch_d = stride_d*ne21; 6427 6428 const uint64_t r2 = ne12 / ne02; 6429 const uint64_t r3 = ne13 / ne03; 6430 6431 ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; 6432 ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context; 6433 ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context; 6434 6435 vk_buffer d_Qx = nullptr; 6436 size_t qx_buf_offset = 0; 6437 vk_buffer d_Qy = nullptr; 6438 size_t qy_buf_offset = 0; 6439 6440 bool src0_uma = false; 6441 bool src1_uma = false; 6442 6443 if (ctx->device->uma) { 6444 ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset); 6445 ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset); 6446 src0_uma = d_Qx != nullptr; 6447 src1_uma = d_Qy != nullptr; 6448 } 6449 6450 const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) || 6451 !ggml_vk_dim01_contiguous(src0); 6452 // If src0 is BF16, try to use a BF16 x BF16 multiply 6453 ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16; 6454 6455 const bool is_coopmat = ctx->device->coopmat_support || ctx->device->coopmat2; 6456 const bool can_quantize_y = (ctx->device->integer_dot_product || ctx->device->coopmat_int_support) && 6457 src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst); 6458 // coopmat shaders are fast enough that memory bandwidth reduction from f16 activations helps 6459 const bool prefer_f16_b = is_coopmat && ggml_is_quantized(src0->type) && src1->type == GGML_TYPE_F32; 6460 6461 const ggml_type y_kernel_type = ggml_vk_mul_mat_b_type(ctx, src0->type, src1, f16_type, 6462 ggml_prec_get_acc(dst), false, can_quantize_y, prefer_f16_b); 6463 6464 const bool quantize_y = y_kernel_type == GGML_TYPE_Q8_1; 6465 const bool y_f32_kernel = y_kernel_type == GGML_TYPE_F32; 6466 const bool y_needs_reformat = !quantize_y && (!ggml_vk_dim01_contiguous(src1) || y_kernel_type != src1->type); 6467 6468 const std::vector* mmp_map = 6469 ggml_vk_get_mul_mat_mat_pipeline_map(ctx, src0->type, y_kernel_type, ggml_prec_get_acc(dst)); 6470 6471 const bool qx_needs_dequant = mmp_map == nullptr || x_non_contig; 6472 const bool qy_needs_dequant = y_needs_reformat; 6473 6474 if (qx_needs_dequant) { 6475 // dequant src0 to f16 6476 mmp_map = ggml_vk_get_mul_mat_mat_pipeline_map(ctx, f16_type, y_kernel_type, ggml_prec_get_acc(dst)); 6477 } 6478 6479 GGML_ASSERT(mmp_map != nullptr); 6480 6481 const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align_map(ctx, *mmp_map, ne01, ne11, false)); 6482 const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8; 6483 6484 vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *mmp_map, ne01, ne11, aligned, false); 6485 6486 if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { 6487 pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); 6488 } 6489 6490 // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking 6491 uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11; 6492 const uint64_t x_ne = ggml_nelements(src0); 6493 // 128 elements per Q8_1 x4 block 6494 const uint64_t y_ne = padded_n * ne10 * ne12 * ne13; 6495 const uint64_t d_ne = ggml_nelements(dst); 6496 6497 const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline); 6498 6499 const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type); 6500 const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type); 6501 const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne; 6502 const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); 6503 const uint64_t d_sz = sizeof(float) * d_ne; 6504 6505 vk_pipeline to_fp16_vk_0 = nullptr; 6506 vk_pipeline to_fp16_vk_1 = nullptr; 6507 vk_pipeline to_q8_1 = nullptr; 6508 6509 if (x_non_contig) { 6510 to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type); 6511 } else { 6512 to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type); 6513 } 6514 if (y_needs_reformat) { 6515 to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, y_kernel_type); 6516 } else { 6517 to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type); 6518 } 6519 GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT 6520 GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT 6521 6522 if (quantize_y) { 6523 to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1); 6524 } 6525 6526 { 6527 const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0; 6528 if ( 6529 (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || 6530 (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) || 6531 (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) { 6532 GGML_ABORT("Requested preallocation size is too large"); 6533 } 6534 if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) { 6535 ctx->prealloc_size_x = x_sz; 6536 ggml_vk_preallocate_buffers(ctx, subctx); 6537 } 6538 if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) { 6539 ctx->prealloc_size_y = y_sz; 6540 ggml_vk_preallocate_buffers(ctx, subctx); 6541 } 6542 if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) { 6543 ctx->prealloc_size_split_k = split_k_size; 6544 ggml_vk_preallocate_buffers(ctx, subctx); 6545 } 6546 6547 // Request descriptor sets 6548 if (qx_needs_dequant) { 6549 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1); 6550 } 6551 if (qy_needs_dequant) { 6552 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1); 6553 } 6554 if (quantize_y) { 6555 ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1); 6556 } 6557 if (split_k > 1) { 6558 ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1); 6559 } 6560 } 6561 6562 vk_buffer d_D = dst_buf_ctx->dev_buffer; 6563 const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs; 6564 GGML_ASSERT(d_D != nullptr); 6565 GGML_ASSERT(d_D->size >= d_buf_offset + d_sz); 6566 vk_buffer d_X; 6567 uint64_t x_buf_offset = 0; 6568 vk_buffer d_Y; 6569 uint64_t y_buf_offset = 0; 6570 if (!src0_uma) { 6571 d_Qx = src0_buf_ctx->dev_buffer; 6572 qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs; 6573 GGML_ASSERT(d_Qx != nullptr); 6574 } 6575 if (!src1_uma) { 6576 d_Qy = src1_buf_ctx->dev_buffer; 6577 qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs; 6578 GGML_ASSERT(d_Qy != nullptr); 6579 } 6580 if (qx_needs_dequant) { 6581 d_X = ctx->prealloc_x; 6582 GGML_ASSERT(d_X->size >= x_sz); 6583 } else { 6584 d_X = d_Qx; 6585 x_buf_offset = qx_buf_offset; 6586 GGML_ASSERT(qx_sz == x_sz); 6587 } 6588 if (qy_needs_dequant) { 6589 d_Y = ctx->prealloc_y; 6590 GGML_ASSERT(d_Y->size >= y_sz); 6591 } else if (quantize_y) { 6592 d_Y = ctx->prealloc_y; 6593 GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144); 6594 } else { 6595 d_Y = d_Qy; 6596 y_buf_offset = qy_buf_offset; 6597 GGML_ASSERT(qy_sz == y_sz); 6598 } 6599 6600 if (x_non_contig || qx_needs_dequant) { 6601 if (ctx->prealloc_x_need_sync) { 6602 ggml_vk_sync_buffers(ctx, subctx); 6603 } 6604 } 6605 6606 if (x_non_contig) { 6607 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0)); 6608 } else if (qx_needs_dequant) { 6609 const std::vector pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) }; 6610 ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)(x_ne), 1, 1}); 6611 ggml_vk_sync_buffers(ctx, subctx); 6612 } 6613 if (y_needs_reformat) { 6614 if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || 6615 ctx->prealloc_y_last_tensor_used != src1 || 6616 ctx->prealloc_y_last_k_padded) { 6617 if (ctx->prealloc_y_need_sync) { 6618 ggml_vk_sync_buffers(ctx, subctx); 6619 } 6620 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0)); 6621 ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); 6622 ctx->prealloc_y_last_tensor_used = src1; 6623 ctx->prealloc_y_last_k_padded = false; 6624 } 6625 } 6626 if (quantize_y) { 6627 if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || 6628 ctx->prealloc_y_last_tensor_used != src1 || 6629 ctx->prealloc_y_last_k_padded) { 6630 if (ctx->prealloc_y_need_sync) { 6631 ggml_vk_sync_buffers(ctx, subctx); 6632 } 6633 ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne); 6634 ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); 6635 ctx->prealloc_y_last_tensor_used = src1; 6636 ctx->prealloc_y_last_k_padded = false; 6637 } 6638 } 6639 6640 // The partial tiles of a quantized A rely on the bound range to read zeros past the last row, 6641 // so the range stays exact: the strided extent of a tensor read in place, the staged size otherwise. 6642 const uint64_t x_range = qx_needs_dequant ? x_sz : ggml_nbytes(src0); 6643 const uint64_t y_range = (qy_needs_dequant || quantize_y) ? y_sz : ggml_nbytes(src1); 6644 6645 uint32_t stride_batch_x = qx_needs_dequant ? ne00*ne01 : ggml_vk_batch_stride(src0); 6646 uint32_t stride_batch_y = (qy_needs_dequant || quantize_y) ? ne10*ne11 : ggml_vk_batch_stride(src1); 6647 6648 if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) { 6649 stride_batch_x = src0->nb[0] / ggml_type_size(src0->type); 6650 } 6651 6652 if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) { 6653 stride_batch_y = src1->nb[0] / ggml_type_size(src1->type); 6654 } 6655 6656 // column stride in bytes of the B buffer: raw src1 keeps its own stride, staging buffers are tightly packed 6657 const uint64_t b_col_bytes = (y_needs_reformat || qy_needs_dequant || quantize_y) 6658 ? (quantize_y ? (uint64_t)(ne10 / ggml_blck_size(GGML_TYPE_Q8_1)) * ggml_type_size(GGML_TYPE_Q8_1) : (uint64_t)ne10 * sizeof(ggml_fp16_t)) 6659 : (uint64_t)src1->nb[1]; 6660 6661 // compute 6662 ggml_vk_matmul( 6663 ctx, subctx, pipeline, 6664 { d_X, x_buf_offset, x_range }, { d_Y, y_buf_offset, y_range }, 6665 ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k }, 6666 ne01, ne11, ne10, 6667 ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d, 6668 split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n, 6669 b_col_bytes, (uint64_t)dst->nb[1] 6670 ); // NOLINT 6671 6672 if (x_non_contig || qx_needs_dequant) { 6673 ctx->prealloc_x_need_sync = true; 6674 } 6675 if (y_needs_reformat || quantize_y) { 6676 ctx->prealloc_y_need_sync = true; 6677 } 6678 } 6679 6680 static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) { 6681 if (device->mmvq_mode == 1) { 6682 return true; 6683 } else if (device->mmvq_mode == -1) { 6684 return false; 6685 } 6686 6687 // q6_k only has 2-byte alignment which makes it somewhat problematic, 6688 // using MMVQ is only a win on Intel. 6689 bool mmvq_q6 = device->vendor_id == VK_VENDOR_ID_INTEL; 6690 if (src0_type == GGML_TYPE_Q6_K && !mmvq_q6) { 6691 return false; 6692 } 6693 6694 // MMVQ is generally good for batches 6695 if (n > 1) { 6696 return true; 6697 } 6698 6699 // Quantization overhead is not worth it for small k 6700 switch (device->vendor_id) { 6701 case VK_VENDOR_ID_NVIDIA: 6702 if (src0_type == GGML_TYPE_Q2_0 || src0_type == GGML_TYPE_Q2_K || src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_IQ1_S || src0_type == GGML_TYPE_IQ1_M) { 6703 return true; 6704 } 6705 6706 if (k <= 4096) { 6707 return false; 6708 } 6709 6710 switch (src0_type) { 6711 case GGML_TYPE_MXFP4: 6712 case GGML_TYPE_Q8_0: 6713 return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING; 6714 default: 6715 return true; 6716 } 6717 case VK_VENDOR_ID_AMD: 6718 if (k < 2048) { 6719 return false; 6720 } 6721 6722 switch (src0_type) { 6723 case GGML_TYPE_Q8_0: 6724 return device->architecture == vk_device_architecture::AMD_GCN; 6725 default: 6726 return true; 6727 } 6728 case VK_VENDOR_ID_INTEL: 6729 if (device->architecture == vk_device_architecture::INTEL_XE2) { 6730 if (src0_type == GGML_TYPE_Q2_0 || src0_type == GGML_TYPE_Q2_K || src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K) { 6731 return true; 6732 } 6733 } 6734 6735 if (device->driver_id == vk::DriverId::eIntelProprietaryWindows) { 6736 // Intel Windows proprietary driver MMVQ performance for !Q2/Q3/Q6 is worse than fp16, 6737 // see https://github.com/ggml-org/llama.cpp/issues/17628 and 6738 // https://github.com/ggml-org/llama.cpp/pull/23056 6739 return false; 6740 } 6741 6742 if (k < 2048) { 6743 return false; 6744 } 6745 6746 switch (src0_type) { 6747 // From tests on A770 Linux, may need more tuning 6748 case GGML_TYPE_Q4_0: 6749 case GGML_TYPE_Q5_1: 6750 case GGML_TYPE_IQ4_XS: 6751 return false; 6752 default: 6753 return true; 6754 } 6755 case VK_VENDOR_ID_QUALCOMM: 6756 return false; 6757 default: 6758 return true; 6759 } 6760 6761 GGML_UNUSED(m); 6762 } 6763 6764 static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, bool swap_inputs = false) { 6765 ggml_tensor * dst = cgraph->nodes[node_idx]; 6766 const ggml_tensor * src0 = dst->src[swap_inputs ? 1 : 0]; 6767 const ggml_tensor * src1 = dst->src[swap_inputs ? 0 : 1]; 6768 6769 VK_LOG_DEBUG("ggml_vk_mul_mat_vec_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; 6770 std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; 6771 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; 6772 std::cerr << ")),)"); 6773 GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT 6774 GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT 6775 6776 const uint64_t ne00 = src0->ne[0]; 6777 const uint64_t ne01 = src0->ne[1]; 6778 const uint64_t ne02 = src0->ne[2]; 6779 const uint64_t ne03 = src0->ne[3]; 6780 6781 const uint64_t ne10 = src1->ne[0]; 6782 const uint64_t ne11 = src1->ne[1]; 6783 const uint64_t ne12 = src1->ne[2]; 6784 const uint64_t ne13 = src1->ne[3]; 6785 6786 const uint64_t ne20 = dst->ne[swap_inputs ? 1 : 0]; 6787 const uint64_t ne21 = dst->ne[swap_inputs ? 0 : 1]; 6788 // const uint64_t ne22 = dst->ne[2]; 6789 // const uint64_t ne23 = dst->ne[3]; 6790 6791 const uint64_t r2 = ne12 / ne02; 6792 const uint64_t r3 = ne13 / ne03; 6793 6794 // batch_n indicates that we need to compute a few vector results, and this assumes 6795 // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides. 6796 GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1); 6797 bool batch_n = ne11 > 1; 6798 6799 const bool x_non_contig = !ggml_vk_dim01_contiguous(src0); 6800 6801 // BF16 src1 has no mul_mat_vec B-type; widen to F32 6802 const bool widen_bf16 = src1->type == GGML_TYPE_BF16; 6803 const bool y_non_contig = !ggml_vk_dim01_contiguous(src1) || widen_bf16; 6804 6805 const ggml_type y_kernel_type = widen_bf16 ? GGML_TYPE_F32 : src1->type; 6806 const bool f16_f32_kernel = y_kernel_type == GGML_TYPE_F32; 6807 bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && (swap_inputs || ggml_vk_src1_prec_allows_q8(dst)) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type); 6808 6809 vk_pipeline to_fp16_vk_0 = nullptr; 6810 vk_pipeline to_fp16_vk_1 = nullptr; 6811 if (x_non_contig) { 6812 to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type); 6813 } 6814 if (y_non_contig) { 6815 to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, y_kernel_type); 6816 } else { 6817 to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type); 6818 } 6819 6820 // Check for mmq first 6821 vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr; 6822 vk_pipeline to_q8_1 = nullptr; 6823 6824 if (dmmv == nullptr) { 6825 // Fall back to f16 dequant mul mat 6826 dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, y_kernel_type, ne11, ne20, ne00); 6827 quantize_y = false; 6828 } 6829 6830 if (quantize_y) { 6831 to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1); 6832 } 6833 6834 if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { 6835 dmmv = ggml_vk_get_64b_indexing_pipeline(ctx, dmmv); 6836 } 6837 6838 const bool qx_needs_dequant = x_non_contig; 6839 const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig); 6840 6841 // Not implemented 6842 GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT 6843 6844 GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT 6845 GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT 6846 GGML_ASSERT(dmmv != nullptr); 6847 6848 const uint64_t x_ne = ggml_nelements(src0); 6849 const uint64_t y_ne = ggml_nelements(src1); 6850 6851 const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment); 6852 const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz; 6853 const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : 6854 (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); 6855 6856 { 6857 if ( 6858 (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || 6859 (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) { 6860 GGML_ABORT("Requested preallocation size is too large"); 6861 } 6862 if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) { 6863 ctx->prealloc_size_x = x_sz; 6864 ggml_vk_preallocate_buffers(ctx, subctx); 6865 } 6866 if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) { 6867 ctx->prealloc_size_y = y_sz; 6868 ggml_vk_preallocate_buffers(ctx, subctx); 6869 } 6870 6871 // Request descriptor sets 6872 if (qx_needs_dequant) { 6873 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1); 6874 } 6875 if (qy_needs_dequant) { 6876 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1); 6877 } 6878 if (quantize_y) { 6879 ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1); 6880 } 6881 } 6882 6883 vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]); 6884 vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0); 6885 vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1); 6886 vk_subbuffer d_X, d_Y; 6887 6888 if (qx_needs_dequant) { 6889 d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size }; 6890 } else { 6891 d_X = d_Qx; 6892 GGML_ASSERT(qx_sz == x_sz); 6893 } 6894 if (qy_needs_dequant || quantize_y) { 6895 d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size }; 6896 } else { 6897 d_Y = d_Qy; 6898 } 6899 6900 if (x_non_contig) { 6901 if (ctx->prealloc_x_need_sync) { 6902 ggml_vk_sync_buffers(ctx, subctx); 6903 } 6904 6905 GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment)); 6906 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X); 6907 } 6908 if (y_non_contig) { 6909 GGML_ASSERT(y_sz == ggml_type_size(y_kernel_type) * y_ne); 6910 if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || 6911 ctx->prealloc_y_last_tensor_used != src1 || 6912 ctx->prealloc_y_last_k_padded) { 6913 if (ctx->prealloc_y_need_sync) { 6914 ggml_vk_sync_buffers(ctx, subctx); 6915 } 6916 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y); 6917 ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); 6918 ctx->prealloc_y_last_tensor_used = src1; 6919 ctx->prealloc_y_last_k_padded = false; 6920 } 6921 } 6922 if (quantize_y) { 6923 if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || 6924 ctx->prealloc_y_last_tensor_used != src1 || 6925 ctx->prealloc_y_last_k_padded) { 6926 if (ctx->prealloc_y_need_sync) { 6927 ggml_vk_sync_buffers(ctx, subctx); 6928 } 6929 ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne); 6930 ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); 6931 ctx->prealloc_y_last_tensor_used = src1; 6932 ctx->prealloc_y_last_k_padded = false; 6933 } 6934 } 6935 6936 // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride 6937 uint32_t stride_batch_x = batch_n ? 0 : (qx_needs_dequant ? ne00*ne01 : ggml_vk_batch_stride(src0)); 6938 uint32_t stride_batch_y = batch_n ? ne10 : ((qy_needs_dequant || quantize_y) ? ne10*ne11 : ggml_vk_batch_stride(src1)); 6939 uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21); 6940 6941 if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) { 6942 stride_batch_x = src0->nb[0] / ggml_type_size(src0->type); 6943 } 6944 6945 if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) { 6946 stride_batch_y = src1->nb[0] / ggml_type_size(src1->type); 6947 } 6948 6949 const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0]; 6950 6951 uint32_t groups_x = ne01; 6952 uint32_t groups_z = 1; 6953 6954 if (ne01 > max_groups_x) { 6955 groups_z = 64; 6956 groups_x = CEIL_DIV(groups_x, groups_z); 6957 } 6958 6959 uint32_t fusion_flags = 0; 6960 6961 vk_subbuffer d_F0 = d_D; 6962 if (ctx->num_additional_fused_ops > 0) { 6963 const ggml_tensor * add = cgraph->nodes[node_idx + 1]; 6964 const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0]; 6965 6966 d_F0 = ggml_vk_tensor_subbuffer(ctx, bias); 6967 fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; 6968 } 6969 6970 vk_subbuffer d_F1 = d_D; 6971 if (ctx->num_additional_fused_ops == 2) { 6972 const ggml_tensor * add = cgraph->nodes[node_idx + 2]; 6973 const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0]; 6974 6975 d_F1 = ggml_vk_tensor_subbuffer(ctx, bias); 6976 fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1; 6977 } 6978 6979 ggml_pipeline_request_descriptor_sets(ctx, dmmv, CEIL_DIV(ne12 * ne13, ctx->device->properties.limits.maxComputeWorkGroupCount[1])); 6980 6981 uint32_t base_work_group_y = 0; 6982 while (base_work_group_y < ne12 * ne13) { 6983 6984 uint32_t groups_y = std::min((uint32_t)(ne12 * ne13) - base_work_group_y, ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 6985 const vk_mat_vec_push_constants pc = { 6986 (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01, 6987 stride_batch_x, stride_batch_y, stride_batch_d, 6988 fusion_flags, base_work_group_y, 6989 (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3, 6990 }; 6991 ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, 6992 { 6993 d_X, 6994 d_Y, 6995 d_D, 6996 d_F0, 6997 d_F1, 6998 }, 6999 pc, { groups_x, groups_y, groups_z }); 7000 base_work_group_y += groups_y; 7001 } 7002 7003 if (x_non_contig) { 7004 ctx->prealloc_x_need_sync = true; 7005 } 7006 if (y_non_contig || quantize_y) { 7007 ctx->prealloc_y_need_sync = true; 7008 } 7009 } 7010 7011 static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { 7012 ggml_tensor * dst = cgraph->nodes[node_idx]; 7013 const ggml_tensor * src0 = dst->src[0]; 7014 const ggml_tensor * src1 = dst->src[1]; 7015 VK_LOG_DEBUG("ggml_vk_mul_mat_p021_f16_f32(" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; 7016 std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; 7017 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; 7018 std::cerr << "))"); 7019 GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1)); 7020 GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT 7021 GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT 7022 GGML_ASSERT(src0->type == GGML_TYPE_F16); 7023 GGML_ASSERT(src1->type == GGML_TYPE_F32); 7024 7025 const uint64_t ne00 = src0->ne[0]; 7026 const uint64_t ne01 = src0->ne[1]; 7027 const uint64_t ne02 = src0->ne[2]; 7028 // const uint64_t ne03 = src0->ne[3]; 7029 7030 //const uint64_t ne10 = src1->ne[0]; 7031 const uint64_t ne11 = src1->ne[1]; 7032 const uint64_t ne12 = src1->ne[2]; 7033 // const uint64_t ne13 = src1->ne[3]; 7034 7035 GGML_ASSERT(ne11 == 1); 7036 7037 // With grouped query attention there are > 1 Q matrices per K, V matrix. 7038 uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02; 7039 if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) { 7040 gqa_ratio = 1; 7041 } 7042 7043 vk_pipeline pipeline = ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1]; 7044 7045 if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { 7046 pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); 7047 } 7048 7049 { 7050 // Request descriptor sets 7051 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 7052 } 7053 7054 vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true); 7055 vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0); 7056 vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true); 7057 7058 vk_subbuffer d_F0 = d_D; 7059 7060 uint32_t fusion_flags = 0; 7061 7062 if (ctx->num_additional_fused_ops > 0) { 7063 const ggml_tensor * add = cgraph->nodes[node_idx + 1]; 7064 const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0]; 7065 7066 d_F0 = ggml_vk_tensor_subbuffer(ctx, bias); 7067 fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; 7068 } 7069 7070 vk_subbuffer d_F1 = d_D; 7071 if (ctx->num_additional_fused_ops > 1) { 7072 const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1]; 7073 7074 d_F1 = ggml_vk_tensor_subbuffer(ctx, bias); 7075 fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1; 7076 } 7077 7078 // compute 7079 7080 vk_mat_vec_p021_push_constants pc = { 7081 (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12, 7082 0, 0, fusion_flags 7083 }; 7084 7085 init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]); 7086 7087 uint32_t workgroups_z = (uint32_t)ne12; 7088 // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups 7089 if (gqa_ratio > 1) { 7090 workgroups_z /= gqa_ratio; 7091 } 7092 7093 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 7094 { 7095 d_Qx, 7096 d_Qy, 7097 d_D, 7098 d_F0, 7099 d_F1, 7100 }, pc, { 1, (uint32_t)ne01, workgroups_z }); 7101 } 7102 7103 static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { 7104 ggml_tensor * dst = cgraph->nodes[node_idx]; 7105 const ggml_tensor * src0 = dst->src[0]; 7106 const ggml_tensor * src1 = dst->src[1]; 7107 VK_LOG_DEBUG("ggml_vk_mul_mat_nc_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; 7108 std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; 7109 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; 7110 std::cerr << "))"); 7111 GGML_ASSERT(!ggml_is_transposed(src0)); 7112 GGML_ASSERT(!ggml_is_transposed(src1)); 7113 GGML_ASSERT(!ggml_is_permuted(src0)); 7114 GGML_ASSERT(src0->type == GGML_TYPE_F16); 7115 GGML_ASSERT(src1->type == GGML_TYPE_F32); 7116 7117 const uint64_t ne00 = src0->ne[0]; 7118 const uint64_t ne01 = src0->ne[1]; 7119 const uint64_t ne02 = src0->ne[2]; 7120 const uint64_t ne03 = src0->ne[3]; 7121 7122 const uint64_t nb01 = src0->nb[1]; 7123 const uint64_t nb02 = src0->nb[2]; 7124 7125 const uint64_t nb12 = src1->nb[2]; 7126 7127 // const uint64_t ne10 = src1->ne[0]; 7128 const uint64_t ne11 = src1->ne[1]; 7129 const uint64_t ne12 = src1->ne[2]; 7130 // const uint64_t ne13 = src1->ne[3]; 7131 7132 const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t)); 7133 const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float)); 7134 const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float)); 7135 7136 GGML_ASSERT(ne11 == 1); 7137 GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in ggml_vk_mul_mat 7138 7139 const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t); 7140 const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t); 7141 const uint32_t channel_stride_y = nb12 / sizeof(float); 7142 7143 vk_pipeline pipeline = ctx->device->pipeline_mul_mat_vec_nc_f16_f32; 7144 if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { 7145 pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); 7146 } 7147 7148 { 7149 // Request descriptor sets 7150 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 7151 } 7152 7153 vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true); 7154 vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0); 7155 vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true); 7156 vk_subbuffer d_F0 = d_D; 7157 7158 uint32_t fusion_flags = 0; 7159 7160 if (ctx->num_additional_fused_ops > 0) { 7161 const ggml_tensor * add = cgraph->nodes[node_idx + 1]; 7162 const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0]; 7163 7164 d_F0 = ggml_vk_tensor_subbuffer(ctx, bias); 7165 fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; 7166 } 7167 7168 vk_subbuffer d_F1 = d_D; 7169 if (ctx->num_additional_fused_ops > 1) { 7170 const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1]; 7171 7172 d_F1 = ggml_vk_tensor_subbuffer(ctx, bias); 7173 fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1; 7174 } 7175 7176 // compute 7177 vk_mat_vec_nc_push_constants pc = { 7178 (uint32_t)ne00, (uint32_t)ne01, 7179 row_stride_x, channel_stride_x, channel_stride_y, 7180 (uint32_t)(ne12 / ne02), (uint32_t)ne12, 7181 0, 0, 7182 nb03, nb13, nb23, fusion_flags 7183 }; 7184 7185 init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]); 7186 7187 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 7188 { 7189 d_Qx, 7190 d_Qy, 7191 d_D, 7192 d_F0, 7193 d_F1, 7194 }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 }); 7195 } 7196 7197 static int ggml_vk_fwht_pipeline_idx(int64_t n) { 7198 switch (n) { 7199 case 64: return 0; 7200 case 128: return 1; 7201 case 256: return 2; 7202 case 512: return 3; 7203 default: return -1; 7204 } 7205 } 7206 7207 bool ggml_vk_can_use_fwht(const ggml_backend_vk_context * ctx, const ggml_tensor * src1, const ggml_tensor * dst) { 7208 if (ctx->num_additional_fused_ops != 0) { 7209 return false; 7210 } 7211 7212 if (ggml_get_op_params_i32(dst, 1) != GGML_HINT_SRC0_IS_HADAMARD) { 7213 return false; 7214 } 7215 7216 const int idx = ggml_vk_fwht_pipeline_idx(src1->ne[0]); 7217 if (idx < 0 || ctx->device->pipeline_fwht_f32[idx] == nullptr) { 7218 return false; 7219 } 7220 7221 if (src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { 7222 return false; 7223 } 7224 7225 if (!ggml_is_contiguous(src1)) { 7226 return false; 7227 } 7228 GGML_ASSERT(ggml_is_contiguous(dst)); 7229 7230 return true; 7231 } 7232 7233 void ggml_vk_fwht(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src, ggml_tensor * dst) { 7234 const int idx = ggml_vk_fwht_pipeline_idx(src->ne[0]); 7235 vk_pipeline pipeline = ctx->device->pipeline_fwht_f32[idx]; 7236 7237 const uint32_t rows_per_workgroup = 4; 7238 const uint32_t n_rows = (uint32_t)ggml_nrows(src); 7239 const uint32_t max_workgroups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0]; 7240 7241 const uint32_t total_workgroups = CEIL_DIV(n_rows, rows_per_workgroup); 7242 const uint32_t workgroups_x = std::min(total_workgroups, max_workgroups_x); 7243 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 7244 7245 const vk_subbuffer src_buf = ggml_vk_tensor_subbuffer(ctx, src, true); 7246 const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); 7247 7248 vk_op_fwht_push_constants pc = { 7249 n_rows, 7250 0, 7251 0, 7252 1.0f / std::sqrt((float)src->ne[0]), 7253 }; 7254 init_pushconst_tensor_offsets(ctx, pc, src, nullptr, nullptr, nullptr, dst); 7255 7256 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc, { workgroups_x, 1, 1 }); 7257 } 7258 7259 static uint32_t ggml_vk_nb_elem(const ggml_tensor * t, int i) { 7260 return (uint32_t)(t->nb[i] / ggml_type_size(t->type)); 7261 } 7262 7263 void ggml_vk_dsv4_hc_comb(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * mixes, const ggml_tensor * scale, const ggml_tensor * base, ggml_tensor * dst) { 7264 VK_LOG_DEBUG("ggml_vk_dsv4_hc_comb(" << mixes << ", " << scale << ", " << base << ", " << dst << ")"); 7265 7266 vk_pipeline pipeline = ctx->device->pipeline_dsv4_hc_comb_f32; 7267 GGML_ASSERT(pipeline != nullptr); 7268 7269 const uint32_t n_tokens = (uint32_t)mixes->ne[1]; 7270 7271 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 7272 7273 const vk_subbuffer mixes_buf = ggml_vk_tensor_subbuffer(ctx, mixes, true); 7274 const vk_subbuffer scale_buf = ggml_vk_tensor_subbuffer(ctx, scale, true); 7275 const vk_subbuffer base_buf = ggml_vk_tensor_subbuffer(ctx, base, true); 7276 const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); 7277 7278 vk_op_dsv4_hc_comb_push_constants pc = { 7279 n_tokens, 7280 ggml_vk_nb_elem(mixes, 0), ggml_vk_nb_elem(mixes, 1), 7281 ggml_vk_nb_elem(scale, 0), 7282 ggml_vk_nb_elem(base, 0), 7283 ggml_vk_nb_elem(dst, 0), ggml_vk_nb_elem(dst, 1), ggml_vk_nb_elem(dst, 2), 7284 0, 0, 0, 0, 7285 ggml_get_op_params_f32(dst, 0), 7286 (uint32_t)ggml_get_op_params_i32(dst, 1), 7287 }; 7288 init_pushconst_tensor_offsets(ctx, pc, mixes, scale, base, nullptr, dst); 7289 7290 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { mixes_buf, scale_buf, base_buf, dst_buf }, pc, { n_tokens, 1, 1 }); 7291 } 7292 7293 void ggml_vk_dsv4_hc_pre(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * x, const ggml_tensor * weights, ggml_tensor * dst) { 7294 VK_LOG_DEBUG("ggml_vk_dsv4_hc_pre(" << x << ", " << weights << ", " << dst << ")"); 7295 7296 const float scale = ggml_get_op_params_f32(dst, 0); 7297 const bool gated = ggml_get_op_params_i32(dst, 1) != 0; 7298 7299 vk_pipeline pipeline = gated ? ctx->device->pipeline_dsv4_hc_pre_gated_f32 : ctx->device->pipeline_dsv4_hc_pre_f32; 7300 GGML_ASSERT(pipeline != nullptr); 7301 7302 const uint32_t n_embd = (uint32_t)x->ne[0]; 7303 const uint32_t n_tokens = (uint32_t)x->ne[2]; 7304 7305 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 7306 7307 const vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x, true); 7308 const vk_subbuffer w_buf = ggml_vk_tensor_subbuffer(ctx, weights, true); 7309 const vk_subbuffer d_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); 7310 7311 vk_op_dsv4_hc_pre_push_constants pc = { 7312 n_embd, n_tokens, 7313 ggml_vk_nb_elem(x, 0), ggml_vk_nb_elem(x, 1), ggml_vk_nb_elem(x, 2), 7314 ggml_vk_nb_elem(weights, 0), ggml_vk_nb_elem(weights, 1), ggml_vk_nb_elem(weights, 2), 7315 ggml_vk_nb_elem(dst, 0), ggml_vk_nb_elem(dst, 1), 7316 0, 0, 0, 7317 scale, 7318 }; 7319 init_pushconst_tensor_offsets(ctx, pc, x, weights, nullptr, nullptr, dst); 7320 7321 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { x_buf, w_buf, d_buf }, pc, { n_embd, n_tokens, 1 }); 7322 } 7323 7324 void ggml_vk_dsv4_hc_post(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * x, const ggml_tensor * residual, const ggml_tensor * post, const ggml_tensor * comb, ggml_tensor * dst, const ggml_tensor * gate_scale_in) { 7325 VK_LOG_DEBUG("ggml_vk_dsv4_hc_post(" << x << ", " << residual << ", " << post << ", " << comb << ", " << dst << ")"); 7326 7327 vk_pipeline pipeline = comb ? ctx->device->pipeline_dsv4_hc_post_f32 : ctx->device->pipeline_dsv4_hc_post_nocomb_f32; 7328 GGML_ASSERT(pipeline != nullptr); 7329 7330 const uint32_t n_embd = (uint32_t)x->ne[0]; 7331 const uint32_t n_tokens = (uint32_t)x->ne[1]; 7332 7333 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 7334 7335 const vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x, true); 7336 const vk_subbuffer r_buf = ggml_vk_tensor_subbuffer(ctx, residual, true); 7337 // with a fused gate, post is scale(sigmoid(scale(p_src))) and the shader applies it to p_src 7338 const ggml_tensor * p_src = gate_scale_in ? gate_scale_in->src[0] : post; 7339 const vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p_src, true); 7340 const vk_subbuffer c_buf = comb ? ggml_vk_tensor_subbuffer(ctx, comb, true) : x_buf; 7341 const vk_subbuffer d_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); 7342 7343 vk_op_dsv4_hc_post_push_constants pc = { 7344 n_embd, n_tokens, 7345 ggml_vk_nb_elem(x, 0), ggml_vk_nb_elem(x, 1), 7346 ggml_vk_nb_elem(residual, 0), ggml_vk_nb_elem(residual, 1), ggml_vk_nb_elem(residual, 2), 7347 ggml_vk_nb_elem(p_src, 0), ggml_vk_nb_elem(p_src, 1), 7348 comb ? ggml_vk_nb_elem(comb, 0) : 0, comb ? ggml_vk_nb_elem(comb, 1) : 0, comb ? ggml_vk_nb_elem(comb, 2) : 0, 7349 ggml_vk_nb_elem(dst, 0), ggml_vk_nb_elem(dst, 1), ggml_vk_nb_elem(dst, 2), 7350 0, 0, 0, 0, 0, 7351 gate_scale_in ? 1u : 0u, 7352 gate_scale_in ? ggml_get_op_params_f32(gate_scale_in, 0) : 1.0f, 7353 gate_scale_in ? ggml_get_op_params_f32(post, 0) : 1.0f, 7354 }; 7355 init_pushconst_tensor_offsets(ctx, pc, x, residual, p_src, comb, dst); 7356 7357 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { x_buf, r_buf, p_buf, c_buf, d_buf }, pc, { n_embd, n_tokens, 1 }); 7358 } 7359 7360 void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { 7361 ggml_tensor * dst = cgraph->nodes[node_idx]; 7362 ggml_tensor * src0 = dst->src[0]; 7363 ggml_tensor * src1 = dst->src[1]; 7364 VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")"); 7365 7366 // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases 7367 // where the M dimension is very large. 7368 // Split_k doesn't work with M splitting. 7369 // This only supports batchsize == 1. 7370 const size_t nbytes = ggml_nbytes(src0); 7371 const bool needs_split = dst->ne[2] == 1 && dst->ne[3] == 1 && nbytes > ctx->device->properties.limits.maxStorageBufferRange; 7372 if (needs_split) { 7373 // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets) 7374 const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]); 7375 uint32_t m_offset = 0; 7376 while (m_offset < dst->ne[0]) { 7377 const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset)); 7378 ggml_tensor dst2 = *dst; 7379 ggml_tensor src02 = *src0; 7380 7381 dst2.view_src = dst->view_src ? dst->view_src : dst; 7382 src02.view_src = src0->view_src ? src0->view_src : src0; 7383 7384 dst2.view_offs += m_offset * dst->nb[0]; 7385 src02.view_offs += m_offset * src0->nb[1]; 7386 dst2.ne[0] = cur_M_size; 7387 src02.ne[1] = cur_M_size; 7388 7389 ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true); 7390 7391 m_offset += cur_M_size; 7392 } 7393 } else if (ggml_vk_can_use_fwht(ctx, src1, dst)) { 7394 ggml_vk_fwht(ctx, subctx, src1, dst); 7395 } else if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 && 7396 // detect 0213 permutation, and batch size of 1 7397 src0->nb[0] <= src0->nb[2] && 7398 src0->nb[2] <= src0->nb[1] && 7399 src0->nb[1] <= src0->nb[3] && 7400 src1->nb[0] <= src1->nb[2] && 7401 src1->nb[2] <= src1->nb[1] && 7402 src1->nb[1] <= src1->nb[3] && 7403 src0->ne[3] == 1 && 7404 src1->ne[3] == 1 && 7405 src0->ne[1] <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] && 7406 src1->ne[2] <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]) { 7407 ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx); 7408 } else if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 && 7409 !ggml_is_permuted(src0) && !ggml_is_permuted(src1) && src0->ne[3] == src1->ne[3] && 7410 src0->ne[3] <= ctx->device->properties.limits.maxComputeWorkGroupCount[0] && 7411 src0->ne[1] <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] && 7412 src1->ne[2] <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]) { 7413 ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx); 7414 // With one output row, B^T*A has the same flat output as A^T*B. 7415 } else if (ctx->num_additional_fused_ops == 0 && 7416 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) && 7417 (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16 || ggml_is_quantized(src1->type)) && 7418 dst->ne[0] == 1 && dst->ne[1] > mul_mat_vec_max_cols && 7419 src0->ne[2] == 1 && src0->ne[3] == 1 && 7420 src1->ne[2] == 1 && src1->ne[3] == 1 && 7421 ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) && 7422 get_misalign_bytes(ctx, src0) == 0 && get_misalign_bytes(ctx, src1) == 0 && get_misalign_bytes(ctx, dst) == 0) { 7423 ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx, true); 7424 // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four) 7425 // when ne12 and ne13 are one. 7426 } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) && 7427 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) { 7428 ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx); 7429 } else { 7430 ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false); 7431 } 7432 } 7433 7434 static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) { 7435 VK_LOG_DEBUG("ggml_vk_mul_mat_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; 7436 std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; 7437 std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3]; 7438 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3] << "),)"); 7439 GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT 7440 GGML_ASSERT(ids->type == GGML_TYPE_I32); 7441 7442 const uint64_t ne00 = src0->ne[0]; 7443 const uint64_t ne01 = src0->ne[1]; 7444 const uint64_t ne02 = src0->ne[2]; 7445 // const uint64_t ne03 = src0->ne[3]; 7446 7447 const uint64_t ne10 = src1->ne[0]; 7448 const uint64_t ne11 = src1->ne[1]; 7449 const uint64_t ne12 = src1->ne[2]; 7450 const uint64_t ne13 = src1->ne[3]; 7451 7452 const uint64_t nei0 = ids->ne[0]; 7453 const uint64_t nei1 = ids->ne[1]; 7454 7455 const uint32_t nbi0 = ids->nb[0]; 7456 const uint32_t nbi1 = ids->nb[1]; 7457 7458 const uint64_t ne20 = dst->ne[0]; 7459 const uint64_t ne21 = dst->ne[1]; 7460 // const uint64_t ne22 = dst->ne[2]; 7461 // const uint64_t ne23 = dst->ne[3]; 7462 7463 const uint64_t n_as = ne02; 7464 7465 ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; 7466 ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context; 7467 ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context; 7468 7469 vk_buffer d_Qx = nullptr; 7470 size_t qx_buf_offset = 0; 7471 vk_buffer d_Qy = nullptr; 7472 size_t qy_buf_offset = 0; 7473 7474 bool src0_uma = false; 7475 bool src1_uma = false; 7476 7477 if (ctx->device->uma) { 7478 ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset); 7479 ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset); 7480 src0_uma = d_Qx != nullptr; 7481 src1_uma = d_Qy != nullptr; 7482 } 7483 7484 // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf 7485 const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) || 7486 !ggml_vk_dim01_contiguous(src0); 7487 // If src0 is BF16, try to use a BF16 x BF16 multiply 7488 ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16; 7489 #if defined(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) 7490 // B must already be, or be convertible to, the matmul B type used by this path. 7491 const bool y_decode_vector_supported = ctx->device->coopmat2_decode_vector && 7492 (f16_type != GGML_TYPE_BF16 || ctx->device->coopmat2_bf16_support) && 7493 (src1->type == GGML_TYPE_F32 || src1->type == f16_type); 7494 // If B is copied to prealloc_y, we can choose a 4-element-aligned row stride. 7495 const bool y_decode_vector_uses_prealloc = !ggml_vk_dim01_contiguous(src1) || src1->type != f16_type; 7496 // Direct B reads are safe only if row starts and the original buffer offset are 4-element aligned. 7497 const bool y_decode_vector_aligned = 7498 (ne10 % 4 == 0) && 7499 (y_decode_vector_uses_prealloc || get_misalign_bytes(ctx, src1) % (4 * ggml_type_size(src1->type)) == 0); 7500 // Stage B only when decode-vector is available and direct B reads would be misaligned. 7501 const bool y_decode_vector_staging = y_decode_vector_supported && !y_decode_vector_aligned; 7502 #else 7503 const bool y_decode_vector_staging = false; 7504 #endif 7505 const bool can_quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && 7506 ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst); 7507 // Intel coopmat1 matrix cores prefer f16 activations for quantized weights 7508 const bool prefer_f16_b = ctx->device->coopmat_support && !ctx->device->coopmat2 && 7509 ctx->device->vendor_id == VK_VENDOR_ID_INTEL && 7510 ggml_is_quantized(src0->type) && src1->type == GGML_TYPE_F32; 7511 7512 const ggml_type y_kernel_type = ggml_vk_mul_mat_b_type(ctx, src0->type, src1, f16_type, 7513 ggml_prec_get_acc(dst), true, can_quantize_y, prefer_f16_b); 7514 7515 const bool quantize_y = y_kernel_type == GGML_TYPE_Q8_1; 7516 const bool y_f32_kernel = y_kernel_type == GGML_TYPE_F32; 7517 7518 const std::vector* mmp_map = 7519 ggml_vk_get_mul_mat_mat_pipeline_map(ctx, src0->type, y_kernel_type, ggml_prec_get_acc(dst), true); 7520 7521 const bool qx_needs_dequant = mmp_map == nullptr || x_non_contig; 7522 7523 if (qx_needs_dequant) { 7524 // dequant src0 to f16 7525 mmp_map = ggml_vk_get_mul_mat_mat_pipeline_map(ctx, f16_type, y_kernel_type, ggml_prec_get_acc(dst), true); 7526 } 7527 7528 GGML_ASSERT(mmp_map != nullptr); 7529 7530 // Coopmat2 MUL_MAT_ID BK specialization constants in ggml_vk_load_shaders are at most 64. 7531 const uint32_t y_staged_row_stride = ctx->device->coopmat2 && !quantize_y ? ggml_vk_align_size(ne10, 64) : ne10; 7532 const bool y_needs_k_padding = ne10 != y_staged_row_stride; 7533 7534 const bool y_needs_reformat = !quantize_y && (!ggml_vk_dim01_contiguous(src1) || y_kernel_type != src1->type || 7535 y_decode_vector_staging || y_needs_k_padding); 7536 const bool qy_needs_dequant = y_needs_reformat; 7537 7538 const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align_map(ctx, *mmp_map, ne01, nei1, true)); 7539 const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8; 7540 7541 vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *mmp_map, ne01, nei1, aligned, true); 7542 7543 const uint32_t bn = pipeline->wg_denoms[1]; 7544 const uint64_t max_tiles = ggml_vk_mul_mat_id_max_tiles(n_as, nei0 * nei1, bn); 7545 const uint64_t row_ids_offset = 1 + 2 * max_tiles; 7546 const uint64_t row_map_words = row_ids_offset + max_tiles * bn; 7547 7548 if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { 7549 pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); 7550 } 7551 const uint64_t x_ne = ggml_nelements(src0); 7552 const uint64_t y_ne = (uint64_t)y_staged_row_stride * ne11 * ne12 * ne13; 7553 const uint64_t d_ne = ggml_nelements(dst); 7554 7555 const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type); 7556 const uint64_t qy_sz = ggml_type_size(src1->type) * ggml_nelements(src1) / ggml_blck_size(src1->type); 7557 const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne; 7558 const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); 7559 const uint64_t d_sz = sizeof(float) * d_ne; 7560 7561 vk_pipeline to_fp16_vk_0 = nullptr; 7562 vk_pipeline to_fp16_vk_1 = nullptr; 7563 vk_pipeline to_q8_1 = nullptr; 7564 7565 auto make_y_staged_dst = [&]() { 7566 ggml_tensor y_staged_dst = *src1; 7567 y_staged_dst.type = f16_type; 7568 y_staged_dst.nb[0] = ggml_type_size(f16_type); 7569 y_staged_dst.nb[1] = y_staged_dst.nb[0] * y_staged_row_stride; 7570 y_staged_dst.nb[2] = y_staged_dst.nb[1] * ne11; 7571 y_staged_dst.nb[3] = y_staged_dst.nb[2] * y_staged_dst.ne[2]; 7572 return y_staged_dst; 7573 }; 7574 7575 if (x_non_contig) { 7576 to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type); 7577 } else { 7578 to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type); 7579 } 7580 if (y_needs_reformat) { 7581 ggml_tensor y_staged_dst; 7582 const ggml_tensor * y_staged_dst_ptr = nullptr; 7583 if (y_needs_k_padding) { 7584 y_staged_dst = make_y_staged_dst(); 7585 y_staged_dst_ptr = &y_staged_dst; 7586 } 7587 7588 to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, y_staged_dst_ptr, f16_type); 7589 } else { 7590 to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type); 7591 } 7592 GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT 7593 GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT 7594 7595 if (quantize_y) { 7596 to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1); 7597 } 7598 vk_pipeline count_experts = ctx->device->pipeline_count_experts; 7599 7600 const size_t expert_data_size = sizeof(uint32_t) * row_map_words; 7601 7602 { 7603 if ( 7604 (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || 7605 (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) { 7606 GGML_ABORT("Requested preallocation size is too large"); 7607 } 7608 if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) { 7609 ctx->prealloc_size_x = x_sz; 7610 ggml_vk_preallocate_buffers(ctx, subctx); 7611 } 7612 if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) { 7613 ctx->prealloc_size_y = y_sz; 7614 ggml_vk_preallocate_buffers(ctx, subctx); 7615 } 7616 if (ctx->prealloc_size_split_k < expert_data_size) { 7617 ctx->prealloc_size_split_k = expert_data_size; 7618 ggml_vk_preallocate_buffers(ctx, subctx); 7619 } 7620 7621 // Request descriptor sets 7622 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 7623 if (qx_needs_dequant) { 7624 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1); 7625 } 7626 if (qy_needs_dequant) { 7627 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1); 7628 } 7629 if (quantize_y) { 7630 ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1); 7631 } 7632 ggml_pipeline_request_descriptor_sets(ctx, count_experts, 1); 7633 } 7634 7635 vk_buffer d_D = dst_buf_ctx->dev_buffer; 7636 const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs; 7637 GGML_ASSERT(d_D != nullptr); 7638 vk_buffer d_X; 7639 uint64_t x_buf_offset = 0; 7640 vk_buffer d_Y; 7641 uint64_t y_buf_offset = 0; 7642 if (!src0_uma) { 7643 d_Qx = src0_buf_ctx->dev_buffer; 7644 qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs; 7645 GGML_ASSERT(d_Qx != nullptr); 7646 } 7647 if (!src1_uma) { 7648 d_Qy = src1_buf_ctx->dev_buffer; 7649 qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs; 7650 GGML_ASSERT(d_Qy != nullptr); 7651 } 7652 if (qx_needs_dequant) { 7653 d_X = ctx->prealloc_x; 7654 GGML_ASSERT(d_X->size >= x_sz); 7655 } else { 7656 d_X = d_Qx; 7657 x_buf_offset = qx_buf_offset; 7658 GGML_ASSERT(qx_sz == x_sz); 7659 } 7660 if (qy_needs_dequant) { 7661 d_Y = ctx->prealloc_y; 7662 GGML_ASSERT(d_Y->size >= y_sz); 7663 } else if (quantize_y) { 7664 d_Y = ctx->prealloc_y; 7665 GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144); 7666 } else { 7667 d_Y = d_Qy; 7668 y_buf_offset = qy_buf_offset; 7669 GGML_ASSERT(qy_sz == y_sz); 7670 } 7671 7672 if (x_non_contig || qx_needs_dequant) { 7673 if (ctx->prealloc_x_need_sync) { 7674 ggml_vk_sync_buffers(ctx, subctx); 7675 } 7676 } 7677 vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids, true); 7678 7679 // Count how many times each expert is used 7680 vk_subbuffer expert_count_buf = { ctx->prealloc_split_k, 0, expert_data_size }; 7681 if (ctx->prealloc_split_k_need_sync) { 7682 ggml_vk_sync_buffers(ctx, subctx); 7683 } 7684 { 7685 // this also zeroes the dst rows of the skipped slots (negative ids) 7686 vk_op_count_experts_push_constants pc = { (uint32_t)nei0, 7687 (uint32_t)nei1, 7688 (uint32_t)(nbi0 / ggml_type_size(ids->type)), 7689 (uint32_t)(nbi1 / ggml_type_size(ids->type)), 7690 (uint32_t)(get_misalign_bytes(ctx, ids) / ggml_type_size(ids->type)), 7691 (uint32_t)n_as, 7692 0, 0, bn, (uint32_t)row_ids_offset, 7693 (uint32_t)ne01, 7694 (uint32_t)(dst->nb[1] / sizeof(float)), 7695 (uint32_t)(dst->nb[2] / sizeof(float)) }; 7696 init_pushconst_fastdiv(pc); 7697 ggml_vk_dispatch_pipeline(ctx, subctx, count_experts, 7698 { d_ids, expert_count_buf, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, 7699 { 1, 1, 1 }); 7700 } 7701 7702 if (x_non_contig) { 7703 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0)); 7704 } else if (qx_needs_dequant) { 7705 const std::vector pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) }; 7706 ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, 7707 { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1}); 7708 } 7709 if (y_needs_reformat) { 7710 if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || 7711 ctx->prealloc_y_last_tensor_used != src1 || 7712 ctx->prealloc_y_last_k_padded != y_needs_k_padding) { 7713 if (ctx->prealloc_y_need_sync) { 7714 ggml_vk_sync_buffers(ctx, subctx); 7715 } 7716 if (y_needs_k_padding) { 7717 GGML_ASSERT(y_sz % 4 == 0); 7718 // Zero B padding because clamping only A can produce 0 * Inf or NaN. 7719 subctx->s->buffer->buf.fillBuffer(d_Y->buffer, 0, y_sz, 0); 7720 ggml_vk_sync_buffers(ctx, subctx); 7721 const ggml_tensor y_staged_dst = make_y_staged_dst(); 7722 const uint32_t y_staged_dst_type_size = ggml_type_size(y_staged_dst.type); 7723 ggml_vk_cpy_to_strided( 7724 ctx, subctx, to_fp16_vk_1, src1, 7725 ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), 7726 (uint32_t)(y_staged_dst.nb[0] / y_staged_dst_type_size), 7727 (uint32_t)(y_staged_dst.nb[1] / y_staged_dst_type_size), 7728 (uint32_t)(y_staged_dst.nb[2] / y_staged_dst_type_size), 7729 (uint32_t)(y_staged_dst.nb[3] / y_staged_dst_type_size)); 7730 } else { 7731 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0)); 7732 } 7733 ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); 7734 ctx->prealloc_y_last_tensor_used = src1; 7735 ctx->prealloc_y_last_k_padded = y_needs_k_padding; 7736 } 7737 } 7738 if (quantize_y) { 7739 if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || 7740 ctx->prealloc_y_last_tensor_used != src1 || 7741 ctx->prealloc_y_last_k_padded) { 7742 if (ctx->prealloc_y_need_sync) { 7743 ggml_vk_sync_buffers(ctx, subctx); 7744 } 7745 ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne); 7746 ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); 7747 ctx->prealloc_y_last_tensor_used = src1; 7748 ctx->prealloc_y_last_k_padded = false; 7749 } 7750 } 7751 ggml_vk_sync_buffers(ctx, subctx); 7752 7753 const uint64_t x_range = qx_needs_dequant ? x_sz : ggml_nbytes(src0); 7754 const uint64_t y_range = (qy_needs_dequant || quantize_y) ? y_sz : ggml_nbytes(src1); 7755 7756 uint32_t stride_batch_x = qx_needs_dequant ? ne00*ne01 : ggml_vk_batch_stride(src0); 7757 uint32_t stride_b_y = y_needs_k_padding ? y_staged_row_stride : ne10; 7758 uint32_t stride_batch_y = y_needs_k_padding ? y_staged_row_stride * ne11 : ((qy_needs_dequant || quantize_y) ? ne10*ne11 : ggml_vk_batch_stride(src1)); 7759 7760 if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) { 7761 stride_batch_x = src0->nb[0] / ggml_type_size(src0->type); 7762 } 7763 7764 if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) { 7765 stride_batch_y = src1->nb[0] / ggml_type_size(src1->type); 7766 } 7767 7768 // compute 7769 ggml_vk_matmul_id( 7770 ctx, subctx, pipeline, 7771 { d_X, x_buf_offset, x_range }, { d_Y, y_buf_offset, y_range }, 7772 { d_D, d_buf_offset, d_sz }, std::move(d_ids), expert_count_buf, 7773 ne01, ne21, ne10, ne10, stride_b_y, ne01, 7774 stride_batch_x, stride_batch_y, ne20*ne21, 7775 n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, row_ids_offset, max_tiles 7776 ); // NOLINT 7777 7778 if (x_non_contig || qx_needs_dequant) { 7779 ctx->prealloc_x_need_sync = true; 7780 } 7781 if (y_needs_reformat || quantize_y) { 7782 ctx->prealloc_y_need_sync = true; 7783 } 7784 ctx->prealloc_split_k_need_sync = true; 7785 } 7786 7787 static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { 7788 ggml_tensor * dst = cgraph->nodes[node_idx]; 7789 ggml_tensor * src0 = dst->src[0]; 7790 ggml_tensor * src1 = dst->src[1]; 7791 ggml_tensor * ids = dst->src[2]; 7792 VK_LOG_DEBUG("ggml_vk_mul_mat_vec_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; 7793 std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; 7794 std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3]; 7795 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; 7796 std::cerr << "))"); 7797 GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT 7798 GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT 7799 GGML_ASSERT(ids->type == GGML_TYPE_I32); 7800 7801 const uint64_t ne00 = src0->ne[0]; 7802 const uint64_t ne01 = src0->ne[1]; 7803 // const uint64_t ne02 = src0->ne[2]; 7804 // const uint64_t ne03 = src0->ne[3]; 7805 7806 const uint64_t ne10 = src1->ne[0]; 7807 const uint64_t ne11 = src1->ne[1]; 7808 const uint64_t ne12 = src1->ne[2]; 7809 // const uint64_t ne13 = src1->ne[3]; 7810 7811 const uint64_t nei0 = ids->ne[0]; 7812 const uint64_t nei1 = ids->ne[1]; 7813 const uint32_t nbi1 = (uint32_t)(ids->nb[1] / sizeof(int)); 7814 7815 const uint64_t ne20 = dst->ne[0]; 7816 const uint64_t ne21 = dst->ne[1]; 7817 // const uint64_t ne22 = dst->ne[2]; 7818 // const uint64_t ne23 = dst->ne[3]; 7819 7820 const bool x_non_contig = !ggml_vk_dim01_contiguous(src0); 7821 const bool y_non_contig = !ggml_vk_dim01_contiguous(src1); 7822 7823 const bool f16_f32_kernel = src1->type == GGML_TYPE_F32; 7824 bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne12, ne10, src0->type); 7825 7826 vk_pipeline to_fp16_vk_0 = nullptr; 7827 vk_pipeline to_fp16_vk_1 = nullptr; 7828 if (x_non_contig) { 7829 to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type); 7830 } 7831 if (y_non_contig) { 7832 to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type); 7833 } else { 7834 to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type); 7835 } 7836 7837 // Check for mmq first 7838 vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr; 7839 vk_pipeline to_q8_1 = nullptr; 7840 7841 if (dmmv == nullptr) { 7842 // Fall back to f16 dequant mul mat 7843 dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00); 7844 quantize_y = false; 7845 } 7846 7847 if (quantize_y) { 7848 to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1); 7849 } 7850 7851 const bool qx_needs_dequant = x_non_contig; 7852 const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig); 7853 7854 if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { 7855 dmmv = ggml_vk_get_64b_indexing_pipeline(ctx, dmmv); 7856 } 7857 7858 // Not implemented 7859 GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT 7860 GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT 7861 GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT 7862 GGML_ASSERT(dmmv != nullptr); 7863 7864 const uint64_t x_ne = ggml_nelements(src0); 7865 const uint64_t y_ne = ggml_nelements(src1); 7866 7867 const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment); 7868 const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz; 7869 const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : 7870 (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne); 7871 7872 { 7873 if ( 7874 (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || 7875 (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) { 7876 GGML_ABORT("Requested preallocation size is too large"); 7877 } 7878 if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) { 7879 ctx->prealloc_size_x = x_sz; 7880 ggml_vk_preallocate_buffers(ctx, subctx); 7881 } 7882 if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) { 7883 ctx->prealloc_size_y = y_sz; 7884 ggml_vk_preallocate_buffers(ctx, subctx); 7885 } 7886 7887 // Request descriptor sets 7888 if (qx_needs_dequant) { 7889 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1); 7890 } 7891 if (qy_needs_dequant) { 7892 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1); 7893 } 7894 if (quantize_y) { 7895 ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1); 7896 } 7897 ggml_pipeline_request_descriptor_sets(ctx, dmmv, nei1); 7898 } 7899 7900 vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]); 7901 vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0); 7902 vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1); 7903 vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids); 7904 vk_subbuffer d_F0 = d_D; 7905 vk_subbuffer d_X, d_Y; 7906 7907 if (qx_needs_dequant) { 7908 d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size }; 7909 } else { 7910 d_X = d_Qx; 7911 } 7912 if (qy_needs_dequant || quantize_y) { 7913 d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size }; 7914 } else { 7915 d_Y = d_Qy; 7916 } 7917 7918 if (x_non_contig) { 7919 if (ctx->prealloc_x_need_sync) { 7920 ggml_vk_sync_buffers(ctx, subctx); 7921 } 7922 } 7923 7924 if (x_non_contig) { 7925 GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment)); 7926 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X); 7927 } 7928 if (y_non_contig) { 7929 GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne); 7930 if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() || 7931 ctx->prealloc_y_last_tensor_used != src1 || 7932 ctx->prealloc_y_last_k_padded) { 7933 if (ctx->prealloc_y_need_sync) { 7934 ggml_vk_sync_buffers(ctx, subctx); 7935 } 7936 ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y); 7937 ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get(); 7938 ctx->prealloc_y_last_tensor_used = src1; 7939 ctx->prealloc_y_last_k_padded = false; 7940 } 7941 } 7942 if (quantize_y) { 7943 if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() || 7944 ctx->prealloc_y_last_tensor_used != src1 || 7945 ctx->prealloc_y_last_k_padded) { 7946 if (ctx->prealloc_y_need_sync) { 7947 ggml_vk_sync_buffers(ctx, subctx); 7948 } 7949 ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne); 7950 ctx->prealloc_y_last_pipeline_used = to_q8_1.get(); 7951 ctx->prealloc_y_last_tensor_used = src1; 7952 ctx->prealloc_y_last_k_padded = false; 7953 } 7954 } 7955 7956 uint32_t stride_batch_x = qx_needs_dequant ? ne00*ne01 : ggml_vk_batch_stride(src0); 7957 uint32_t stride_batch_y = (qy_needs_dequant || quantize_y) ? ne10*ne11 : ggml_vk_batch_stride(src1); 7958 7959 if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) { 7960 stride_batch_y = src1->nb[2] / ggml_type_size(src1->type); 7961 } 7962 7963 const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0]; 7964 7965 uint32_t groups_x = ne01; 7966 uint32_t groups_z = 1; 7967 7968 if (ne01 > max_groups_x) { 7969 groups_z = 64; 7970 groups_x = CEIL_DIV(groups_x, groups_z); 7971 } 7972 7973 uint32_t fusion_flags = 0; 7974 7975 if (ctx->num_additional_fused_ops > 0) { 7976 const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1]; 7977 7978 d_F0 = ggml_vk_tensor_subbuffer(ctx, bias); 7979 7980 if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) { 7981 fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0; 7982 } else { 7983 GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID); 7984 fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0; 7985 } 7986 } 7987 7988 vk_subbuffer d_F1 = d_D; 7989 if (ctx->num_additional_fused_ops > 1) { 7990 const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1]; 7991 7992 d_F1 = ggml_vk_tensor_subbuffer(ctx, scale); 7993 fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1; 7994 } 7995 7996 // Loop over the batch dimension 7997 for (uint32_t expert_i1 = 0; expert_i1 < nei1; ++expert_i1) { 7998 const vk_mat_vec_id_push_constants pc = { 7999 (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01, 8000 stride_batch_x, stride_batch_y, (uint32_t)(ne20 * ne21), 8001 fusion_flags, 8002 (uint32_t)nei0, (uint32_t)ne11, expert_i1, nbi1 8003 }; 8004 ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, 8005 { 8006 d_X, 8007 d_Y, 8008 d_D, 8009 d_F0, 8010 d_F1, 8011 d_ids, 8012 }, 8013 pc, { groups_x, (uint32_t)nei0, groups_z }); 8014 } 8015 8016 if (x_non_contig) { 8017 ctx->prealloc_x_need_sync = true; 8018 } 8019 if (y_non_contig || quantize_y) { 8020 ctx->prealloc_y_need_sync = true; 8021 } 8022 } 8023 8024 static bool ggml_vk_use_mul_mat_vec_id(const ggml_tensor * dst) { 8025 const ggml_tensor * src0 = dst->src[0]; 8026 const ggml_tensor * ids = dst->src[2]; 8027 return ids->ne[1] <= 8 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)); 8028 } 8029 8030 bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) { 8031 return ggml_vk_use_mul_mat_vec_id(cgraph->nodes[node_idx]); 8032 } 8033 8034 void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { 8035 ggml_tensor * dst = cgraph->nodes[node_idx]; 8036 ggml_tensor * src0 = dst->src[0]; 8037 ggml_tensor * src1 = dst->src[1]; 8038 ggml_tensor * src2 = dst->src[2]; 8039 VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")"); 8040 if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) { 8041 ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx); 8042 } else { 8043 ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst); 8044 } 8045 } 8046 8047 bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type) { 8048 GGML_UNUSED(f32acc); 8049 // Needs to be kept up to date on shader changes 8050 const uint32_t wg_size = params.workgroup_size; 8051 const uint32_t Br = params.block_rows; 8052 const uint32_t Bc = params.block_cols; 8053 8054 // BF16 uses the fp32 shader (FLOAT_TYPE=float) 8055 const uint32_t float_type_size = (device->fp16 && k_type != GGML_TYPE_BF16) ? sizeof(ggml_fp16_t) : sizeof(float); 8056 8057 const bool mmq = ggml_vk_fa_scalar_uses_mmq(device, k_type, v_type); 8058 8059 // tmpsh is overestimated slightly 8060 const uint32_t tmpsh = wg_size * sizeof(float); 8061 const uint32_t tmpshv4 = wg_size * 4 * float_type_size; 8062 8063 const uint32_t masksh = Bc * (Br + 1) * float_type_size; 8064 // DATA_A_IQ4_NL is compiled into the FA shaders unconditionally, so its shared table is always allocated. 8065 const uint32_t iq_shmem = 16 * float_type_size; 8066 8067 uint32_t Qf, kvsh, kblocksh_size; 8068 if (mmq) { 8069 // block_b_cache: int32_t qs[8] + FLOAT_TYPEV2 ds 8070 const uint32_t block_b_size = 8 * sizeof(int32_t) + 2 * float_type_size; 8071 Qf = Br * (hsk / 32) * block_b_size; 8072 8073 // kvsh uses D = HSV (K goes through kblocksh instead) 8074 kvsh = params.shmem_staging ? Bc * (hsv / 4 + 1) * 4 * float_type_size : 4 * float_type_size; 8075 8076 // The mixed MMQ shader uses a superset block_a_cache that fits every 8077 // FA-supported quant: int32_t qs[8] + uint32_t qh + FLOAT_TYPEV2 dm. 8078 // Single-scale types leave dm.y unused; non-Q5_* leave qh unused. 8079 const uint32_t block_a_size = 8 * sizeof(int32_t) + sizeof(uint32_t) + 2 * float_type_size; 8080 kblocksh_size = params.shmem_staging ? Bc * (hsk / 32) * block_a_size : block_a_size; 8081 } else { 8082 Qf = Br * (hsk / 4 + 1) * 4 * float_type_size; 8083 8084 const uint32_t D = std::max(hsk, hsv); 8085 kvsh = params.shmem_staging ? Bc * (D / 4 + 1) * 4 * float_type_size : 4 * float_type_size; 8086 8087 kblocksh_size = 0; 8088 } 8089 8090 const uint32_t total_size = tmpsh + tmpshv4 + masksh + iq_shmem + Qf + kvsh + kblocksh_size; 8091 const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize; 8092 8093 VK_LOG_DEBUG("ggml_vk_flash_attn_scalar_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", mmq=" << mmq << ", total_size=" << total_size << ", supported=" << supported); 8094 8095 return supported; 8096 } 8097 8098 bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type) { 8099 GGML_UNUSED(v_type); 8100 // Needs to be kept up to date on shader changes 8101 const uint32_t Br = params.block_rows; 8102 const uint32_t Bc = params.block_cols; 8103 8104 const uint32_t MatBr = 16, MatBc = 16; 8105 8106 const uint32_t row_split = Bc / MatBc; 8107 8108 const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16); 8109 const uint32_t hsv_pad = ROUNDUP_POW2(hsv, 16); 8110 8111 const uint32_t acctype = f32acc ? 4 : 2; 8112 const uint32_t f16vec4 = 8; 8113 8114 const uint32_t tmpsh = (Bc / MatBc) * sizeof(float); 8115 // DATA_A_IQ4_NL is compiled into the FA shaders unconditionally, so its shared table is always allocated. 8116 const uint32_t iq_shmem = 16 * sizeof(ggml_fp16_t); 8117 8118 const uint32_t qstride = hsk_pad / 4 + 2; 8119 const uint32_t Qf = Br * qstride * f16vec4; 8120 8121 const uint32_t psh_stride = Br / 4 + 2; 8122 const uint32_t Psh = Bc * psh_stride * f16vec4; 8123 8124 const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br; 8125 const uint32_t sfsh = Bc * sfshstride * acctype; 8126 8127 const uint32_t kvshstride = (params.shmem_staging ? std::max(hsk_pad, hsv_pad) : MatBr) / 4 + 2; 8128 const uint32_t vsh_stride = MatBc / 4 * row_split; 8129 const uint32_t ksh = ((kvshstride >= vsh_stride) ? (Bc * kvshstride) : (Bc * vsh_stride)) * f16vec4; 8130 8131 // BF16 PVMat accumulator is f32 (no bf16 accumulator support), so pvsh is vec4 (16 bytes) 8132 const uint32_t pvsh_elem_size = (k_type == GGML_TYPE_BF16) ? 16u : f16vec4; 8133 const uint32_t osh_stride = params.row_split * MatBr / 4; 8134 const uint32_t pvsh = MatBc * osh_stride * pvsh_elem_size; 8135 8136 const uint32_t slope = Br * acctype; 8137 8138 const uint32_t total_size = tmpsh + iq_shmem + Qf + Psh + sfsh + ksh + pvsh + slope; 8139 const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize; 8140 8141 VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported); 8142 8143 return supported; 8144 } 8145 8146 void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, const ggml_tensor * sinks, ggml_tensor * dst) { 8147 VK_LOG_DEBUG("ggml_vk_flash_attn((" << q << ", name=" << q->name << ", type=" << q->type << ", ne0=" << q->ne[0] << ", ne1=" << q->ne[1] << ", ne2=" << q->ne[2] << ", ne3=" << q->ne[3] << ", nb0=" << q->nb[0] << ", nb1=" << q->nb[1] << ", nb2=" << q->nb[2] << ", nb3=" << q->nb[3]; 8148 std::cerr << "), (" << k << ", name=" << k->name << ", type=" << k->type << ", ne0=" << k->ne[0] << ", ne1=" << k->ne[1] << ", ne2=" << k->ne[2] << ", ne3=" << k->ne[3] << ", nb0=" << k->nb[0] << ", nb1=" << k->nb[1] << ", nb2=" << k->nb[2] << ", nb3=" << k->nb[3]; 8149 std::cerr << "), (" << v << ", name=" << v->name << ", type=" << v->type << ", ne0=" << v->ne[0] << ", ne1=" << v->ne[1] << ", ne2=" << v->ne[2] << ", ne3=" << v->ne[3] << ", nb0=" << v->nb[0] << ", nb1=" << v->nb[1] << ", nb2=" << v->nb[2] << ", nb3=" << v->nb[3]; 8150 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; 8151 if (sinks) { 8152 std::cerr << "), (" << sinks << ", name=" << sinks->name << ", type=" << sinks->type << ", ne0=" << sinks->ne[0] << ", ne1=" << sinks->ne[1] << ", ne2=" << sinks->ne[2] << ", ne3=" << sinks->ne[3] << ", nb0=" << sinks->nb[0] << ", nb1=" << sinks->nb[1] << ", nb2=" << sinks->nb[2] << ", nb3=" << sinks->nb[3]; 8153 } 8154 std::cerr << "))"); 8155 8156 GGML_TENSOR_LOCALS(int64_t, neq, q, ne) 8157 GGML_TENSOR_LOCALS(size_t, nbq, q, nb) 8158 GGML_TENSOR_LOCALS(int64_t, nek, k, ne) 8159 GGML_TENSOR_LOCALS(size_t, nbk, k, nb) 8160 GGML_TENSOR_LOCALS(int64_t, nev, v, ne) 8161 GGML_TENSOR_LOCALS(size_t, nbv, v, nb) 8162 GGML_TENSOR_LOCALS(int64_t, ne, dst, ne) 8163 GGML_TENSOR_LOCALS(size_t, nb, dst, nb) 8164 8165 const uint32_t nem0 = mask ? mask->ne[0] : 0; 8166 const uint32_t nem1 = mask ? mask->ne[1] : 0; 8167 const uint32_t nem2 = mask ? mask->ne[2] : 0; 8168 const uint32_t nem3 = mask ? mask->ne[3] : 0; 8169 8170 const uint32_t HSK = nek0; 8171 const uint32_t HSV = nev0; 8172 uint32_t N = neq1; 8173 const uint32_t KV = nek1; 8174 8175 GGML_ASSERT(ne0 == HSV); 8176 GGML_ASSERT(ne2 == N); 8177 8178 // input tensor rows must be contiguous 8179 GGML_ASSERT(nbq0 == ggml_type_size(q->type)); 8180 GGML_ASSERT(nbk0 == ggml_type_size(k->type)); 8181 GGML_ASSERT(nbv0 == ggml_type_size(v->type)); 8182 8183 GGML_ASSERT(neq0 == HSK); 8184 8185 GGML_ASSERT(neq1 == N); 8186 8187 GGML_ASSERT(nev1 == nek1); 8188 8189 // dst cannot be transposed or permuted 8190 GGML_ASSERT(nb0 == sizeof(float)); 8191 GGML_ASSERT(nb0 <= nb1); 8192 GGML_ASSERT(nb1 <= nb2); 8193 GGML_ASSERT(nb2 <= nb3); 8194 8195 assert(dst->type == GGML_TYPE_F32); 8196 assert(q->type == GGML_TYPE_F32); 8197 uint32_t gqa_ratio = 1; 8198 uint32_t qk_ratio = neq2 / nek2; 8199 uint32_t workgroups_x = (uint32_t)neq1; 8200 uint32_t workgroups_y = (uint32_t)neq2; 8201 uint32_t workgroups_z = (uint32_t)neq3; 8202 8203 const bool f32acc = !ctx->device->fp16 || !ggml_vk_prec_allows_f16acc(ggml_prec_get_acc(dst)) || k->type == GGML_TYPE_BF16; 8204 8205 // dequant K/V once into an f16 scratch, reordered KV layout so FA can read without a stride 8206 auto is_dense_kv_cache = [](const ggml_tensor * t) { 8207 return t->nb[0] == ggml_type_size(t->type) && 8208 t->nb[2] == ggml_row_size(t->type, t->ne[0]) && 8209 t->nb[1] == t->nb[2] * t->ne[2] && 8210 (t->ne[3] == 1 || t->nb[3] == t->nb[1] * t->ne[1]); 8211 }; 8212 const bool k_quant = k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_BF16 && k->type != GGML_TYPE_F32; 8213 const bool v_quant = v->type != GGML_TYPE_F16 && v->type != GGML_TYPE_BF16 && v->type != GGML_TYPE_F32; 8214 const bool kv_raw = (k->type == GGML_TYPE_F16 || k->type == GGML_TYPE_BF16) && k->type == v->type; 8215 // gated to AMD, except RDNA4, which regressed in benchmarks 8216 const bool kv_raw_strided = ctx->device->vendor_id == VK_VENDOR_ID_AMD && 8217 ctx->device->architecture != vk_device_architecture::AMD_RDNA4 && 8218 neq1 >= 256 && 8219 kv_raw && 8220 (k->nb[1] != (uint64_t)HSK * ggml_type_size(k->type) || 8221 v->nb[1] != (uint64_t)HSV * ggml_type_size(v->type)) && 8222 (HSK % 8) == 0 && (HSV % 8) == 0; 8223 const size_t kv_scratch_ts = kv_raw_strided ? ggml_type_size(k->type) : sizeof(ggml_fp16_t); 8224 const bool use_dequant_kv = ((k_quant && v_quant) || kv_raw_strided) && neq1 >= 64 && 8225 is_dense_kv_cache(k) && is_dense_kv_cache(v) && 8226 (uint64_t)ggml_nelements(k) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && 8227 (uint64_t)ggml_nelements(v) * kv_scratch_ts <= ctx->device->properties.limits.maxStorageBufferRange && 8228 (kv_raw_strided || 8229 (ctx->device->pipeline_dequant_transpose[k->type] != nullptr && 8230 ctx->device->pipeline_dequant_transpose[v->type] != nullptr)) && 8231 // coopmat2 path does not benefit from the f16 scratch 8232 !ctx->device->coopmat2 && 8233 // Intel Xe1 regresses, see PR 25494 8234 (ctx->device->vendor_id != VK_VENDOR_ID_INTEL || 8235 (ctx->device->coopmat_support && ctx->device->architecture != vk_device_architecture::INTEL_XE1)); 8236 const ggml_type k_type_eff = (use_dequant_kv && !kv_raw_strided) ? GGML_TYPE_F16 : k->type; 8237 const ggml_type v_type_eff = (use_dequant_kv && !kv_raw_strided) ? GGML_TYPE_F16 : v->type; 8238 8239 // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga. 8240 // For coopmat2 FA, we always use the small size (which is still pretty large for gqa). 8241 vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 512, KV, k_type_eff, v_type_eff, f32acc); 8242 const uint32_t max_gqa = std::min(tuning_params.block_rows, 32u); 8243 8244 if (N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && 8245 qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) { 8246 // grouped query attention - make the N dimension equal to gqa_ratio, reduce 8247 // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1 8248 // and change addressing calculations to index Q's dimension 2. 8249 gqa_ratio = qk_ratio; 8250 N = gqa_ratio; 8251 workgroups_y /= gqa_ratio; 8252 } 8253 8254 tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc); 8255 8256 float scale = 1.0f; 8257 float max_bias = 0.0f; 8258 float logit_softcap = 0.0f; 8259 8260 memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float)); 8261 memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); 8262 memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float)); 8263 8264 if (logit_softcap != 0) { 8265 scale /= logit_softcap; 8266 } 8267 8268 // Sparse mask hint (op_params[4]): compact the <= n_kv_max finite positions and gather only those. 8269 const int32_t n_kv_max = mask ? ggml_get_op_params_i32(dst, 4) : 0; 8270 static const bool disable_sparse = getenv("GGML_VK_FA_SPARSE_DISABLE") != nullptr; 8271 const bool kv_f16 = k_type_eff == GGML_TYPE_F16 && v_type_eff == GGML_TYPE_F16; 8272 // cm2 dense is fast, so it needs a larger reduction to win. 8273 // With quantized K/V, sparse only breaks even around 16x (measured on RDNA3/RDNA4). 8274 const int64_t min_ratio = tuning_params.path == FA_COOPMAT2 ? 4 : (kv_f16 ? 2 : 16); 8275 // coopmat2 vector decode requires 8B strides. 8276 auto sparse_gather_aligned = [](const ggml_tensor * t) { 8277 return (t->type != GGML_TYPE_F16 && t->type != GGML_TYPE_BF16) || 8278 (t->nb[1] | t->nb[2] | t->nb[3]) % (4 * sizeof(ggml_fp16_t)) == 0; 8279 }; 8280 const bool use_sparse = !disable_sparse && n_kv_max > 0 && mask && 8281 max_bias == 0.0f && logit_softcap == 0.0f && 8282 (tuning_params.path != FA_COOPMAT2 || (sparse_gather_aligned(k) && sparse_gather_aligned(v))) && 8283 nem0 == KV && 8284 (int64_t)KV >= std::max(4096, min_ratio * (int64_t)n_kv_max) && 8285 (gqa_ratio > 1 || (tuning_params.path == FA_SCALAR && N == 1)); 8286 8287 const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type)); 8288 uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type)); 8289 uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type)); 8290 8291 // For F32, the shader treats it as a block of size 4 (for vec4 loads) 8292 if (k->type == GGML_TYPE_F32) { 8293 k_stride /= 4; 8294 } 8295 if (v->type == GGML_TYPE_F32) { 8296 v_stride /= 4; 8297 } 8298 8299 uint32_t nbk2_eff = (uint32_t)nbk2, nbk3_eff = (uint32_t)nbk3; 8300 uint32_t nbv2_eff = (uint32_t)nbv2, nbv3_eff = (uint32_t)nbv3; 8301 if (use_dequant_kv) { 8302 k_stride = HSK; 8303 v_stride = HSV; 8304 nbk2_eff = (uint32_t)((uint64_t)HSK * KV * sizeof(ggml_fp16_t)); 8305 nbk3_eff = (uint32_t)((uint64_t)HSK * KV * nek2 * sizeof(ggml_fp16_t)); 8306 nbv2_eff = (uint32_t)((uint64_t)HSV * KV * sizeof(ggml_fp16_t)); 8307 nbv3_eff = (uint32_t)((uint64_t)HSV * KV * nev2 * sizeof(ggml_fp16_t)); 8308 } 8309 const uint32_t alignment = tuning_params.block_cols; 8310 bool aligned = (KV % alignment) == 0 && 8311 // the "aligned" shader variant will forcibly align strides, for performance 8312 (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0; 8313 8314 // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned. 8315 if (((HSK | HSV) % 16) != 0 && tuning_params.path == FA_COOPMAT2) { 8316 aligned = false; 8317 } 8318 8319 // Only use mask opt when the mask is fairly large. This hasn't been tuned extensively. 8320 bool use_mask_opt = mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16 8321 && (ctx->device->architecture != vk_device_architecture::AMD_GCN || HSK > 256 || HSV > 256); 8322 vk_fa_pipeline_state fa_pipeline_state = get_fa_pipeline_state(ctx->device, tuning_params, HSK, HSV, aligned, f32acc, 8323 mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff); 8324 8325 vk_pipeline pipeline = nullptr; 8326 8327 bool xe_fa_opt = false; 8328 bool fa_copy_qstate = false; 8329 bool xe_fa_supported_platform = 8330 (ctx->device.get()->architecture == INTEL_XE2 && ctx->device.get()->properties.deviceID != 0xFD80 && ctx->device.get()->properties.deviceID != 0xFD81) || 8331 (ctx->device.get()->architecture == INTEL_XE1 && ctx->device.get()->coopmat_support && ctx->device.get()->uma); 8332 bool xe_fa_supported_usage = neq0 % 32 == 0 && nev0 % 16 == 0 && q->nb[1] > q->nb[2] && k->nb[1] > k->nb[2] && v->nb[1] > v->nb[2] && mask != nullptr; 8333 bool xe_fa_supported_dtype = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 && (mask != nullptr && mask->type == GGML_TYPE_F16); 8334 std::pair xe_fa_pipeline_dual_phases = { nullptr , nullptr }; 8335 vk_pipeline xe_fa_pipeline = nullptr; 8336 size_t size_p = 0; 8337 size_t size_group_max = 0; 8338 8339 { 8340 std::lock_guard guard(ctx->device->compile_mutex); 8341 auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16; 8342 auto it = pipelines.find(fa_pipeline_state); 8343 if (it != pipelines.end()) { 8344 pipeline = it->second; 8345 } else { 8346 pipelines[fa_pipeline_state] = pipeline = std::make_shared(); 8347 } 8348 } 8349 8350 assert(pipeline); 8351 // Compile early to initialize wg_denoms. 8352 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 8353 8354 uint32_t split_kv = KV; 8355 uint32_t split_k = 1; 8356 8357 // Intel Alchemist prefers more workgroups 8358 const uint32_t shader_core_count_multiplier = (ctx->device->vendor_id == VK_VENDOR_ID_INTEL && ctx->device->architecture != INTEL_XE2) ? 2 : 1; 8359 8360 // Use a placeholder core count if one isn't available. split_k is a big help for perf. 8361 const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count * shader_core_count_multiplier : 16; 8362 8363 const uint32_t Br = fa_pipeline_state.Br; 8364 const uint32_t Bc = fa_pipeline_state.Bc; 8365 8366 GGML_ASSERT(Br == pipeline->wg_denoms[0]); 8367 const uint32_t Tr = CEIL_DIV(N, Br); 8368 8369 // Try to use split_k when KV is large enough to be worth the overhead. 8370 // Sparse: split_kv carries n_kv_max, split_k partitions its blocks for occupancy. 8371 if (use_sparse) { 8372 split_kv = (uint32_t)n_kv_max; 8373 const uint32_t total_blocks = CEIL_DIV((uint32_t)n_kv_max, Bc); 8374 const uint32_t base_wgs = (gqa_ratio > 1 ? workgroups_x : Tr) * workgroups_y * workgroups_z; 8375 if (base_wgs < shader_core_count * 2) { 8376 split_k = shader_core_count * 2 / base_wgs; 8377 } 8378 split_k = std::max(1u, std::min(split_k, total_blocks)); 8379 // Match the shader's per-split block count so no split is empty. 8380 const uint32_t per_blocks = CEIL_DIV(total_blocks, split_k); 8381 split_k = CEIL_DIV(total_blocks, per_blocks); 8382 } else if (gqa_ratio > 1 && workgroups_x <= Br) { 8383 split_k = shader_core_count * 2 / (workgroups_x * workgroups_y * workgroups_z); 8384 } else if (gqa_ratio <= 1) { 8385 uint32_t total_wgs_no_split = Tr * workgroups_y * workgroups_z; 8386 if (total_wgs_no_split < shader_core_count * 2) { 8387 split_k = shader_core_count * 2 / total_wgs_no_split; 8388 } 8389 } 8390 8391 if (!use_sparse && split_k > 1) { 8392 // Try to evenly split KV into split_k chunks, but it needs to be a multiple 8393 // of "align", so recompute split_k based on that. 8394 split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment); 8395 split_k = CEIL_DIV(KV, split_kv); 8396 xe_fa_opt = xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype; 8397 if (xe_fa_opt) { 8398 const uint32_t split_p_size = 32; 8399 const size_t max_dim = (nek1 + split_p_size - 1) / split_p_size; 8400 const size_t p_dim = max_dim * split_p_size; 8401 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 8402 std::lock_guard guard(ctx->device->compile_mutex); 8403 auto& pipelines = ctx->device->pipeline_xe_fa_decode_dual_phases; 8404 auto it = pipelines.find({ (uint32_t)neq0, (uint32_t)nev0, qk_ratio, (uint32_t)neq1 }); 8405 if (it != pipelines.end()) { 8406 xe_fa_pipeline_dual_phases = it->second; 8407 } else { 8408 pipelines[{(uint32_t)neq0, (uint32_t)nev0, qk_ratio, (uint32_t)neq1}] = xe_fa_pipeline_dual_phases = std::make_pair(std::make_shared(), std::make_shared()); 8409 } 8410 #endif 8411 if (xe_fa_pipeline_dual_phases.first == nullptr || xe_fa_pipeline_dual_phases.second == nullptr) { 8412 xe_fa_opt = false; 8413 fa_copy_qstate = false; 8414 } else { 8415 size_p = neq1 * neq2 * p_dim * neq3 * sizeof(ggml_fp16_t); 8416 size_group_max = neq1 * neq2 * max_dim * neq3 * sizeof(float); 8417 size_t temp_size = ggml_nelements(q) * sizeof(ggml_fp16_t) + size_p + size_group_max; 8418 fa_copy_qstate = true; 8419 if (ctx->prealloc_size_x < temp_size) { 8420 ctx->prealloc_size_x = temp_size; 8421 ggml_vk_preallocate_buffers(ctx, subctx); 8422 } 8423 8424 if (ctx->prealloc_x_need_sync) { 8425 ggml_vk_sync_buffers(ctx, subctx); 8426 } 8427 } 8428 } 8429 } 8430 8431 if (xe_fa_opt == true) { 8432 use_mask_opt = false; 8433 } 8434 8435 // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1) 8436 // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows. 8437 // For matrices, the order is (inner to outer) [HSV, ne1, k, ne2, ne3]. 8438 // For L/M, the order is (inner to outer) [ne1, k, ne2, ne3]. 8439 const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne2 * ne3 : 0; 8440 if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) { 8441 GGML_ABORT("Requested preallocation size is too large"); 8442 } 8443 if (ctx->prealloc_size_split_k < split_k_size) { 8444 ctx->prealloc_size_split_k = split_k_size; 8445 ggml_vk_preallocate_buffers(ctx, subctx); 8446 } 8447 8448 const uint32_t mask_opt_num_dwords = CEIL_DIV(nem0, 16 * Bc); 8449 const uint64_t mask_opt_size = sizeof(uint32_t) * mask_opt_num_dwords * CEIL_DIV(nem1, Br) * nem2 * nem3; 8450 8451 vk_pipeline pipeline_fa_mask_opt = nullptr; 8452 if (use_mask_opt) { 8453 { 8454 std::lock_guard guard(ctx->device->compile_mutex); 8455 auto &pipelines = ctx->device->pipeline_fa_mask_opt; 8456 auto it = pipelines.find({Br, Bc}); 8457 if (it != pipelines.end()) { 8458 pipeline_fa_mask_opt = it->second; 8459 } else { 8460 pipelines[{Br, Bc}] = pipeline_fa_mask_opt = std::make_shared(); 8461 } 8462 } 8463 assert(pipeline_fa_mask_opt); 8464 ggml_pipeline_request_descriptor_sets(ctx, pipeline_fa_mask_opt, 1); 8465 8466 if (ctx->prealloc_size_y < mask_opt_size) { 8467 ctx->prealloc_size_y = mask_opt_size; 8468 ggml_vk_preallocate_buffers(ctx, subctx); 8469 } 8470 if (ctx->prealloc_y_need_sync) { 8471 ggml_vk_sync_buffers(ctx, subctx); 8472 } 8473 } 8474 8475 // Sparse index scratch reuses prealloc_y (mutually exclusive with mask opt). 8476 const uint64_t sparse_idx_size = use_sparse 8477 ? sizeof(int32_t) * (uint64_t)n_kv_max * nem1 * nem2 * nem3 8478 : 0; 8479 vk_pipeline sparse_compact_pipeline = ctx->device->fa_sparse_compact_use_subgroups 8480 ? ctx->device->pipeline_fa_sparse_compact_subgroup 8481 : ctx->device->pipeline_fa_sparse_compact; 8482 if (use_sparse) { 8483 ggml_pipeline_request_descriptor_sets(ctx, sparse_compact_pipeline, 1); 8484 if (ctx->prealloc_size_y < sparse_idx_size) { 8485 ctx->prealloc_size_y = sparse_idx_size; 8486 ggml_vk_preallocate_buffers(ctx, subctx); 8487 } 8488 if (ctx->prealloc_y_need_sync) { 8489 ggml_vk_sync_buffers(ctx, subctx); 8490 } 8491 } 8492 8493 const uint32_t n_head_kv = neq2; 8494 const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv)); 8495 const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); 8496 const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); 8497 8498 vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q); 8499 vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k); 8500 vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v); 8501 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 8502 vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf; 8503 vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf; 8504 vk_subbuffer mask_opt_buf = use_mask_opt ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; 8505 vk_subbuffer sparse_buf = use_sparse ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf; 8506 if (use_mask_opt || use_sparse) { 8507 // the mask opt bits and the sparse index list overwrite a matmul input converted into prealloc_y 8508 ctx->prealloc_y_last_pipeline_used = nullptr; 8509 ctx->prealloc_y_last_tensor_used = nullptr; 8510 } 8511 8512 if (use_dequant_kv) { 8513 const uint64_t k_sz = (uint64_t)ggml_nelements(k) * kv_scratch_ts; 8514 const uint64_t v_sz = (uint64_t)ggml_nelements(v) * kv_scratch_ts; 8515 if (ctx->prealloc_size_x < k_sz + v_sz) { 8516 ctx->prealloc_size_x = k_sz + v_sz; 8517 ggml_vk_preallocate_buffers(ctx, subctx); 8518 } 8519 vk_subbuffer k_dst = vk_subbuffer{ ctx->prealloc_x, 0, k_sz }; 8520 vk_subbuffer v_dst = vk_subbuffer{ ctx->prealloc_x, k_sz, v_sz }; 8521 const uint32_t k_nel = (uint32_t)ggml_nelements(k); 8522 const uint32_t v_nel = (uint32_t)ggml_nelements(v); 8523 if (kv_raw_strided) { 8524 vk_pipeline cp_k = ggml_vk_get_cpy_pipeline(ctx, k, nullptr, k->type); 8525 vk_pipeline cp_v = ggml_vk_get_cpy_pipeline(ctx, v, nullptr, v->type); 8526 ggml_pipeline_request_descriptor_sets(ctx, cp_k, 1); 8527 ggml_pipeline_request_descriptor_sets(ctx, cp_v, 1); 8528 if (ctx->prealloc_x_need_sync) { 8529 ggml_vk_sync_buffers(ctx, subctx); 8530 } 8531 auto make_pc = [](uint32_t hs, uint32_t nh, uint32_t kv, uint32_t nel) { 8532 vk_op_unary_push_constants pc{}; 8533 pc.ne = nel; 8534 pc.ne00 = hs; pc.ne01 = nh; pc.ne02 = kv; pc.ne03 = nel / (hs * nh * kv); 8535 pc.nb00 = 1; pc.nb01 = hs; pc.nb02 = hs * nh; pc.nb03 = hs * nh * kv; 8536 pc.ne10 = hs; pc.ne11 = nh; pc.ne12 = kv; pc.ne13 = pc.ne03; 8537 pc.nb10 = 1; pc.nb11 = hs * kv; pc.nb12 = hs; pc.nb13 = hs * kv * nh; 8538 init_pushconst_fastdiv(pc); 8539 return pc; 8540 }; 8541 auto cpy_elems = [](uint32_t ne) -> std::array { 8542 if (ne > 262144) { return { 512, 512, CEIL_DIV(ne, 262144) }; } 8543 if (ne > 512) { return { 512, CEIL_DIV(ne, 512), 1 }; } 8544 return { ne, 1, 1 }; 8545 }; 8546 ggml_vk_dispatch_pipeline(ctx, subctx, cp_k, { k_buf, k_dst }, 8547 make_pc((uint32_t)HSK, (uint32_t)nek2, (uint32_t)KV, k_nel), cpy_elems(k_nel)); 8548 ggml_vk_dispatch_pipeline(ctx, subctx, cp_v, { v_buf, v_dst }, 8549 make_pc((uint32_t)HSV, (uint32_t)nev2, (uint32_t)KV, v_nel), cpy_elems(v_nel)); 8550 } else { 8551 vk_pipeline tr_k = ctx->device->pipeline_dequant_transpose[k->type]; 8552 vk_pipeline tr_v = ctx->device->pipeline_dequant_transpose[v->type]; 8553 ggml_pipeline_request_descriptor_sets(ctx, tr_k, 1); 8554 ggml_pipeline_request_descriptor_sets(ctx, tr_v, 1); 8555 if (ctx->prealloc_x_need_sync) { 8556 ggml_vk_sync_buffers(ctx, subctx); 8557 } 8558 { const std::vector pc = { (uint32_t)HSK, (uint32_t)nek2, (uint32_t)KV, 0, k_nel }; 8559 ggml_vk_dispatch_pipeline(ctx, subctx, tr_k, { k_buf, k_dst }, pc, { k_nel, 1, 1 }); } 8560 { const std::vector pc = { (uint32_t)HSV, (uint32_t)nev2, (uint32_t)KV, 0, v_nel }; 8561 ggml_vk_dispatch_pipeline(ctx, subctx, tr_v, { v_buf, v_dst }, pc, { v_nel, 1, 1 }); } 8562 } 8563 ggml_vk_sync_buffers(ctx, subctx); 8564 k_buf = k_dst; 8565 v_buf = v_dst; 8566 } 8567 8568 uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | n_head_log2; 8569 8570 if (use_mask_opt) 8571 { 8572 const vk_op_flash_attn_mask_opt_push_constants opt_pc = { 8573 nem0, 8574 nem1, 8575 nem2, 8576 (uint32_t)(mask->nb[1] / sizeof(ggml_fp16_t)), 8577 (uint32_t)(mask->nb[2] / sizeof(ggml_fp16_t)), 8578 (uint32_t)(mask->nb[3] / sizeof(ggml_fp16_t)), 8579 mask_opt_num_dwords, 8580 mask_opt_num_dwords * CEIL_DIV(nem1, Br), 8581 mask_opt_num_dwords * CEIL_DIV(nem1, Br) * nem2, 8582 }; 8583 8584 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline_fa_mask_opt, 8585 { mask_buf, mask_opt_buf }, opt_pc, 8586 { mask_opt_num_dwords, CEIL_DIV(nem1, Br), nem2 * nem3 }); 8587 ggml_vk_sync_buffers(ctx, subctx); 8588 } 8589 8590 if (use_sparse) 8591 { 8592 const vk_op_flash_attn_sparse_compact_push_constants sc_pc = { 8593 KV, 8594 nem1, 8595 nem2, 8596 (uint32_t)(mask->nb[1] / sizeof(ggml_fp16_t)), 8597 (uint32_t)(mask->nb[2] / sizeof(ggml_fp16_t)), 8598 (uint32_t)(mask->nb[3] / sizeof(ggml_fp16_t)), 8599 (uint32_t)n_kv_max, 8600 }; 8601 8602 ggml_vk_dispatch_pipeline(ctx, subctx, sparse_compact_pipeline, 8603 { mask_buf, sparse_buf }, sc_pc, 8604 { nem1, nem2, nem3 }); 8605 ggml_vk_sync_buffers(ctx, subctx); 8606 } 8607 8608 const vk_flash_attn_push_constants pc = { N, KV, 8609 (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, 8610 (uint32_t)neq2, (uint32_t)neq3, 8611 (uint32_t)nek2, (uint32_t)nek3, 8612 (uint32_t)nev2, (uint32_t)nev3, 8613 nem1, nem2, nem3, 8614 q_stride, (uint32_t)nbq2, (uint32_t)nbq3, 8615 k_stride, nbk2_eff, nbk3_eff, 8616 v_stride, nbv2_eff, nbv3_eff, 8617 scale, max_bias, logit_softcap, 8618 mask_n_head_log2, m0, m1, 8619 gqa_ratio, split_kv, split_k }; 8620 8621 if (xe_fa_opt && split_k > 1) { 8622 auto upper_power_of_2 = [&](uint32_t in) { 8623 GGML_ASSERT(in != 0); 8624 if (in <= 1) return 1u; 8625 uint32_t ret = in - 1; 8626 ret |= ret >> 1; 8627 ret |= ret >> 2; 8628 ret |= ret >> 4; 8629 ret |= ret >> 8; 8630 ret |= ret >> 16; 8631 return ret + 1; 8632 }; 8633 auto to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, q->type); 8634 const uint32_t out_dim_per_wg = qk_ratio > 16 ? 8 : 16; 8635 size_t x_ne = ggml_nelements(q); 8636 size_t temp_buf_offset = 0; 8637 uint32_t head_stride_k = uint32_t(nbk2 / ggml_type_size(k->type)); 8638 uint32_t head_stride_v = uint32_t(nbv2 / ggml_type_size(v->type)); 8639 uint32_t batch_stride_q = uint32_t(nbq3 / ggml_type_size(q->type)); 8640 uint32_t batch_stride_k = uint32_t(nbk3 / ggml_type_size(k->type)); 8641 uint32_t batch_stride_v = uint32_t(nbv3 / ggml_type_size(v->type)); 8642 uint32_t batch_stride_m = mask ? uint32_t(mask->nb[3] / ggml_type_size(mask->type)) : 0u; 8643 uint32_t batch_stride_o = uint32_t(nb3 / ggml_type_size(dst->type)); 8644 vk_fa_xe_opt_push_constants pc_ph1 = { (uint32_t)nek1, (uint32_t)neq1, (uint32_t)neq2, (uint32_t)nek2, qk_ratio, 1, (sinks != nullptr) ? 1u : 0u, (uint32_t)k_stride, head_stride_k, 8645 batch_stride_q, batch_stride_k, batch_stride_v, batch_stride_m, batch_stride_o, scale }; 8646 vk_fa_xe_opt_push_constants pc_ph2 = pc_ph1; 8647 pc_ph2.nbkv_tok = v_stride; 8648 pc_ph2.nbkv_head = head_stride_v; 8649 vk_subbuffer q_temp_buf = fa_copy_qstate ? ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset) : q_buf; 8650 temp_buf_offset += fa_copy_qstate ? x_ne * sizeof(ggml_fp16_t) : 0; 8651 vk_subbuffer p_temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset); 8652 temp_buf_offset += size_p; 8653 vk_subbuffer max_temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset); 8654 temp_buf_offset += size_group_max; 8655 uint32_t xe_native_sub_group_size = ctx->device.get()->architecture == INTEL_XE1 ? 8 : 16; 8656 uint32_t aligned_gqa_ratio = upper_power_of_2(qk_ratio); 8657 uint32_t out_per_wg_ph1 = std::min(256u / xe_native_sub_group_size, (uint32_t)neq1); 8658 uint32_t out_per_wg_ph2 = std::min(std::max(16u / aligned_gqa_ratio, 1u), (uint32_t)neq1); 8659 uint32_t ph1_wg = ((neq1 + out_per_wg_ph1 - 1) / out_per_wg_ph1) * nek2; 8660 uint32_t ph2_wg = ((neq1 + out_per_wg_ph2 - 1) / out_per_wg_ph2) * ne0 / out_dim_per_wg; 8661 if (fa_copy_qstate) { 8662 const std::vector pc_cpy_fp16 = 8663 { (uint32_t)q->ne[0], (uint32_t)q->ne[1], (uint32_t)q->ne[2], (uint32_t)q->ne[3], (uint32_t)(x_ne) }; 8664 ggml_vk_sync_buffers(ctx, subctx); 8665 ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1); 8666 ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { q_buf, q_temp_buf }, pc_cpy_fp16, { (uint32_t)(x_ne), 1, 1 }); 8667 } 8668 8669 ggml_vk_sync_buffers(ctx, subctx); 8670 ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.first, 1); 8671 ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.first, 8672 { q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf }, 8673 pc_ph1, { (uint32_t)ph1_wg, (uint32_t)nek1, (uint32_t)neq3 }); 8674 8675 ggml_vk_sync_buffers(ctx, subctx); 8676 ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.second, 1); 8677 ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.second, 8678 { p_temp_buf, v_buf, max_temp_buf, sinks_buf, dst_buf }, 8679 pc_ph2, { (uint32_t)ph2_wg, (uint32_t)nev2, (uint32_t)neq3 }); 8680 8681 ctx->prealloc_x_need_sync = true; 8682 } else if (split_k > 1) { 8683 ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1); 8684 8685 if (ctx->prealloc_split_k_need_sync) { 8686 ggml_vk_sync_buffers(ctx, subctx); 8687 } 8688 8689 // We reuse workgroups_x to mean the number of splits, so we need to 8690 // cancel out the divide by wg_denoms[0]. 8691 uint32_t dispatch_x; 8692 if (gqa_ratio > 1) { 8693 workgroups_x *= pipeline->wg_denoms[0]; 8694 dispatch_x = split_k * workgroups_x; 8695 } else { 8696 dispatch_x = Tr * split_k * pipeline->wg_denoms[0]; 8697 } 8698 8699 vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0); 8700 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 8701 {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf}, 8702 pc, { dispatch_x, workgroups_y, workgroups_z }); 8703 8704 ggml_vk_sync_buffers(ctx, subctx); 8705 const vk_op_flash_attn_split_k_reduce_push_constants pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, split_k, (sinks != nullptr) }; 8706 ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce, 8707 {split_k_buf, sinks_buf, dst_buf}, 8708 pc2, { (uint32_t)ne1, HSV, (uint32_t)(ne2 * ne3) }); 8709 ctx->prealloc_split_k_need_sync = true; 8710 } else { 8711 if (gqa_ratio > 1) { 8712 // When using gqa, we want one actual workgroup per batch, so cancel out wg_denoms 8713 workgroups_x *= pipeline->wg_denoms[0]; 8714 } 8715 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 8716 {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf}, 8717 pc, { workgroups_x, workgroups_y, workgroups_z }); 8718 } 8719 8720 if (use_dequant_kv) { 8721 ctx->prealloc_x_need_sync = true; 8722 } 8723 if (use_mask_opt || use_sparse) { 8724 ctx->prealloc_y_need_sync = true; 8725 } 8726 } 8727 8728 static vk_conv_shapes ggml_vk_conv_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) { 8729 auto n_tiles = [&](vk_conv_shapes s) { 8730 return CEIL_DIV(K, vk_conv_block_sizes[s].K) 8731 * CEIL_DIV(NPQ, vk_conv_block_sizes[s].NPQ); 8732 }; 8733 8734 // We can't query number of shader cores on Intel, use 32 as a placeholder 8735 // so small convolutions will still choose a smaller tile. 8736 const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32; 8737 8738 // 128x128 isn't used with cm1 due to shared memory size; fall through to a smaller tile. 8739 bool allow_128x128 = true; 8740 #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) 8741 if (!ctx->device->coopmat2 && ctx->device->coopmat_support && ctx->device->coopmat_support_16x16x16_f16acc) { 8742 allow_128x128 = false; 8743 } 8744 #endif 8745 8746 if (allow_128x128 && K > 64 && n_tiles(CONV_SHAPE_128x128) >= shader_core_count * 2) { 8747 return CONV_SHAPE_128x128; 8748 } else if (K <= 32 && n_tiles(CONV_SHAPE_32x256) >= shader_core_count * 2) { 8749 return CONV_SHAPE_32x256; 8750 } else if (K <= 64 && n_tiles(CONV_SHAPE_64x128) >= shader_core_count * 2) { 8751 return CONV_SHAPE_64x128; 8752 } else if (!allow_128x128 && K > 64 && n_tiles(CONV_SHAPE_64x128) >= shader_core_count * 2) { 8753 // cm1 fallback for large K when 128x128 isn't available 8754 return CONV_SHAPE_64x128; 8755 } else { 8756 return CONV_SHAPE_64x32; 8757 } 8758 } 8759 8760 static vk_conv_shapes ggml_vk_conv3d_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) { 8761 const auto & block = vk_conv_block_sizes[CONV_SHAPE_256x128]; 8762 const uint32_t shader_core_count = ctx->device->shader_core_count; 8763 // Slowdowns were observed on DGX Spark with drivers older than R615. 8764 const bool driver_supported = ctx->device->driver_id != vk::DriverId::eNvidiaProprietary || 8765 (ctx->device->properties.driverVersion >> 22) >= 615; 8766 if (ctx->device->coopmat2 && shader_core_count > 0 && K % block.K == 0 && driver_supported) { 8767 const uint64_t n_tiles = (uint64_t)(K / block.K) * CEIL_DIV((uint64_t)NPQ, block.NPQ); 8768 // Use the largest cm2 padding and include the dummy Csh[8]. 8769 const uint32_t pad = 8, csh_elems = 8; 8770 const uint32_t shmem = (block.K * (block.CRS + pad) + block.CRS * (block.NPQ + pad) + csh_elems) * sizeof(uint16_t); 8771 // Reuse each loaded input across 256 output channels instead of 128. 8772 // Require full channel tiles and at least as many workgroups as GPU cores. 8773 if (n_tiles >= shader_core_count && shmem <= ctx->device->properties.limits.maxComputeSharedMemorySize) { 8774 return CONV_SHAPE_256x128; 8775 } 8776 } 8777 return ggml_vk_conv_select_shape(ctx, K, NPQ); 8778 } 8779 8780 static vk_pipeline ggml_vk_rms_norm_pipeline(const std::array & pipelines, int64_t ncols) { 8781 if (pipelines[0] && ncols <= 128) { 8782 return pipelines[0]; 8783 } 8784 if (pipelines[1] && ncols <= 256) { 8785 return pipelines[1]; 8786 } 8787 return pipelines[2]; 8788 } 8789 8790 static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * dst, ggml_op op) { 8791 switch (op) { 8792 case GGML_OP_GET_ROWS: 8793 GGML_ASSERT(src1->type == GGML_TYPE_I32); 8794 if (src0->type == GGML_TYPE_I32) { 8795 // i32 src only supports i32 result 8796 GGML_ASSERT(dst->type == GGML_TYPE_I32); 8797 return ctx->device->pipeline_get_rows[src0->type]; 8798 } 8799 if (dst->type == GGML_TYPE_F16) { 8800 return ctx->device->pipeline_get_rows[src0->type]; 8801 } 8802 if (dst->type == GGML_TYPE_F32) { 8803 return ctx->device->pipeline_get_rows_f32[src0->type]; 8804 } 8805 return nullptr; 8806 case GGML_OP_GET_ROWS_BACK: 8807 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) { 8808 return ctx->device->pipeline_get_rows_back_f32; 8809 } 8810 return nullptr; 8811 case GGML_OP_ACC: 8812 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8813 return ctx->device->pipeline_acc_f32; 8814 } 8815 return nullptr; 8816 case GGML_OP_SET: 8817 if (src0->type == src1->type && src0->type == dst->type && 8818 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_I32)) { 8819 return ctx->device->pipeline_set_f32; 8820 } 8821 return nullptr; 8822 case GGML_OP_ADD: 8823 case GGML_OP_SUB: 8824 case GGML_OP_MUL: 8825 case GGML_OP_DIV: 8826 if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || 8827 (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) || 8828 (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { 8829 return nullptr; 8830 } 8831 switch (op) { 8832 case GGML_OP_ADD: 8833 { 8834 if (ctx->num_additional_fused_ops > 0) { 8835 if (ctx->do_add_rms_partials) { 8836 return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops]; 8837 } else { 8838 return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops]; 8839 } 8840 } 8841 if (ctx->do_add_rms_partials) { 8842 auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms; 8843 return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16]; 8844 } else { 8845 auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add; 8846 return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16]; 8847 } 8848 } 8849 case GGML_OP_SUB: 8850 { 8851 auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub; 8852 return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16]; 8853 } 8854 case GGML_OP_MUL: 8855 { 8856 auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul; 8857 return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16]; 8858 } 8859 case GGML_OP_DIV: 8860 { 8861 auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div; 8862 return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16]; 8863 } 8864 default: 8865 break; 8866 } 8867 return nullptr; 8868 case GGML_OP_ADD_ID: 8869 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) { 8870 return ctx->device->pipeline_add_id_f32; 8871 } 8872 return nullptr; 8873 case GGML_OP_OUT_PROD: 8874 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8875 return ctx->device->pipeline_out_prod_f32; 8876 } 8877 return nullptr; 8878 case GGML_OP_CONCAT: { 8879 if (!ggml_vk_concat_supported(src0, src1, dst)) { 8880 return nullptr; 8881 } 8882 switch (ggml_vk_concat_unit_size(src0->type)) { 8883 case 1: 8884 return ctx->device->pipeline_concat_i8; 8885 case 2: 8886 return ctx->device->pipeline_concat_i16; 8887 case 4: 8888 return ctx->device->pipeline_concat_i32; 8889 case 8: 8890 return ctx->device->pipeline_concat_i64; 8891 default: 8892 return nullptr; 8893 } 8894 } 8895 case GGML_OP_UPSCALE: 8896 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8897 uint32_t mode = (ggml_get_op_params_i32(dst, 0) & (0xFF | GGML_SCALE_FLAG_ANTIALIAS)); 8898 switch (mode) { 8899 case GGML_SCALE_MODE_NEAREST: 8900 return ctx->device->pipeline_upscale_nearest_f32; 8901 case GGML_SCALE_MODE_BILINEAR: 8902 return ctx->device->pipeline_upscale_bilinear_f32; 8903 case GGML_SCALE_MODE_BICUBIC: 8904 return ctx->device->pipeline_upscale_bicubic_f32; 8905 case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS: 8906 return ctx->device->pipeline_upscale_bilinear_antialias_f32; 8907 default: 8908 return nullptr; 8909 } 8910 } 8911 return nullptr; 8912 case GGML_OP_SCALE: 8913 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8914 return ctx->device->pipeline_scale_f32; 8915 } 8916 return nullptr; 8917 case GGML_OP_SQR: 8918 if (src0->type == dst->type && 8919 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8920 return ctx->device->pipeline_sqr[dst->type == GGML_TYPE_F16]; 8921 } 8922 return nullptr; 8923 case GGML_OP_SQRT: 8924 if (src0->type == dst->type && 8925 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8926 return ctx->device->pipeline_sqrt[dst->type == GGML_TYPE_F16]; 8927 } 8928 return nullptr; 8929 case GGML_OP_SIN: 8930 if (src0->type == dst->type && 8931 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8932 return ctx->device->pipeline_sin[dst->type == GGML_TYPE_F16]; 8933 } 8934 return nullptr; 8935 case GGML_OP_COS: 8936 if (src0->type == dst->type && 8937 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8938 return ctx->device->pipeline_cos[dst->type == GGML_TYPE_F16]; 8939 } 8940 return nullptr; 8941 case GGML_OP_LOG: 8942 if (src0->type == dst->type && 8943 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8944 return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16]; 8945 } 8946 return nullptr; 8947 case GGML_OP_TRI: 8948 if (src0->type == dst->type && 8949 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8950 return ctx->device->pipeline_tri[dst->type == GGML_TYPE_F16]; 8951 } 8952 return nullptr; 8953 case GGML_OP_DIAG: 8954 if (src0->type == dst->type && 8955 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8956 return ctx->device->pipeline_diag[dst->type == GGML_TYPE_F16]; 8957 } 8958 return nullptr; 8959 case GGML_OP_CLAMP: 8960 if (src0->type == dst->type && 8961 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 8962 return ctx->device->pipeline_clamp[dst->type == GGML_TYPE_F16]; 8963 } 8964 return nullptr; 8965 case GGML_OP_PAD: 8966 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8967 return ctx->device->pipeline_pad_f32; 8968 } 8969 return nullptr; 8970 case GGML_OP_PAD_REFLECT_1D: 8971 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8972 return ctx->device->pipeline_pad_reflect_1d_f32; 8973 } 8974 return nullptr; 8975 case GGML_OP_ROLL: 8976 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8977 return ctx->device->pipeline_roll_f32; 8978 } 8979 return nullptr; 8980 case GGML_OP_REPEAT: 8981 if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) { 8982 return ctx->device->pipeline_repeat_i32; 8983 } 8984 if (ggml_type_size(src0->type) == 2 && ggml_type_size(dst->type) == 2) { 8985 return ctx->device->pipeline_repeat_i16; 8986 } 8987 return nullptr; 8988 case GGML_OP_REPEAT_BACK: 8989 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 8990 return ctx->device->pipeline_repeat_back_f32; 8991 } 8992 return nullptr; 8993 case GGML_OP_CPY: 8994 case GGML_OP_CONT: 8995 case GGML_OP_DUP: 8996 return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type); 8997 case GGML_OP_SET_ROWS: 8998 { 8999 if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) { 9000 return nullptr; 9001 } 9002 const int src_idx = src0->type == GGML_TYPE_F16; 9003 if (src1->type == GGML_TYPE_I64) { 9004 return ctx->device->pipeline_set_rows_i64[src_idx][dst->type]; 9005 } else if (src1->type == GGML_TYPE_I32) { 9006 return ctx->device->pipeline_set_rows_i32[src_idx][dst->type]; 9007 } 9008 return nullptr; 9009 } 9010 case GGML_OP_SILU_BACK: 9011 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9012 return ctx->device->pipeline_silu_back_f32; 9013 } 9014 return nullptr; 9015 case GGML_OP_NORM: 9016 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9017 return ctx->device->pipeline_norm_f32; 9018 } 9019 return nullptr; 9020 case GGML_OP_GROUP_NORM: 9021 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9022 return ctx->device->pipeline_group_norm_f32; 9023 } 9024 return nullptr; 9025 case GGML_OP_RMS_NORM: 9026 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9027 if (ctx->do_add_rms_partials) { 9028 return ctx->fused_rms_norm_mode == RMS_NORM_MUL ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32; 9029 } 9030 return ggml_vk_rms_norm_pipeline(ctx->fused_rms_norm_mode == RMS_NORM_MUL ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32, src0->ne[0]); 9031 } 9032 return nullptr; 9033 case GGML_OP_RMS_NORM_BACK: 9034 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9035 return ctx->device->pipeline_rms_norm_back_f32; 9036 } 9037 return nullptr; 9038 case GGML_OP_L2_NORM: 9039 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9040 return ctx->device->pipeline_l2_norm_f32; 9041 } 9042 return nullptr; 9043 case GGML_OP_UNARY: 9044 if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || 9045 (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) || 9046 (src0->type != dst->type)) { 9047 return nullptr; 9048 } 9049 9050 switch (ggml_get_unary_op(dst)) { 9051 case GGML_UNARY_OP_EXP: 9052 return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16]; 9053 case GGML_UNARY_OP_EXPM1: 9054 return ctx->device->pipeline_expm1[dst->type == GGML_TYPE_F16]; 9055 case GGML_UNARY_OP_ELU: 9056 return ctx->device->pipeline_elu[dst->type == GGML_TYPE_F16]; 9057 case GGML_UNARY_OP_SILU: 9058 return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16]; 9059 case GGML_UNARY_OP_GELU: 9060 return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16]; 9061 case GGML_UNARY_OP_GELU_ERF: 9062 return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16]; 9063 case GGML_UNARY_OP_GELU_QUICK: 9064 return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16]; 9065 case GGML_UNARY_OP_RELU: 9066 return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16]; 9067 case GGML_UNARY_OP_XIELU: 9068 return ctx->device->pipeline_xielu[dst->type == GGML_TYPE_F16]; 9069 case GGML_UNARY_OP_NEG: 9070 return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16]; 9071 case GGML_UNARY_OP_TANH: 9072 return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16]; 9073 case GGML_UNARY_OP_SIGMOID: 9074 return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16]; 9075 case GGML_UNARY_OP_HARDSIGMOID: 9076 return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16]; 9077 case GGML_UNARY_OP_HARDSWISH: 9078 return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16]; 9079 case GGML_UNARY_OP_ABS: 9080 return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16]; 9081 case GGML_UNARY_OP_SOFTPLUS: 9082 return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16]; 9083 case GGML_UNARY_OP_STEP: 9084 return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16]; 9085 case GGML_UNARY_OP_ROUND: 9086 return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16]; 9087 case GGML_UNARY_OP_CEIL: 9088 return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16]; 9089 case GGML_UNARY_OP_FLOOR: 9090 return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16]; 9091 case GGML_UNARY_OP_TRUNC: 9092 return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16]; 9093 case GGML_UNARY_OP_SGN: 9094 return ctx->device->pipeline_sgn[dst->type == GGML_TYPE_F16]; 9095 default: 9096 break; 9097 } 9098 return nullptr; 9099 case GGML_OP_GLU: 9100 if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || 9101 (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) || 9102 (src0->type != dst->type)) { 9103 return nullptr; 9104 } 9105 9106 switch (ggml_get_glu_op(dst)) { 9107 case GGML_GLU_OP_GEGLU: 9108 return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16]; 9109 case GGML_GLU_OP_REGLU: 9110 return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16]; 9111 case GGML_GLU_OP_SWIGLU: 9112 return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16]; 9113 case GGML_GLU_OP_SWIGLU_OAI: 9114 return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16]; 9115 case GGML_GLU_OP_SWIGLU_CLAMP: 9116 return ctx->device->pipeline_swiglu_clamp[dst->type == GGML_TYPE_F16]; 9117 case GGML_GLU_OP_GEGLU_ERF: 9118 return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16]; 9119 case GGML_GLU_OP_GEGLU_QUICK: 9120 return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16]; 9121 default: 9122 break; 9123 } 9124 return nullptr; 9125 case GGML_OP_DIAG_MASK_INF: 9126 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9127 return ctx->device->pipeline_diag_mask_inf_f32; 9128 } 9129 return nullptr; 9130 case GGML_OP_SOFT_MAX: 9131 GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); 9132 GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32); 9133 9134 if (ctx->num_additional_fused_ops) { 9135 uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0]))); 9136 GGML_ASSERT(idx < num_topk_moe_pipelines); 9137 // use n_experts from push constant if it's not equal to the power of two spec constant 9138 bool use_push = dst->ne[0] != (1u << idx); 9139 return ctx->device->pipeline_topk_moe[idx][use_push]; 9140 } 9141 9142 if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) { 9143 return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32; 9144 } 9145 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) { 9146 return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16; 9147 } 9148 return nullptr; 9149 case GGML_OP_SOFT_MAX_BACK: 9150 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9151 return ctx->device->pipeline_soft_max_back_f32; 9152 } 9153 return nullptr; 9154 case GGML_OP_ROPE: 9155 case GGML_OP_ROPE_BACK: 9156 { 9157 const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst; 9158 const int mode = ((const int32_t *) rope->op_params)[2]; 9159 const bool is_neox = mode & GGML_ROPE_TYPE_NEOX; 9160 const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; 9161 const bool is_vision = mode == GGML_ROPE_TYPE_VISION; 9162 9163 if (is_neox) { 9164 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9165 return ctx->device->pipeline_rope_neox_f32; 9166 } 9167 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) { 9168 return ctx->device->pipeline_rope_neox_f32_f16; 9169 } 9170 if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { 9171 return ctx->device->pipeline_rope_neox_f16; 9172 } 9173 } else if (is_mrope && !is_vision) { 9174 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9175 return ctx->device->pipeline_rope_multi_f32; 9176 } 9177 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) { 9178 return ctx->device->pipeline_rope_multi_f32_f16; 9179 } 9180 if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { 9181 return ctx->device->pipeline_rope_multi_f16; 9182 } 9183 } else if (is_vision) { 9184 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9185 return ctx->device->pipeline_rope_vision_f32; 9186 } 9187 if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { 9188 return ctx->device->pipeline_rope_vision_f16; 9189 } 9190 } else { 9191 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9192 return ctx->device->pipeline_rope_norm_f32; 9193 } 9194 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) { 9195 return ctx->device->pipeline_rope_norm_f32_f16; 9196 } 9197 if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { 9198 return ctx->device->pipeline_rope_norm_f16; 9199 } 9200 } 9201 return nullptr; 9202 } 9203 case GGML_OP_SUM: 9204 case GGML_OP_SUM_ROWS: 9205 case GGML_OP_MEAN: 9206 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9207 return ctx->device->pipeline_sum_rows_f32; 9208 } 9209 return nullptr; 9210 case GGML_OP_CROSS_ENTROPY_LOSS: 9211 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9212 return src0->ne[0] > 1024 ? ctx->device->pipeline_cross_entropy_loss_f32_wg512 : ctx->device->pipeline_cross_entropy_loss_f32; 9213 } 9214 return nullptr; 9215 case GGML_OP_CROSS_ENTROPY_LOSS_BACK: 9216 // src0 is the scalar grad; src1 is logits 9217 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2 && src2->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9218 return src1->ne[0] > 1024 ? ctx->device->pipeline_cross_entropy_loss_back_f32_wg512 : ctx->device->pipeline_cross_entropy_loss_back_f32; 9219 } 9220 return nullptr; 9221 case GGML_OP_CUMSUM: 9222 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9223 if (src0->ne[0] <= 512) { 9224 return ctx->device->pipeline_cumsum_small_f32; 9225 } else { 9226 return ctx->device->pipeline_cumsum_f32; 9227 } 9228 } 9229 return nullptr; 9230 case GGML_OP_SOLVE_TRI: 9231 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9232 9233 vk_solve_tri_pipeline_state solve_tri_pipeline_state(src0->ne[0], src1->ne[0]); 9234 9235 vk_pipeline pipeline = nullptr; 9236 9237 { 9238 std::lock_guard guard(ctx->device->compile_mutex); 9239 auto it = ctx->device->pipeline_solve_tri_f32.find(solve_tri_pipeline_state); 9240 if (it != ctx->device->pipeline_solve_tri_f32.end()) { 9241 pipeline = it->second; 9242 } else { 9243 ctx->device->pipeline_solve_tri_f32[solve_tri_pipeline_state] = pipeline = std::make_shared(); 9244 } 9245 } 9246 9247 return pipeline; 9248 } 9249 return nullptr; 9250 case GGML_OP_ARGMAX: 9251 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) { 9252 return ctx->device->pipeline_argmax_f32; 9253 } 9254 return nullptr; 9255 case GGML_OP_COUNT_EQUAL: 9256 if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) { 9257 return ctx->device->pipeline_count_equal_i32; 9258 } 9259 return nullptr; 9260 case GGML_OP_IM2COL: 9261 if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9262 return ctx->device->pipeline_im2col_f32; 9263 } 9264 if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) { 9265 return ctx->device->pipeline_im2col_f32_f16; 9266 } 9267 return nullptr; 9268 case GGML_OP_IM2COL_3D: 9269 if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9270 return ctx->device->pipeline_im2col_3d_f32; 9271 } 9272 if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) { 9273 return ctx->device->pipeline_im2col_3d_f32_f16; 9274 } 9275 return nullptr; 9276 case GGML_OP_TIMESTEP_EMBEDDING: 9277 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9278 return ctx->device->pipeline_timestep_embedding_f32; 9279 } 9280 return nullptr; 9281 case GGML_OP_CONV_TRANSPOSE_1D: 9282 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9283 return ctx->device->pipeline_conv_transpose_1d_f32; 9284 } 9285 return nullptr; 9286 case GGML_OP_COL2IM_1D: 9287 switch (src0->type) { 9288 case GGML_TYPE_F32: return ctx->device->pipeline_col2im_1d_f32; 9289 case GGML_TYPE_F16: return ctx->device->pipeline_col2im_1d_f16; 9290 case GGML_TYPE_BF16: return ctx->device->pipeline_col2im_1d_bf16; 9291 default: return nullptr; 9292 } 9293 case GGML_OP_POOL_1D: 9294 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9295 return ctx->device->pipeline_pool1d_f32; 9296 } 9297 return nullptr; 9298 case GGML_OP_POOL_2D: 9299 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9300 // Wide windows use neighboring subgroup lanes to read neighboring inputs. 9301 if (ctx->device->pipeline_pool2d_subgroup_f32 && dst->op_params[1] >= int32_t(ctx->device->subgroup_size)) { 9302 return ctx->device->pipeline_pool2d_subgroup_f32; 9303 } 9304 return ctx->device->pipeline_pool2d_f32; 9305 } 9306 return nullptr; 9307 case GGML_OP_RWKV_WKV6: 9308 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9309 return ctx->device->pipeline_rwkv_wkv6_f32; 9310 } 9311 return nullptr; 9312 case GGML_OP_RWKV_WKV7: 9313 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9314 return ctx->device->pipeline_rwkv_wkv7_f32; 9315 } 9316 return nullptr; 9317 case GGML_OP_GATED_LINEAR_ATTN: 9318 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9319 return ctx->device->pipeline_gated_linear_attn_f32; 9320 } 9321 return nullptr; 9322 case GGML_OP_LIGHTNING_INDEXER: 9323 // only the k type selects a pipeline, the other types are fixed by ggml_lightning_indexer() 9324 if (ggml_vk_lightning_indexer_k_type_supported(src1->type)) { 9325 return ctx->device->pipeline_lightning_indexer_f32[src1->type]; 9326 } 9327 return nullptr; 9328 case GGML_OP_GATED_DELTA_NET: 9329 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9330 const uint32_t S_v = dst->src[2]->ne[0]; 9331 const uint32_t kda = (dst->src[3]->ne[0] == (int64_t)S_v) ? 1 : 0; 9332 uint32_t si; 9333 switch (S_v) { 9334 case 16: si = 0; break; 9335 case 32: si = 1; break; 9336 case 64: si = 2; break; 9337 case 128: si = 3; break; 9338 default: return nullptr; 9339 } 9340 return ctx->device->pipeline_gated_delta_net[si][kda]; 9341 } 9342 return nullptr; 9343 case GGML_OP_SSM_SCAN: 9344 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9345 const uint32_t d_state = src0->ne[0]; 9346 if (d_state == 128) { 9347 return ctx->device->pipeline_ssm_scan_f32_d128; 9348 } else if (d_state == 256) { 9349 return ctx->device->pipeline_ssm_scan_f32_d256; 9350 } 9351 } 9352 return nullptr; 9353 case GGML_OP_SSM_CONV: 9354 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9355 switch (ctx->num_additional_fused_ops) { 9356 case 0: return ctx->device->pipeline_ssm_conv_f32; 9357 case 1: return ctx->device->pipeline_ssm_conv_silu_f32; 9358 case 2: return ctx->device->pipeline_ssm_conv_bias_silu_f32; 9359 default: return nullptr; 9360 } 9361 } 9362 return nullptr; 9363 case GGML_OP_OPT_STEP_ADAMW: 9364 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9365 return ctx->device->pipeline_opt_step_adamw_f32; 9366 } 9367 return nullptr; 9368 case GGML_OP_OPT_STEP_SGD: 9369 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9370 return ctx->device->pipeline_opt_step_sgd_f32; 9371 } 9372 return nullptr; 9373 case GGML_OP_LEAKY_RELU: 9374 if (src0->type == dst->type && 9375 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) { 9376 return ctx->device->pipeline_leaky_relu[dst->type == GGML_TYPE_F16]; 9377 } 9378 return nullptr; 9379 case GGML_OP_CONV_2D: 9380 case GGML_OP_CONV_TRANSPOSE_2D: 9381 if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9382 uint32_t K = dst->ne[2]; // Cout 9383 uint32_t NPQ = dst->ne[3] * dst->ne[1] * dst->ne[0]; // N * OH * OW 9384 vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, K, NPQ); 9385 9386 bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D; 9387 uint32_t KW = (uint32_t)src0->ne[0]; 9388 uint32_t KH = (uint32_t)src0->ne[1]; 9389 uint32_t s0 = (uint32_t)(ggml_get_op_params_i32(dst, 0)); 9390 uint32_t s1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 1) : s0; 9391 uint32_t p0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0; 9392 uint32_t p1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 3) : 0; 9393 uint32_t d0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 4) : 1; 9394 uint32_t d1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 5) : 1; 9395 9396 // tile-aligned shapes let the shader skip bounds checks 9397 const uint32_t Cin = (uint32_t)src1->ne[2]; 9398 const uint32_t CRS = Cin * KW * KH; 9399 const uint32_t BS_K = vk_conv_block_sizes[shape].K; 9400 const uint32_t BS_CRS = vk_conv_block_sizes[shape].CRS; 9401 const uint32_t BS_NPQ = vk_conv_block_sizes[shape].NPQ; 9402 const uint32_t aligned = ((K % BS_K == 0) && 9403 (CRS % BS_CRS == 0) && 9404 (NPQ % BS_NPQ == 0)) ? 1u : 0u; 9405 9406 vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH, aligned); 9407 9408 std::map *pipelines = nullptr; 9409 if (op == GGML_OP_CONV_2D) { 9410 if (src0->type == GGML_TYPE_F32) { 9411 pipelines = &ctx->device->pipeline_conv2d_f32[shape]; 9412 } else if (src0->type == GGML_TYPE_F16) { 9413 pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape]; 9414 } 9415 } else if (op == GGML_OP_CONV_TRANSPOSE_2D) { 9416 if (src0->type == GGML_TYPE_F32) { 9417 pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape]; 9418 } else if (src0->type == GGML_TYPE_F16) { 9419 pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape]; 9420 } 9421 } 9422 9423 vk_pipeline pipeline = nullptr; 9424 9425 { 9426 std::lock_guard guard(ctx->device->compile_mutex); 9427 auto it = pipelines->find(conv2d_pipeline_state); 9428 if (it != pipelines->end()) { 9429 pipeline = it->second; 9430 } else { 9431 (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared(); 9432 } 9433 } 9434 9435 return pipeline; 9436 } 9437 return nullptr; 9438 case GGML_OP_CONV_2D_DW: 9439 if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9440 if (ggml_is_contiguous(src1)) { 9441 return ctx->device->pipeline_conv2d_dw_whcn_f32; 9442 } else if (ggml_is_contiguous_channels(src1)) { 9443 return ctx->device->pipeline_conv2d_dw_cwhn_f32; 9444 } 9445 } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) { 9446 if (ggml_is_contiguous(src1)) { 9447 return ctx->device->pipeline_conv2d_dw_whcn_f16_f32; 9448 } else if (ggml_is_contiguous_channels(src1)) { 9449 return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32; 9450 } 9451 } 9452 return nullptr; 9453 case GGML_OP_CONV_3D: 9454 if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9455 const uint32_t OC = (uint32_t)ggml_get_op_params_i32(dst, 11); 9456 const uint32_t IC = (uint32_t)ggml_get_op_params_i32(dst, 9); 9457 const uint32_t N = (uint32_t)ggml_get_op_params_i32(dst, 10); 9458 const uint32_t NPQ = N * dst->ne[2] * dst->ne[1] * dst->ne[0]; 9459 const vk_conv_shapes shape = ggml_vk_conv3d_select_shape(ctx, OC, NPQ); 9460 9461 const uint32_t KW = (uint32_t)src0->ne[0]; 9462 const uint32_t KH = (uint32_t)src0->ne[1]; 9463 const uint32_t KD = (uint32_t)src0->ne[2]; 9464 const uint32_t s0 = (uint32_t)ggml_get_op_params_i32(dst, 0); 9465 const uint32_t s1 = (uint32_t)ggml_get_op_params_i32(dst, 1); 9466 const uint32_t s2 = (uint32_t)ggml_get_op_params_i32(dst, 2); 9467 const uint32_t p0 = (uint32_t)ggml_get_op_params_i32(dst, 3); 9468 const uint32_t p1 = (uint32_t)ggml_get_op_params_i32(dst, 4); 9469 const uint32_t p2 = (uint32_t)ggml_get_op_params_i32(dst, 5); 9470 const uint32_t d0 = (uint32_t)ggml_get_op_params_i32(dst, 6); 9471 const uint32_t d1 = (uint32_t)ggml_get_op_params_i32(dst, 7); 9472 const uint32_t d2 = (uint32_t)ggml_get_op_params_i32(dst, 8); 9473 9474 const uint32_t CRS = IC * KW * KH * KD; 9475 const uint32_t BS_K = vk_conv_block_sizes[shape].K; 9476 const uint32_t BS_CRS = vk_conv_block_sizes[shape].CRS; 9477 const uint32_t BS_NPQ = vk_conv_block_sizes[shape].NPQ; 9478 const uint32_t aligned = ((OC % BS_K == 0) && 9479 (CRS % BS_CRS == 0) && 9480 (NPQ % BS_NPQ == 0)) ? 1u : 0u; 9481 9482 vk_conv3d_pipeline_state conv3d_pipeline_state(s0, s1, s2, p0, p1, p2, d0, d1, d2, KW, KH, KD, aligned); 9483 9484 std::map *pipelines = nullptr; 9485 if (src0->type == GGML_TYPE_F32) { 9486 pipelines = &ctx->device->pipeline_conv3d_f32[shape]; 9487 } else if (src0->type == GGML_TYPE_F16) { 9488 pipelines = &ctx->device->pipeline_conv3d_f16_f32[shape]; 9489 } else { 9490 return nullptr; 9491 } 9492 9493 vk_pipeline pipeline = nullptr; 9494 9495 { 9496 std::lock_guard guard(ctx->device->compile_mutex); 9497 auto it = pipelines->find(conv3d_pipeline_state); 9498 if (it != pipelines->end()) { 9499 pipeline = it->second; 9500 } else { 9501 (*pipelines)[conv3d_pipeline_state] = pipeline = std::make_shared(); 9502 } 9503 } 9504 9505 return pipeline; 9506 } 9507 return nullptr; 9508 case GGML_OP_ADD1: 9509 if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { 9510 return ctx->device->pipeline_add1_f16_f16; 9511 } 9512 if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) { 9513 return ctx->device->pipeline_add1_f16_f32; 9514 } 9515 if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { 9516 return ctx->device->pipeline_add1_f32_f32; 9517 } 9518 return nullptr; 9519 case GGML_OP_ARANGE: 9520 if (dst->type == GGML_TYPE_F32) { 9521 return ctx->device->pipeline_arange_f32; 9522 } 9523 return nullptr; 9524 case GGML_OP_FILL: 9525 if (dst->type == GGML_TYPE_F32) { 9526 return ctx->device->pipeline_fill_f32; 9527 } 9528 if (dst->type == GGML_TYPE_F16) { 9529 return ctx->device->pipeline_fill_f16; 9530 } 9531 return nullptr; 9532 default: 9533 return nullptr; 9534 } 9535 9536 GGML_UNUSED(src2); 9537 } 9538 9539 template 9540 static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst, ggml_op op, PC&& pc, vk_pipeline pipeline_override = nullptr) { 9541 VK_LOG_DEBUG("ggml_vk_op_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3]; 9542 if (src1 != nullptr) { 9543 std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3]; 9544 } 9545 if (src2 != nullptr) { 9546 std::cerr << "), (" << src2 << ", name=" << src2->name << ", type=" << src2->type << ", ne0=" << src2->ne[0] << ", ne1=" << src2->ne[1] << ", ne2=" << src2->ne[2] << ", ne3=" << src2->ne[3] << ", nb0=" << src2->nb[0] << ", nb1=" << src2->nb[1] << ", nb2=" << src2->nb[2] << ", nb3=" << src2->nb[3]; 9547 } 9548 if (src3 != nullptr) { 9549 std::cerr << "), (" << src3 << ", name=" << src3->name << ", type=" << src3->type << ", ne0=" << src3->ne[0] << ", ne1=" << src3->ne[1] << ", ne2=" << src3->ne[2] << ", ne3=" << src3->ne[3] << ", nb0=" << src3->nb[0] << ", nb1=" << src3->nb[1] << ", nb2=" << src3->nb[2] << ", nb3=" << src3->nb[3]; 9550 } 9551 std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3]; 9552 std::cerr << "), " << ggml_op_name(op) << ")"); 9553 GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || op == GGML_OP_CONCAT || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT 9554 GGML_ASSERT(dst->buffer != nullptr); 9555 const uint64_t ne00 = src0->ne[0]; 9556 const uint64_t ne01 = src0->ne[1]; 9557 const uint64_t ne02 = src0->ne[2]; 9558 const uint64_t ne03 = src0->ne[3]; 9559 9560 const bool use_src1 = src1 != nullptr; 9561 const uint64_t ne10 = use_src1 ? src1->ne[0] : 0; 9562 const uint64_t ne11 = use_src1 ? src1->ne[1] : 0; 9563 const uint64_t ne12 = use_src1 ? src1->ne[2] : 0; 9564 const uint64_t ne13 = use_src1 ? src1->ne[3] : 0; 9565 9566 const bool use_src2 = src2 != nullptr; 9567 const bool use_src3 = src3 != nullptr; 9568 9569 init_pushconst_fastdiv(pc); 9570 9571 vk_pipeline pipeline; 9572 if (pipeline_override) { 9573 pipeline = pipeline_override; 9574 } else { 9575 pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op); 9576 } 9577 9578 if (pipeline == nullptr) { 9579 std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type); 9580 if (src1 != nullptr) { 9581 std::cerr << " and " << ggml_type_name(src1->type); 9582 } 9583 std::cerr << " to " << ggml_type_name(dst->type) << std::endl; 9584 GGML_ABORT("fatal error"); 9585 } 9586 9587 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 9588 9589 vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true); 9590 vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : vk_subbuffer{}; 9591 vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, true) : vk_subbuffer{}; 9592 vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, true) : vk_subbuffer{}; 9593 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); 9594 9595 // Compute misalignment offset for descriptors and store it in in push constants. 9596 init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst); 9597 9598 std::array elements; 9599 9600 switch (op) { 9601 case GGML_OP_NORM: 9602 case GGML_OP_RMS_NORM_BACK: 9603 case GGML_OP_L2_NORM: 9604 case GGML_OP_SOFT_MAX: 9605 case GGML_OP_SOFT_MAX_BACK: 9606 case GGML_OP_SUM_ROWS: 9607 case GGML_OP_CUMSUM: 9608 case GGML_OP_MEAN: 9609 case GGML_OP_ARGMAX: 9610 { 9611 const uint32_t nr = ggml_nrows(src0); 9612 if (nr > 262144) { 9613 elements = { 512, 512, CEIL_DIV(nr, 262144) }; 9614 } else if (nr > 512) { 9615 elements = { 512, CEIL_DIV(nr, 512), 1 }; 9616 } else { 9617 elements = { nr, 1, 1 }; 9618 } 9619 } break; 9620 case GGML_OP_SOLVE_TRI: 9621 { 9622 uint32_t nr = (uint32_t)(ne02 * ne03); 9623 if (nr > 262144) { 9624 elements = { 512, 512, CEIL_DIV(nr, 262144) }; 9625 } else if (nr > 512) { 9626 elements = { 512, CEIL_DIV(nr, 512), 1 }; 9627 } else { 9628 elements = { nr, 1, 1 }; 9629 } 9630 } 9631 break; 9632 case GGML_OP_RMS_NORM: 9633 if (ctx->do_add_rms_partials) { 9634 // Run one element per thread, 128 threads per workgroup 9635 elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 }; 9636 } else { 9637 elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 }; 9638 elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 9639 elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 9640 } 9641 break; 9642 9643 case GGML_OP_SUM: 9644 // We use GGML_OP_SUM_ROWS with 1 row. 9645 elements = { 1, 1, 1 }; 9646 break; 9647 case GGML_OP_GROUP_NORM: 9648 { 9649 const uint32_t num_groups = dst->op_params[0]; 9650 elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 }; 9651 } break; 9652 case GGML_OP_DIAG_MASK_INF: 9653 elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 }; 9654 break; 9655 case GGML_OP_ROPE: 9656 case GGML_OP_ROPE_BACK: 9657 { 9658 uint32_t nrows = (uint32_t)ggml_nrows(src0); 9659 uint32_t z = 1; 9660 if (nrows > ctx->device->properties.limits.maxComputeWorkGroupCount[0]) { 9661 z = CEIL_DIV(nrows, 32768); 9662 nrows = 32768; 9663 } 9664 elements = { nrows, (uint32_t)ne00, z }; 9665 9666 } break; 9667 case GGML_OP_GET_ROWS: 9668 elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) }; 9669 elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 9670 elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 9671 break; 9672 case GGML_OP_GET_ROWS_BACK: 9673 elements = { (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], 1 }; 9674 elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 9675 break; 9676 case GGML_OP_ARGSORT: 9677 GGML_ASSERT(0); 9678 break; 9679 case GGML_OP_IM2COL: 9680 { 9681 const bool is_2D = dst->op_params[6] == 1; 9682 9683 const uint32_t IC = src1->ne[is_2D ? 2 : 1]; 9684 9685 const uint32_t KH = is_2D ? src0->ne[1] : 1; 9686 const uint32_t KW = src0->ne[0]; 9687 9688 const uint32_t OH = is_2D ? dst->ne[2] : 1; 9689 const uint32_t OW = dst->ne[1]; 9690 9691 const uint32_t batch = src1->ne[is_2D ? 3 : 2]; 9692 9693 const uint32_t CHW = IC * KH * KW; 9694 // Cap X workgroups to limit concurrent IC channel reads. 9695 // The shader loops over X to cover the full CHW dimension. 9696 // AMD prefers a lower limit 9697 const uint32_t min_cap = ctx->device->vendor_id == VK_VENDOR_ID_AMD ? 512u : 4096u; 9698 const uint32_t x_elements = std::min(CHW, std::max(min_cap, OW * KH * KW)); 9699 elements = { x_elements, OW, OH * batch }; 9700 elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 9701 elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 9702 } break; 9703 case GGML_OP_IM2COL_3D: 9704 { 9705 const uint32_t IC = ((const uint32_t *)(dst->op_params))[9]; 9706 9707 const uint32_t N = ne13 / IC; 9708 9709 const uint32_t KD = ne02; 9710 const uint32_t KH = ne01; 9711 const uint32_t KW = ne00; 9712 9713 const uint32_t OD = dst->ne[3] / N; 9714 const uint32_t OH = dst->ne[2]; 9715 const uint32_t OW = dst->ne[1]; 9716 9717 const uint32_t IC_KD_KH_KW = IC*KD*KH*KW; 9718 const uint32_t N_OD_OH = N*OD*OH; 9719 9720 elements = { IC_KD_KH_KW, OW, N_OD_OH }; 9721 elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 9722 } break; 9723 case GGML_OP_TIMESTEP_EMBEDDING: 9724 { 9725 const uint32_t dim = dst->op_params[0]; 9726 uint32_t half_ceil = (dim + 1) / 2; 9727 elements = { half_ceil, (uint32_t)src0->ne[0], 1 }; 9728 } break; 9729 case GGML_OP_CONV_TRANSPOSE_1D: 9730 { 9731 elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1} 9732 } break; 9733 case GGML_OP_COL2IM_1D: 9734 { 9735 elements = { uint32_t(dst->ne[0]), uint32_t(dst->ne[1]), 1 }; 9736 } break; 9737 case GGML_OP_POOL_1D: 9738 { 9739 const uint32_t N = dst->ne[3] * dst->ne[2]; 9740 const uint32_t OC = dst->ne[1]; 9741 const uint32_t OL = dst->ne[0]; 9742 elements = { N * OC * OL, 1, 1}; 9743 } break; 9744 case GGML_OP_POOL_2D: 9745 { 9746 const uint32_t outputs = ggml_nelements(dst); 9747 const uint32_t outputs_per_workgroup = pipeline == ctx->device->pipeline_pool2d_subgroup_f32 ? 128 / ctx->device->subgroup_size : 512; 9748 const uint32_t workgroups = CEIL_DIV(outputs, outputs_per_workgroup); 9749 const uint32_t groups_y = CEIL_DIV(workgroups, ctx->device->properties.limits.maxComputeWorkGroupCount[0]); 9750 const uint32_t groups_x = CEIL_DIV(workgroups, groups_y); 9751 elements = { groups_x, groups_y, 1 }; 9752 } break; 9753 case GGML_OP_CONV_2D: 9754 case GGML_OP_CONV_TRANSPOSE_2D: 9755 if constexpr (std::is_same_v) { 9756 const uint32_t NPQ = pc.N * pc.OH * pc.OW; 9757 const vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, pc.Cout, NPQ); 9758 const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ); 9759 9760 elements = { pc.Cout, NPQ_blocks, 1 }; 9761 if (elements[1] > 512) { 9762 elements[2] = CEIL_DIV(elements[1], 512); 9763 elements[1] = 512; 9764 } 9765 } else { 9766 GGML_ABORT("invalid push constant type for CONV_2D"); 9767 } 9768 break; 9769 case GGML_OP_CONV_3D: 9770 if constexpr (std::is_same_v) { 9771 const uint32_t NPQ = pc.N * pc.OD * pc.OH * pc.OW; 9772 const vk_conv_shapes shape = ggml_vk_conv3d_select_shape(ctx, pc.OC, NPQ); 9773 const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ); 9774 9775 elements = { pc.OC, NPQ_blocks, 1 }; 9776 if (elements[1] > 512) { 9777 elements[2] = CEIL_DIV(elements[1], 512); 9778 elements[1] = 512; 9779 } 9780 } else { 9781 GGML_ABORT("invalid push constant type for CONV_3D"); 9782 } 9783 break; 9784 case GGML_OP_ADD: 9785 case GGML_OP_SUB: 9786 case GGML_OP_DIV: 9787 case GGML_OP_MUL: 9788 case GGML_OP_ADD1: 9789 case GGML_OP_OUT_PROD: 9790 case GGML_OP_ARANGE: 9791 case GGML_OP_FILL: 9792 case GGML_OP_SCALE: 9793 case GGML_OP_SQR: 9794 case GGML_OP_SQRT: 9795 case GGML_OP_SIN: 9796 case GGML_OP_COS: 9797 case GGML_OP_LOG: 9798 case GGML_OP_TRI: 9799 case GGML_OP_DIAG: 9800 case GGML_OP_CLAMP: 9801 case GGML_OP_LEAKY_RELU: 9802 case GGML_OP_PAD: 9803 case GGML_OP_PAD_REFLECT_1D: 9804 case GGML_OP_ROLL: 9805 case GGML_OP_REPEAT: 9806 case GGML_OP_REPEAT_BACK: 9807 case GGML_OP_CPY: 9808 case GGML_OP_CONCAT: 9809 case GGML_OP_UPSCALE: 9810 case GGML_OP_UNARY: 9811 case GGML_OP_GLU: 9812 case GGML_OP_CONV_2D_DW: 9813 { 9814 uint32_t ne = ggml_nelements(dst); 9815 if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) { 9816 // Convert from number of logical elements to 2- or 4-byte units. 9817 ne /= ggml_blck_size(src0->type); 9818 if ((ggml_type_size(src0->type) % 4) == 0) { 9819 ne *= ggml_type_size(src0->type) / 4; 9820 } else { 9821 ne *= ggml_type_size(src0->type) / 2; 9822 } 9823 } 9824 if (op == GGML_OP_CONCAT && ggml_is_quantized(dst->type)) { 9825 ne = ne / ggml_blck_size(dst->type) * ggml_type_size(dst->type) / ggml_vk_concat_unit_size(dst->type); 9826 } 9827 // copy_to_quant has block size of 32, and each thread does QUANT_K elements. 9828 // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements. 9829 // So divide by block size here before splitting into 512x512 groups. 9830 if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) { 9831 ne = CEIL_DIV(ne, ggml_blck_size(dst->type)); 9832 } 9833 if (ne > 262144) { 9834 elements = { 512, 512, CEIL_DIV(ne, 262144) }; 9835 } else if (ne > 512) { 9836 elements = { 512, CEIL_DIV(ne, 512), 1 }; 9837 } else { 9838 elements = { ne, 1, 1 }; 9839 } 9840 9841 if (pipeline == ctx->device->pipeline_cpy_transpose_02_32 || 9842 pipeline == ctx->device->pipeline_cpy_transpose_02_16) { 9843 // 32x32 tiles over dims 0 and 2; dim1 and dim3 are the batch 9844 elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32); 9845 elements[1] = (uint32_t)CEIL_DIV(dst->ne[2], 32); 9846 elements[2] = (uint32_t)(dst->ne[1]*dst->ne[3]); 9847 elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]); 9848 elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 9849 elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 9850 } else if (pipeline == ctx->device->pipeline_cpy_transpose_32 || 9851 pipeline == ctx->device->pipeline_cpy_transpose_16) { 9852 // 32x32 tiles 9853 elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32); 9854 elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32); 9855 elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]); 9856 elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]); 9857 elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 9858 elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 9859 } 9860 } break; 9861 case GGML_OP_ADD_ID: 9862 { 9863 elements = { (uint32_t)ne01, (uint32_t)ne02, 1 }; 9864 } break; 9865 case GGML_OP_SET_ROWS: 9866 { 9867 uint32_t ne = ggml_nelements(src0); 9868 if (ggml_is_quantized(dst->type)) { 9869 // quants run 32 threads each doing QUANT_K elements 9870 ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type)); 9871 } else { 9872 // scalar types do one element per thread, running 512 threads 9873 ne = CEIL_DIV(ne, 512); 9874 } 9875 if (ne > 262144) { 9876 elements = { 512, 512, CEIL_DIV(ne, 262144) }; 9877 } else if (ne > 512) { 9878 elements = { 512, CEIL_DIV(ne, 512), 1 }; 9879 } else { 9880 elements = { ne, 1, 1 }; 9881 } 9882 } 9883 break; 9884 case GGML_OP_SSM_CONV: 9885 { 9886 const uint32_t nr = src0->ne[1]; 9887 const uint32_t n_t = dst->ne[1]; 9888 const uint32_t n_s = dst->ne[2]; 9889 elements = { nr, n_t, n_s }; 9890 } 9891 break; 9892 default: 9893 elements = { (uint32_t)ggml_nelements(src0), 1, 1 }; 9894 break; 9895 } 9896 9897 if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) { 9898 vk_subbuffer a_buf = src0_buf; 9899 if (ctx->do_add_rms_partials) { 9900 a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset); 9901 } 9902 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 9903 { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements); 9904 } else if (op == GGML_OP_GLU) { 9905 // Empty src1 is possible in glu, but the shader needs a buffer 9906 vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf; 9907 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements); 9908 } else if (op == GGML_OP_SOFT_MAX) { 9909 // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer 9910 vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf; 9911 vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf; 9912 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements); 9913 } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) { 9914 // Empty src2 and src3 is possible in rope, but the shader needs a buffer 9915 vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf; 9916 vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf; 9917 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements); 9918 } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) { 9919 if (ctx->device->shader_int64 && ctx->device->buffer_device_address) { 9920 // buffer device address path doesn't use dst buffer 9921 dst_buf.size = 1; 9922 } 9923 // im2col uses only src1 and dst buffers 9924 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements); 9925 } else if (op == GGML_OP_COUNT_EQUAL) { 9926 // count_equal assumes that destination buffer is initialized with zeroes 9927 ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size); 9928 ggml_vk_sync_buffers(ctx, subctx); 9929 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements); 9930 } else if (op == GGML_OP_OPT_STEP_SGD) { 9931 // OPT_STEP_SGD works on src0, it does not need dst 9932 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements); 9933 } else if (use_src3) { 9934 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements); 9935 } else if (use_src2) { 9936 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements); 9937 } else if (use_src1) { 9938 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements); 9939 } else { 9940 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements); 9941 } 9942 } 9943 9944 void ggml_vk_get_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 9945 const uint32_t src0_type_size = ggml_type_size(src0->type); 9946 const uint32_t src1_type_size = ggml_type_size(src1->type); 9947 const uint32_t dst_type_size = ggml_type_size(dst->type); 9948 9949 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, { 9950 (uint32_t)ggml_nelements(src0), 9951 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 9952 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 9953 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 9954 0, 9955 0.0f, 0.0f, 0, 9956 }); 9957 } 9958 9959 void ggml_vk_get_rows_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 9960 const uint32_t src0_type_size = ggml_type_size(src0->type); 9961 const uint32_t src1_type_size = ggml_type_size(src1->type); 9962 const uint32_t dst_type_size = ggml_type_size(dst->type); 9963 9964 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS_BACK, { 9965 (uint32_t)ggml_nelements(src0), 9966 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 9967 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2], (uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 9968 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 9969 0, 9970 0.0f, 0.0f, 0, 9971 }); 9972 } 9973 9974 void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 9975 const uint32_t src0_type_size = ggml_type_size(src0->type); 9976 const uint32_t src1_type_size = ggml_type_size(src1->type); 9977 const uint32_t dst_type_size = ggml_type_size(dst->type); 9978 9979 int nb1 = dst->op_params[0] / src0_type_size; // 4 bytes of float32 9980 int nb2 = dst->op_params[1] / src0_type_size; // 4 bytes of float32 9981 int nb3 = dst->op_params[2] / src0_type_size; // 4 bytes of float32 9982 int offset = dst->op_params[3] / src0_type_size; // offset in bytes 9983 9984 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, { 9985 (uint32_t)ggml_nelements(src0), 9986 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t)nb3, 9987 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 9988 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t)nb3, 9989 0, 9990 0.0f, 0.0f, offset, 9991 }); 9992 } 9993 9994 void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) { 9995 const ggml_tensor *first_node = cgraph->nodes[node_idx]; 9996 const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; 9997 9998 // Make a list of all the tensors used by the op. 9999 // Last element of the list is the dest tensor. 10000 const ggml_tensor *tensors[MAX_PARAMETER_COUNT]; 10001 uint32_t num_srcs = ctx->num_additional_fused_ops + 2; 10002 uint32_t num_tensors = num_srcs + 1; 10003 GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT); 10004 10005 tensors[0] = first_node->src[0]; 10006 tensors[1] = first_node->src[1]; 10007 for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) { 10008 // check whether the previous result is src[0] or src[1] 10009 if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) { 10010 tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1]; 10011 } else { 10012 tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0]; 10013 } 10014 } 10015 tensors[num_srcs] = dst; 10016 10017 vk_op_multi_add_push_constants pc; 10018 pc.ne20 = (uint32_t)dst->ne[0]; 10019 pc.ne21 = (uint32_t)dst->ne[1]; 10020 pc.ne22 = (uint32_t)dst->ne[2]; 10021 pc.ne23 = (uint32_t)dst->ne[3]; 10022 10023 for (uint32_t i = 0; i < num_tensors; ++i) { 10024 const ggml_tensor *t = tensors[i]; 10025 pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float); 10026 pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float); 10027 pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float); 10028 pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float); 10029 } 10030 pc.rms_partials = ctx->do_add_rms_partials; 10031 10032 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op); 10033 10034 if (pipeline == nullptr) { 10035 std::cerr << "ggml_vulkan: Error: Missing multi_add"; 10036 GGML_ABORT("fatal error"); 10037 } 10038 10039 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10040 10041 ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT]; 10042 vk_buffer buf[MAX_PARAMETER_COUNT]; 10043 size_t offset[MAX_PARAMETER_COUNT]; 10044 bool uma[MAX_PARAMETER_COUNT]; 10045 10046 for (uint32_t i = 0; i < num_tensors; ++i) { 10047 buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context; 10048 buf[i] = nullptr; 10049 offset[i] = 0; 10050 uma[i] = false; 10051 10052 if (ctx->device->uma) { 10053 ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]); 10054 uma[i] = buf[i] != nullptr; 10055 } 10056 if (!uma[i]) { 10057 buf[i] = buf_ctx[i]->dev_buffer; 10058 offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs; 10059 } 10060 GGML_ASSERT(buf[i] != nullptr); 10061 } 10062 // If any remaining descriptors are unused, just point them at src[0] 10063 for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) { 10064 buf[i] = buf[0]; 10065 offset[i] = 0; 10066 } 10067 if (ctx->do_add_rms_partials) { 10068 buf[num_tensors] = ctx->prealloc_add_rms_partials; 10069 offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset; 10070 } 10071 10072 std::array elements; 10073 10074 uint32_t ne = ggml_nelements(dst); 10075 if (ne > 262144) { 10076 elements = { 512, 512, CEIL_DIV(ne, 262144) }; 10077 } else if (ne > 512) { 10078 elements = { 512, CEIL_DIV(ne, 512), 1 }; 10079 } else { 10080 elements = { ne, 1, 1 }; 10081 } 10082 10083 static_assert(MAX_PARAMETER_COUNT == 12); 10084 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10085 { 10086 ggml_vk_subbuffer(ctx, buf[0], offset[0]), 10087 ggml_vk_subbuffer(ctx, buf[1], offset[1]), 10088 ggml_vk_subbuffer(ctx, buf[2], offset[2]), 10089 ggml_vk_subbuffer(ctx, buf[3], offset[3]), 10090 ggml_vk_subbuffer(ctx, buf[4], offset[4]), 10091 ggml_vk_subbuffer(ctx, buf[5], offset[5]), 10092 ggml_vk_subbuffer(ctx, buf[6], offset[6]), 10093 ggml_vk_subbuffer(ctx, buf[7], offset[7]), 10094 ggml_vk_subbuffer(ctx, buf[8], offset[8]), 10095 ggml_vk_subbuffer(ctx, buf[9], offset[9]), 10096 ggml_vk_subbuffer(ctx, buf[10], offset[10]), 10097 ggml_vk_subbuffer(ctx, buf[11], offset[11]), 10098 }, pc, elements); 10099 } 10100 10101 void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10102 const uint32_t src0_type_size = ggml_type_size(src0->type); 10103 const uint32_t src1_type_size = ggml_type_size(src1->type); 10104 const uint32_t dst_type_size = ggml_type_size(dst->type); 10105 10106 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, { 10107 (uint32_t)ggml_nelements(src0), 10108 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10109 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10110 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 10111 0, 10112 0.0f, 0.0f, ctx->do_add_rms_partials, 10113 }); 10114 } 10115 10116 void ggml_vk_out_prod(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10117 const uint32_t src0_type_size = ggml_type_size(src0->type); 10118 const uint32_t src1_type_size = ggml_type_size(src1->type); 10119 const uint32_t dst_type_size = ggml_type_size(dst->type); 10120 10121 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_OUT_PROD, { 10122 (uint32_t)ggml_nelements(dst), 10123 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], 10124 (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10125 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], 10126 (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10127 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], 10128 (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 10129 0, 10130 0.0f, 0.0f, 0, 10131 }); 10132 } 10133 10134 void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10135 const uint32_t src0_type_size = ggml_type_size(src0->type); 10136 const uint32_t src1_type_size = ggml_type_size(src1->type); 10137 const uint32_t dst_type_size = ggml_type_size(dst->type); 10138 10139 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, { 10140 (uint32_t)ggml_nelements(src0), 10141 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10142 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10143 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 10144 0, 10145 0.0f, 0.0f, 0, 10146 }); 10147 } 10148 10149 void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10150 const uint32_t src0_type_size = ggml_type_size(src0->type); 10151 const uint32_t src1_type_size = ggml_type_size(src1->type); 10152 const uint32_t dst_type_size = ggml_type_size(dst->type); 10153 10154 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, { 10155 (uint32_t)ggml_nelements(src0), 10156 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10157 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10158 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 10159 0, 10160 0.0f, 0.0f, 0, 10161 }); 10162 } 10163 10164 int ggml_vk_unary_mul_op_index(ggml_unary_op op) { 10165 switch (op) { 10166 case GGML_UNARY_OP_GELU: return 0; 10167 case GGML_UNARY_OP_SIGMOID: return 1; 10168 case GGML_UNARY_OP_SILU: return 2; 10169 case GGML_UNARY_OP_SOFTPLUS: return 3; 10170 default: return -1; 10171 } 10172 } 10173 10174 void ggml_vk_unary_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { 10175 const ggml_tensor * unary = cgraph->nodes[node_idx]; 10176 ggml_tensor * mul = cgraph->nodes[node_idx + 1]; 10177 10178 // unary on src1 that tiles into src0 10179 const bool op_on_b = mul->src[1] == unary && 10180 !ggml_are_same_shape(unary->src[0], mul->src[0]) && 10181 ggml_can_repeat(unary, mul->src[0]); 10182 10183 const ggml_tensor * src0 = op_on_b ? mul->src[0] : unary->src[0]; 10184 const ggml_tensor * src1 = op_on_b ? unary->src[0] : 10185 ((mul->src[0] == unary) ? mul->src[1] : mul->src[0]); 10186 10187 const bool f16 = src0->type == GGML_TYPE_F16; 10188 const bool norepeat = ggml_are_same_shape(src0, src1); 10189 const int oi = ggml_vk_unary_mul_op_index(ggml_get_unary_op(unary)); 10190 if (oi < 0) { 10191 GGML_ABORT("fatal error"); 10192 } 10193 vk_pipeline pipeline = ctx->device->pipeline_unary_mul[oi][f16][norepeat][op_on_b]; 10194 10195 const uint32_t src0_type_size = ggml_type_size(src0->type); 10196 const uint32_t src1_type_size = ggml_type_size(src1->type); 10197 const uint32_t dst_type_size = ggml_type_size(mul->type); 10198 10199 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, mul, GGML_OP_UNARY, { 10200 (uint32_t)ggml_nelements(op_on_b ? mul : src0), 10201 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10202 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10203 (uint32_t) mul->ne[0], (uint32_t) mul->ne[1], (uint32_t) mul->ne[2],(uint32_t) mul->ne[3], (uint32_t) mul->nb[0] / dst_type_size, (uint32_t) mul->nb[1] / dst_type_size, (uint32_t) mul->nb[2] / dst_type_size, (uint32_t) mul->nb[3] / dst_type_size, 10204 0, 10205 0.0f, 0.0f, 0, 10206 }, pipeline); 10207 } 10208 10209 void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10210 const uint32_t src0_type_size = ggml_type_size(src0->type); 10211 const uint32_t src1_type_size = ggml_type_size(src1->type); 10212 const uint32_t dst_type_size = ggml_type_size(dst->type); 10213 10214 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, { 10215 (uint32_t)ggml_nelements(src0), 10216 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10217 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10218 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 10219 0, 10220 0.0f, 0.0f, 0, 10221 }); 10222 } 10223 10224 void ggml_vk_add_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) { 10225 const uint32_t src0_type_size = ggml_type_size(src0->type); 10226 const uint32_t src1_type_size = ggml_type_size(src1->type); 10227 const uint32_t src2_type_size = ggml_type_size(src2->type); 10228 10229 ggml_vk_op_f32(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, { 10230 (uint32_t)dst->ne[0], 10231 (uint32_t)dst->ne[1], 10232 (uint32_t)src0->nb[1] / src0_type_size, 10233 (uint32_t)src0->nb[2] / src0_type_size, 10234 (uint32_t)src1->nb[1] / src1_type_size, 10235 (uint32_t)src2->nb[1] / src2_type_size, 10236 }); 10237 } 10238 10239 static void ggml_vk_op_f32_wkv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_rwkv_wkv6_push_constants&& pc, int version) { 10240 GGML_ASSERT(version == 6 || version == 7); 10241 int num_srcs = version == 6 ? 6 : 7; 10242 10243 for (int i = 0; i < num_srcs; i++) { 10244 GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type)); 10245 } 10246 10247 GGML_ASSERT(dst->buffer != nullptr); 10248 10249 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op); 10250 GGML_ASSERT(pipeline != nullptr); 10251 10252 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10253 10254 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 10255 vk_subbuffer src_buf[7] = {}; 10256 for (int i = 0; i < num_srcs; i++) { 10257 src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); 10258 } 10259 10260 std::array elements = { 10261 (uint32_t)(pc.B * pc.H), 10262 1, 10263 1 10264 }; 10265 10266 if (version == 6) { 10267 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10268 {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, 10269 pc, elements); 10270 } else if (version == 7) { 10271 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10272 {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf}, 10273 pc, elements); 10274 } else { 10275 // shouldn't happen 10276 GGML_ASSERT(false); 10277 } 10278 } 10279 10280 void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10281 const size_t seq_length = dst->src[0]->ne[2]; 10282 const size_t n_embed = dst->ne[0]; 10283 const size_t n_heads = dst->src[0]->ne[1]; 10284 const size_t n_seqs = dst->src[5]->ne[1]; 10285 10286 ggml_vk_op_f32_wkv( 10287 ctx, subctx, dst, 10288 { 10289 (uint32_t)n_seqs, 10290 (uint32_t)seq_length, 10291 (uint32_t)n_embed, 10292 (uint32_t)n_heads, 10293 }, 10294 6 10295 ); 10296 } 10297 10298 void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10299 const size_t seq_length = dst->src[0]->ne[2]; 10300 const size_t n_embed = dst->ne[0]; 10301 const size_t n_heads = dst->src[0]->ne[1]; 10302 const size_t n_seqs = dst->src[6]->ne[1]; 10303 10304 ggml_vk_op_f32_wkv( 10305 ctx, subctx, dst, 10306 { 10307 (uint32_t)n_seqs, 10308 (uint32_t)seq_length, 10309 (uint32_t)n_embed, 10310 (uint32_t)n_heads, 10311 }, 10312 7 10313 ); 10314 } 10315 10316 void ggml_vk_gated_linear_attn(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10317 const size_t seq_length = dst->src[0]->ne[2]; 10318 const size_t n_embed = dst->ne[0]; 10319 const size_t n_heads = dst->src[0]->ne[1]; 10320 const size_t n_seqs = dst->src[4]->ne[1]; 10321 10322 float scale; 10323 memcpy(&scale, dst->op_params, sizeof(float)); 10324 10325 GGML_ASSERT(dst->buffer != nullptr); 10326 10327 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op); 10328 GGML_ASSERT(pipeline != nullptr); 10329 10330 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10331 10332 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 10333 vk_subbuffer src_buf[5] = {}; 10334 for (int i = 0; i < 5; i++) { 10335 src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); 10336 } 10337 10338 const vk_op_gated_linear_attn_push_constants pc = { 10339 (uint32_t)n_seqs, 10340 (uint32_t)seq_length, 10341 (uint32_t)n_embed, 10342 (uint32_t)n_heads, 10343 scale, 10344 }; 10345 10346 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10347 {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], dst_buf}, 10348 pc, { (uint32_t)(n_seqs * n_heads), 1, 1 }); 10349 } 10350 10351 void ggml_vk_lightning_indexer(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10352 const ggml_tensor * q = dst->src[0]; 10353 const ggml_tensor * k = dst->src[1]; 10354 const ggml_tensor * w = dst->src[2]; 10355 const ggml_tensor * m = dst->src[3]; 10356 10357 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, q, k, w, dst, dst->op); 10358 GGML_ASSERT(pipeline != nullptr); 10359 10360 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10361 10362 const uint32_t n_kv = k->ne[2]; 10363 const uint32_t n_heads = q->ne[1]; 10364 const uint32_t n_tokens = q->ne[2]; 10365 const uint32_t n_streams = q->ne[3]; 10366 const uint32_t n_masks = m->ne[3]; 10367 10368 // one workgroup per tile of 64 keys and 8 tokens, see lightning_indexer.comp 10369 const uint32_t n_tiles_kv = CEIL_DIV(n_kv, 64); 10370 const uint32_t n_tiles_t = CEIL_DIV(n_tokens, 8); 10371 10372 // q, w and dst are f32 and m is f16, so their strides are passed in elements; 10373 // k may be quantized, so its strides stay in bytes 10374 const uint32_t q_nb1 = q->nb[1] / sizeof(float); 10375 const uint32_t q_nb2 = q->nb[2] / sizeof(float); 10376 const uint32_t q_nb3 = q->nb[3] / sizeof(float); 10377 const uint32_t k_nb2 = k->nb[2]; 10378 const uint32_t k_nb3 = k->nb[3]; 10379 const uint32_t w_nb1 = w->nb[1] / sizeof(float); 10380 const uint32_t w_nb3 = w->nb[3] / sizeof(float); 10381 const uint32_t m_nb1 = m->nb[1] / sizeof(ggml_fp16_t); 10382 const uint32_t m_nb3 = m->nb[3] / sizeof(ggml_fp16_t); 10383 const uint32_t d_nb1 = dst->nb[1] / sizeof(float); 10384 const uint32_t d_nb3 = dst->nb[3] / sizeof(float); 10385 10386 const vk_op_lightning_indexer_push_constants pc = { 10387 n_kv, n_heads, n_tokens, n_masks, 10388 q_nb1, q_nb2, q_nb3, 10389 k_nb2, k_nb3, 10390 w_nb1, w_nb3, 10391 m_nb1, m_nb3, 10392 d_nb1, d_nb3, 10393 }; 10394 10395 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10396 {ggml_vk_tensor_subbuffer(ctx, q), ggml_vk_tensor_subbuffer(ctx, k), ggml_vk_tensor_subbuffer(ctx, w), ggml_vk_tensor_subbuffer(ctx, m), ggml_vk_tensor_subbuffer(ctx, dst)}, 10397 pc, {n_tiles_kv, n_tiles_t, n_streams}); 10398 } 10399 10400 void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10401 const ggml_tensor * src_q = dst->src[0]; 10402 const ggml_tensor * src_v = dst->src[2]; 10403 const ggml_tensor * src_beta = dst->src[4]; 10404 10405 GGML_ASSERT(dst->buffer != nullptr); 10406 10407 const uint32_t S_v = (uint32_t)src_v->ne[0]; 10408 const uint32_t H = (uint32_t)src_v->ne[1]; 10409 const uint32_t n_tokens = (uint32_t)src_v->ne[2]; 10410 const uint32_t n_seqs = (uint32_t)src_v->ne[3]; 10411 10412 // K (snapshot slot count) is an op param; state holds s0 only [S_v, S_v, H, n_seqs]. 10413 const uint32_t K = (uint32_t)ggml_get_op_params_i32(dst, 0); 10414 10415 const uint32_t s_off = S_v * H * n_tokens * n_seqs; 10416 10417 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op); 10418 GGML_ASSERT(pipeline != nullptr); 10419 10420 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10421 10422 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 10423 vk_subbuffer src_buf[6] = {}; 10424 for (int i = 0; i < 6; i++) { 10425 src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); 10426 } 10427 10428 const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float)); 10429 const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float)); 10430 const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float)); 10431 const uint32_t sv1 = (uint32_t)(src_v->nb[1] / sizeof(float)); 10432 const uint32_t sv2 = (uint32_t)(src_v->nb[2] / sizeof(float)); 10433 const uint32_t sv3 = (uint32_t)(src_v->nb[3] / sizeof(float)); 10434 const uint32_t sb1 = (uint32_t)(src_beta->nb[1] / sizeof(float)); 10435 const uint32_t sb2 = (uint32_t)(src_beta->nb[2] / sizeof(float)); 10436 const uint32_t sb3 = (uint32_t)(src_beta->nb[3] / sizeof(float)); 10437 10438 const uint32_t neq1 = (uint32_t)src_q->ne[1]; 10439 const uint32_t rq3 = (uint32_t)(src_v->ne[3] / src_q->ne[3]); 10440 10441 const float scale = 1.0f / sqrtf((float)S_v); 10442 const vk_op_gated_delta_net_push_constants pc = { 10443 H, n_tokens, n_seqs, s_off, 10444 sq1, sq2, sq3, 10445 sv1, sv2, sv3, 10446 sb1, sb2, sb3, 10447 neq1, rq3, 10448 scale, 10449 K 10450 }; 10451 10452 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10453 {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, 10454 pc, { H, n_seqs, S_v }); 10455 } 10456 10457 void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10458 const ggml_tensor * src0 = dst->src[0]; 10459 const ggml_tensor * src1 = dst->src[1]; 10460 const ggml_tensor * src2 = dst->src[2]; 10461 const ggml_tensor * src3 = dst->src[3]; 10462 const ggml_tensor * src4 = dst->src[4]; 10463 const ggml_tensor * src5 = dst->src[5]; 10464 10465 GGML_ASSERT(dst->buffer != nullptr); 10466 10467 const uint32_t head_dim = src0->ne[1]; 10468 const uint32_t n_head = src1->ne[1]; 10469 const uint32_t n_group = src4->ne[1]; 10470 const uint32_t n_tok = src1->ne[2]; 10471 const uint32_t n_seq = src1->ne[3]; 10472 10473 bool is_mamba2 = (src3->nb[1] == sizeof(float)); 10474 GGML_ASSERT(is_mamba2); 10475 10476 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op); 10477 GGML_ASSERT(pipeline != nullptr); 10478 10479 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10480 10481 const int64_t s_off = ggml_nelements(src1) * sizeof(float); 10482 10483 const vk_op_ssm_scan_push_constants pc = { 10484 (uint32_t)src0->nb[2], (uint32_t)src0->nb[3], 10485 (uint32_t)src1->nb[2], (uint32_t)src1->nb[3], 10486 (uint32_t)src2->nb[1], (uint32_t)src2->nb[2], 10487 (uint32_t)src3->nb[1], 10488 (uint32_t)src4->nb[2], (uint32_t)src4->nb[3], 10489 (uint32_t)src5->nb[2], (uint32_t)src5->nb[3], 10490 (uint32_t)s_off, 10491 n_head, head_dim, n_group, n_tok, 10492 n_seq, (uint32_t) ggml_get_op_params_i32(dst, 0) 10493 }; 10494 10495 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 10496 vk_subbuffer src_buf[7] = {}; 10497 for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) { 10498 src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); 10499 } 10500 10501 std::array elements; 10502 10503 const uint32_t d_state = src0->ne[0]; 10504 uint32_t num_subgroups = d_state / ctx->device->subgroup_size; 10505 const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups); 10506 const uint32_t num_workgroups_y = n_seq; 10507 elements = { num_workgroups_x, num_workgroups_y, 1 }; 10508 10509 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10510 {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf}, 10511 pc, elements); 10512 } 10513 10514 void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { 10515 ggml_tensor * conv = cgraph->nodes[node_idx]; 10516 const ggml_tensor * src0 = conv->src[0]; 10517 const ggml_tensor * src1 = conv->src[1]; 10518 10519 // Pick the destination tensor (last node in the fused chain) and the optional bias. 10520 // Fusion modes: 0 = ssm_conv, 1 = ssm_conv+silu, 2 = ssm_conv+add(bias)+silu. 10521 ggml_tensor * dst = conv; 10522 const ggml_tensor * bias = nullptr; 10523 10524 if (ctx->num_additional_fused_ops == 1) { 10525 dst = cgraph->nodes[node_idx + 1]; // silu 10526 } else if (ctx->num_additional_fused_ops == 2) { 10527 ggml_tensor * add = cgraph->nodes[node_idx + 1]; 10528 bias = (add->src[0] == conv) ? add->src[1] : add->src[0]; 10529 dst = cgraph->nodes[node_idx + 2]; // silu 10530 } 10531 10532 // The shader always declares 4 bindings; bind src0 as a dummy when bias isn't fused. 10533 const ggml_tensor * src2 = bias ? bias : src0; 10534 10535 ggml_vk_op_f32(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SSM_CONV, { 10536 (uint32_t)src0->nb[1], (uint32_t)src0->nb[2], 10537 (uint32_t)src1->nb[1], 10538 (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2], 10539 (uint32_t)src1->ne[0], 10540 (uint32_t)src0->ne[0], 10541 (uint32_t)src0->ne[1], 10542 (uint32_t)dst->ne[1], 10543 (uint32_t)dst->ne[2], 10544 }); 10545 } 10546 10547 static void ggml_vk_op_f32_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_push_constants&& pc) { 10548 const ggml_tensor * x = dst->src[0]; 10549 const ggml_tensor * g = dst->src[1]; 10550 const ggml_tensor * gm = dst->src[2]; 10551 const ggml_tensor * gv = dst->src[3]; 10552 const ggml_tensor * p = dst->src[4]; 10553 10554 GGML_ASSERT(x->type == GGML_TYPE_F32); 10555 GGML_ASSERT(g->type == GGML_TYPE_F32); 10556 GGML_ASSERT(gm->type == GGML_TYPE_F32); 10557 GGML_ASSERT(gv->type == GGML_TYPE_F32); 10558 GGML_ASSERT(p->type == GGML_TYPE_F32); 10559 GGML_ASSERT(dst->buffer != nullptr); 10560 GGML_ASSERT(ggml_is_contiguous(x)); 10561 GGML_ASSERT(ggml_is_contiguous(g)); 10562 GGML_ASSERT(ggml_is_contiguous(gm)); 10563 GGML_ASSERT(ggml_is_contiguous(gv)); 10564 GGML_ASSERT(ggml_is_contiguous(p)); 10565 GGML_ASSERT(ggml_are_same_shape(x, g)); 10566 GGML_ASSERT(ggml_are_same_shape(x, gm)); 10567 GGML_ASSERT(ggml_are_same_shape(x, gv)); 10568 GGML_ASSERT(ggml_nelements(p) == 7); 10569 10570 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW); 10571 GGML_ASSERT(pipeline != nullptr); 10572 10573 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10574 10575 vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x); 10576 vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g); 10577 vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm); 10578 vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv); 10579 vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p); 10580 10581 std::array elements = { (uint32_t)ggml_nelements(x), 1, 1 }; 10582 10583 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10584 {x_buf, g_buf, gm_buf, gv_buf, p_buf}, 10585 pc, elements); 10586 } 10587 10588 void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10589 const size_t n = ggml_nelements(dst->src[0]); 10590 10591 ggml_vk_op_f32_opt_step_adamw( 10592 ctx, subctx, dst, 10593 { (uint32_t)n, 0, 0.0f, 0.0f, 0.0f, 0.0f } 10594 ); 10595 } 10596 10597 void ggml_vk_opt_step_sgd(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) { 10598 const size_t n = ggml_nelements(dst->src[0]); 10599 10600 ggml_vk_op_f32(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_OPT_STEP_SGD, { (uint32_t)n, 0, 0.0f, 0.0f, 0.0f, 0.0f }); 10601 } 10602 10603 void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10604 int * op_params = (int *)dst->op_params; 10605 10606 const uint32_t unit_size = ggml_vk_concat_unit_size(dst->type); 10607 const uint32_t units_per_block = ggml_type_size(dst->type) / unit_size; 10608 const uint32_t block_size = ggml_blck_size(dst->type); 10609 const bool quantized = ggml_is_quantized(dst->type); 10610 10611 // Address dimension 0 in packed storage units; higher strides may be noncontiguous. 10612 const uint32_t ne00 = src0->ne[0] / block_size * units_per_block; 10613 const uint32_t ne10 = src1->ne[0] / block_size * units_per_block; 10614 const uint32_t ne20 = dst->ne[0] / block_size * units_per_block; 10615 const uint32_t nb00 = quantized ? 1 : src0->nb[0] / unit_size; 10616 const uint32_t nb10 = quantized ? 1 : src1->nb[0] / unit_size; 10617 const uint32_t nb20 = quantized ? 1 : dst->nb[0] / unit_size; 10618 10619 vk_op_concat_push_constants pc {{ 10620 ne20 * (uint32_t)dst->ne[1] * (uint32_t)dst->ne[2] * (uint32_t)dst->ne[3], 10621 ne00, (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], nb00, (uint32_t)src0->nb[1] / unit_size, (uint32_t)src0->nb[2] / unit_size, (uint32_t)src0->nb[3] / unit_size, 10622 ne10, (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], nb10, (uint32_t)src1->nb[1] / unit_size, (uint32_t)src1->nb[2] / unit_size, (uint32_t)src1->nb[3] / unit_size, 10623 ne20, (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], nb20, (uint32_t) dst->nb[1] / unit_size, (uint32_t) dst->nb[2] / unit_size, (uint32_t) dst->nb[3] / unit_size, 10624 0, 10625 0.0f, 0.0f, op_params[0], 10626 }}; 10627 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, std::move(pc)); 10628 } 10629 10630 void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10631 const uint32_t src0_type_size = ggml_type_size(src0->type); 10632 const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0); 10633 10634 GGML_TENSOR_UNARY_OP_LOCALS 10635 10636 float sf0 = (float)ne0 / ne00; 10637 float sf1 = (float)ne1 / ne01; 10638 float sf2 = (float)ne2 / ne02; 10639 float sf3 = (float)ne3 / ne03; 10640 float pixel_offset = 0.5f; 10641 10642 if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) { 10643 sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0; 10644 sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1; 10645 pixel_offset = 0.0f; 10646 } 10647 10648 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, { 10649 (uint32_t)ggml_nelements(dst), 0, 0, 10650 (uint32_t)ne00, (uint32_t)ne01, 10651 (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size, 10652 (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, 10653 sf0, sf1, sf2, sf3, pixel_offset 10654 }); 10655 } 10656 10657 void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10658 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 10659 p.param1 = ggml_get_op_params_f32(dst, 0); 10660 p.param2 = ggml_get_op_params_f32(dst, 1); 10661 10662 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p)); 10663 } 10664 10665 void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10666 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst)); 10667 } 10668 10669 void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10670 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst)); 10671 } 10672 10673 void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10674 const uint32_t src0_type_size = ggml_type_size(src0->type); 10675 const uint32_t src1_type_size = ggml_type_size(src1->type); 10676 const uint32_t dst_type_size = ggml_type_size(dst->type); 10677 10678 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, { 10679 (uint32_t)ggml_nelements(src0), 10680 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10681 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10682 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 10683 0, 10684 0.0f, 0.0f, 0, 10685 }); 10686 } 10687 10688 void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10689 VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")"); 10690 10691 vk_op_push_constants pc = { 10692 (uint32_t)ggml_nelements(dst), 10693 1, 10694 ggml_get_op_params_f32(dst, 0), 10695 ggml_get_op_params_f32(dst, 2), 10696 0.0f, 0.0f, 10697 }; 10698 10699 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE); 10700 GGML_ASSERT(pipeline != nullptr); 10701 10702 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10703 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false); 10704 10705 std::array elements = { (uint32_t)ggml_nelements(dst), 1, 1 }; 10706 10707 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); 10708 } 10709 10710 void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 10711 VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")"); 10712 const uint64_t n = ggml_nelements(dst); 10713 GGML_ASSERT(n > 0); 10714 10715 vk_op_push_constants pc = { 10716 (uint32_t)n, 10717 1, 10718 ggml_get_op_params_f32(dst, 0), 10719 0.0f, 10720 0.0f, 0.0f, 10721 }; 10722 10723 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL); 10724 GGML_ASSERT(pipeline != nullptr); 10725 10726 // Split the task distribution to 2D to avoid exceeding maxComputeWorkGroupCount 10727 const uint32_t total_wg = CEIL_DIV(n, pipeline->wg_denoms[0]); 10728 const uint32_t wg_x = std::min(total_wg, ctx->device->properties.limits.maxComputeWorkGroupCount[0]); 10729 const uint32_t wg_y = CEIL_DIV(total_wg, wg_x); 10730 GGML_ASSERT(wg_y <= ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 10731 10732 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10733 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false); 10734 10735 std::array elements = { wg_x * pipeline->wg_denoms[0], wg_y * pipeline->wg_denoms[1], 1 }; 10736 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); 10737 } 10738 10739 void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10740 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst)); 10741 } 10742 10743 void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10744 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst)); 10745 } 10746 10747 void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10748 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst)); 10749 } 10750 10751 void ggml_vk_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10752 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 10753 p.param1 = ggml_get_op_params_f32(dst, 0); 10754 10755 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TRI, std::move(p)); 10756 } 10757 10758 void ggml_vk_diag(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10759 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst)); 10760 10761 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG, std::move(p)); 10762 } 10763 10764 void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10765 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 10766 p.param1 = ggml_get_op_params_f32(dst, 0); 10767 p.param2 = ggml_get_op_params_f32(dst, 1); 10768 10769 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p)); 10770 } 10771 10772 void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10773 vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst); 10774 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p)); 10775 } 10776 10777 void ggml_vk_pad_reflect_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10778 const uint32_t p0 = (uint32_t)dst->op_params[0]; 10779 const uint32_t p1 = (uint32_t)dst->op_params[1]; 10780 10781 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst)); 10782 memcpy(&p.param1, &p0, sizeof(float)); 10783 memcpy(&p.param2, &p1, sizeof(float)); 10784 10785 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD_REFLECT_1D, std::move(p)); 10786 } 10787 10788 void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10789 const int32_t s0 = ggml_get_op_params_i32(dst, 0); 10790 const int32_t s1 = ggml_get_op_params_i32(dst, 1); 10791 const int32_t s2 = ggml_get_op_params_i32(dst, 2); 10792 const int32_t s3 = ggml_get_op_params_i32(dst, 3); 10793 const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000); 10794 const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000); 10795 10796 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 10797 memcpy(&p.param1, &s01_packed, sizeof(float)); 10798 memcpy(&p.param2, &s23_packed, sizeof(float)); 10799 10800 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p)); 10801 } 10802 10803 void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10804 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst)); 10805 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p)); 10806 } 10807 10808 void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10809 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst)); 10810 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p)); 10811 } 10812 10813 void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10814 uint32_t ne = (uint32_t)ggml_nelements(src0); 10815 if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) { 10816 // Convert from number of logical elements to 2- or 4-byte units. 10817 ne /= ggml_blck_size(src0->type); 10818 if ((ggml_type_size(src0->type) % 4) == 0) { 10819 ne *= ggml_type_size(src0->type) / 4; 10820 } else { 10821 ne *= ggml_type_size(src0->type) / 2; 10822 } 10823 } 10824 10825 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne); 10826 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p)); 10827 } 10828 10829 void ggml_vk_set_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10830 const uint32_t src0_type_size = ggml_type_size(src0->type); 10831 const uint32_t src1_type_size = ggml_type_size(src1->type); 10832 const uint32_t dst_type_size = ggml_type_size(dst->type); 10833 10834 // Skip empty skip_rows operations. For most ops the empty check at the start 10835 // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst 10836 // with empty srcs. 10837 if (ggml_is_empty(src0) || ggml_is_empty(src1)) { 10838 return; 10839 } 10840 10841 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, { 10842 (uint32_t)ggml_nelements(src0), 10843 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 10844 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 10845 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 10846 0, 10847 0.0f, 0.0f, 0, 10848 }); 10849 } 10850 10851 void ggml_vk_silu_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 10852 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SILU_BACK, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f, 0.0f, 0.0f }); 10853 } 10854 10855 void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10856 float * op_params = (float *)dst->op_params; 10857 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 10858 p.param1 = op_params[0]; 10859 10860 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_NORM, std::move(p)); 10861 } 10862 10863 void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 10864 const int * int_op_params = (const int *)dst->op_params; 10865 const float * float_op_params = (const float *)dst->op_params; 10866 10867 const uint32_t num_groups = int_op_params[0]; 10868 const float eps = float_op_params[1]; 10869 const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups); 10870 10871 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f, 0.0f, 0.0f }); 10872 } 10873 10874 static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) { 10875 const uint32_t ne = (uint32_t)node->ne[0]; 10876 const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0]; 10877 const uint32_t num_partials = CEIL_DIV(ne, denom); 10878 return num_partials; 10879 } 10880 10881 uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) { 10882 const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node); 10883 const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment); 10884 return num_bytes; 10885 } 10886 10887 static vk_op_rope_push_constants ggml_vk_make_rope_constants(const ggml_tensor *dst, const ggml_tensor *src0, const bool has_ff, bool backprop, const uint32_t set_rows_stride) { 10888 const int n_dims = ((const int32_t *) dst->op_params)[1]; 10889 const int mode = ((const int32_t *) dst->op_params)[2]; 10890 const int n_offs = ((const int32_t *) dst->op_params)[15]; 10891 // const int n_ctx = ((const int32_t *) dst->op_params)[3]; 10892 const int n_ctx_orig = ((const int32_t *) dst->op_params)[4]; 10893 const float freq_base = ((const float *) dst->op_params)[5]; 10894 const float freq_scale = ((const float *) dst->op_params)[6]; 10895 const float ext_factor = ((const float *) dst->op_params)[7]; 10896 const float attn_factor = ((const float *) dst->op_params)[8]; 10897 const float beta_fast = ((const float *) dst->op_params)[9]; 10898 const float beta_slow = ((const float *) dst->op_params)[10]; 10899 int sections[4] {}; 10900 if (mode & GGML_ROPE_TYPE_MROPE) { 10901 memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4); 10902 } 10903 10904 const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE; 10905 10906 float corr_dims[2]; 10907 ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims); 10908 10909 const float theta_scale = powf(freq_base, -2.0f/n_dims); 10910 10911 uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type); 10912 uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type); 10913 uint32_t nb03 = src0->nb[3] / ggml_type_size(src0->type); 10914 10915 uint32_t nb11 = dst->nb[1] / ggml_type_size(dst->type); 10916 uint32_t nb12 = dst->nb[2] / ggml_type_size(dst->type); 10917 uint32_t nb13 = dst->nb[3] / ggml_type_size(dst->type); 10918 10919 vk_op_rope_push_constants rope { 10920 (uint32_t)mode, (uint32_t)ggml_nrows(src0), (uint32_t)n_dims, (uint32_t)n_offs, freq_scale, 10921 freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale, has_ff, 10922 { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride, 10923 10924 (uint32_t)src0->ne[0], 10925 (uint32_t)src0->ne[1], 10926 (uint32_t)src0->ne[2], 10927 nb01, nb02, nb03, 10928 nb11, nb12, nb13, 10929 0, 0, // a_offset, d_offset filled in by init_pushconst_tensor_offsets 10930 }; 10931 10932 return rope; 10933 } 10934 10935 static void ggml_vk_rms_norm_finish(ggml_backend_vk_context * ctx, const ggml_tensor * src0) { 10936 if (ctx->do_add_rms_partials_offset_calculation) { 10937 ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0); 10938 ctx->do_add_rms_partials = false; 10939 ctx->do_add_rms_partials_offset_calculation = false; 10940 } 10941 } 10942 10943 void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, float * op_params) { 10944 ggml_tensor * rms = cgraph->nodes[node_idx]; 10945 const ggml_tensor * src0 = rms->src[0]; 10946 10947 if (ctx->fused_rms_norm_mode == RMS_NORM_VIEW_SET_ROWS) { 10948 GGML_ASSERT(ctx->num_additional_fused_ops == 2); 10949 ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; 10950 const ggml_tensor * indices = set_rows->src[1]; 10951 vk_op_binary_push_constants pc = ggml_vk_rms_norm_push_constants(src0, src0, set_rows, op_params[0], 0); 10952 init_pushconst_tensor_offsets(ctx, pc, src0, src0, nullptr, nullptr, set_rows); 10953 10954 vk_pipeline pipeline = set_rows->type == GGML_TYPE_F16 ? 10955 ctx->device->pipeline_rms_norm_set_rows_f32_f16 : ctx->device->pipeline_rms_norm_set_rows_f32_f32; 10956 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10957 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10958 { 10959 ggml_vk_tensor_subbuffer(ctx, src0, true), 10960 ggml_vk_tensor_subbuffer(ctx, src0, true), 10961 ggml_vk_tensor_subbuffer(ctx, set_rows, true), 10962 ggml_vk_tensor_subbuffer(ctx, indices), 10963 }, pc, { 10964 (uint32_t)src0->ne[1], 10965 std::min((uint32_t)src0->ne[2], ctx->device->properties.limits.maxComputeWorkGroupCount[1]), 10966 std::min((uint32_t)src0->ne[3], ctx->device->properties.limits.maxComputeWorkGroupCount[2]), 10967 }); 10968 ggml_vk_rms_norm_finish(ctx, src0); 10969 return; 10970 } 10971 10972 if (ctx->fused_rms_norm_mode == RMS_NORM_MUL_ADD || ctx->fused_rms_norm_mode == RMS_NORM_MUL_ADD_MUL) { 10973 ggml_tensor * mul = cgraph->nodes[node_idx + 1]; 10974 ggml_tensor * add = cgraph->nodes[node_idx + 2]; 10975 const ggml_tensor * weight = mul->src[0] == rms ? mul->src[1] : mul->src[0]; 10976 const ggml_tensor * residual = add->src[0] == mul ? add->src[1] : add->src[0]; 10977 const bool do_post_multiply = ctx->fused_rms_norm_mode == RMS_NORM_MUL_ADD_MUL; 10978 GGML_ASSERT(ctx->num_additional_fused_ops == (do_post_multiply ? 3 : 2)); 10979 ggml_tensor * dst = do_post_multiply ? cgraph->nodes[node_idx + 3] : add; 10980 const ggml_tensor * post_scale = do_post_multiply ? 10981 (dst->src[0] == add ? dst->src[1] : dst->src[0]) : src0; 10982 10983 const uint32_t num_partials = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0; 10984 vk_op_binary_push_constants pc = ggml_vk_rms_norm_push_constants(src0, weight, dst, op_params[0], num_partials); 10985 init_pushconst_tensor_offsets(ctx, pc, src0, weight, residual, post_scale, dst); 10986 10987 vk_pipeline pipeline; 10988 if (ctx->do_add_rms_partials) { 10989 pipeline = do_post_multiply ? 10990 ctx->device->pipeline_rms_norm_mul_add_mul_partials_f32 : ctx->device->pipeline_rms_norm_mul_add_partials_f32; 10991 } else { 10992 pipeline = ggml_vk_rms_norm_pipeline(do_post_multiply ? 10993 ctx->device->pipeline_rms_norm_mul_add_mul_f32 : ctx->device->pipeline_rms_norm_mul_add_f32, src0->ne[0]); 10994 } 10995 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 10996 if (ctx->do_add_rms_partials) { 10997 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 10998 { 10999 ggml_vk_tensor_subbuffer(ctx, src0, true), 11000 ggml_vk_tensor_subbuffer(ctx, weight, true), 11001 ggml_vk_tensor_subbuffer(ctx, dst, true), 11002 ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset), 11003 ggml_vk_tensor_subbuffer(ctx, residual), 11004 ggml_vk_tensor_subbuffer(ctx, post_scale), 11005 }, pc, { (uint32_t)CEIL_DIV(src0->ne[0], 128), 1, 1 }); 11006 } else { 11007 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 11008 { 11009 ggml_vk_tensor_subbuffer(ctx, src0, true), 11010 ggml_vk_tensor_subbuffer(ctx, weight, true), 11011 ggml_vk_tensor_subbuffer(ctx, dst, true), 11012 ggml_vk_tensor_subbuffer(ctx, residual), 11013 ggml_vk_tensor_subbuffer(ctx, post_scale), 11014 }, pc, { 11015 (uint32_t)src0->ne[1], 11016 std::min((uint32_t)src0->ne[2], ctx->device->properties.limits.maxComputeWorkGroupCount[1]), 11017 std::min((uint32_t)src0->ne[3], ctx->device->properties.limits.maxComputeWorkGroupCount[2]), 11018 }); 11019 } 11020 ggml_vk_rms_norm_finish(ctx, src0); 11021 return; 11022 } 11023 11024 ggml_tensor * dst; 11025 const ggml_tensor * src1; 11026 11027 if (ctx->fused_rms_norm_mode != RMS_NORM_COUNT) { 11028 ggml_tensor * mul = cgraph->nodes[node_idx + 1]; 11029 dst = mul; 11030 src1 = mul->src[0] == rms ? mul->src[1] : mul->src[0]; 11031 } else { 11032 dst = rms; 11033 src1 = src0; 11034 } 11035 11036 const uint32_t num_partials = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0; 11037 vk_op_binary_push_constants bin = ggml_vk_rms_norm_push_constants(src0, src1, dst, op_params[0], num_partials); 11038 11039 if (ctx->fused_rms_norm_mode == RMS_NORM_MUL_ROPE || 11040 ctx->fused_rms_norm_mode == RMS_NORM_MUL_ROPE_VIEW_SET_ROWS) { 11041 static constexpr uint32_t max_tensors = 7; 11042 const ggml_tensor *tensors[max_tensors] {}; 11043 11044 ggml_tensor *rms = cgraph->nodes[node_idx + 0]; 11045 ggml_tensor *mul = cgraph->nodes[node_idx + 1]; 11046 ggml_tensor *rope = cgraph->nodes[node_idx + 2]; 11047 11048 ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0]; 11049 11050 bool do_set_rows = ctx->fused_rms_norm_mode == RMS_NORM_MUL_ROPE_VIEW_SET_ROWS; 11051 GGML_ASSERT(ctx->num_additional_fused_ops == (do_set_rows ? 4 : 2)); 11052 11053 tensors[0] = rms->src[0]; 11054 tensors[1] = other_src; 11055 tensors[2] = mul; 11056 tensors[3] = rope->src[1]; // pos 11057 tensors[4] = rope->src[2]; // ff 11058 tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst 11059 tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr; 11060 const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0; 11061 11062 vk_op_rms_norm_mul_rope_push_constants pc; 11063 pc.bin = bin; 11064 pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride); 11065 11066 const auto & pipelines = tensors[5]->type == GGML_TYPE_F16 ? ctx->device->pipeline_rms_norm_mul_rope_f32_f16 : ctx->device->pipeline_rms_norm_mul_rope_f32_f32; 11067 vk_pipeline pipeline = ggml_vk_rms_norm_pipeline(pipelines, src0->ne[0]); 11068 11069 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11070 11071 ggml_backend_vk_buffer_context * buf_ctx[max_tensors]; 11072 vk_buffer buf[max_tensors]; 11073 size_t offset[max_tensors]; 11074 bool uma[max_tensors]; 11075 11076 for (uint32_t i = 0; i < max_tensors; ++i) { 11077 if (!tensors[i]) { 11078 // If any remaining descriptors are unused, just point them at src[0] 11079 buf[i] = buf[0]; 11080 offset[i] = 0; 11081 continue; 11082 } 11083 buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context; 11084 buf[i] = nullptr; 11085 offset[i] = 0; 11086 uma[i] = false; 11087 11088 if (ctx->device->uma) { 11089 ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]); 11090 uma[i] = buf[i] != nullptr; 11091 } 11092 if (!uma[i]) { 11093 buf[i] = buf_ctx[i]->dev_buffer; 11094 offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs; 11095 } 11096 GGML_ASSERT(buf[i] != nullptr); 11097 } 11098 11099 // a_offset is unused (the fused path reads from shared memory), but the rope/set_rows dst can be misaligned. 11100 // Round the binding offset down to the storage buffer alignment; the in-element shift goes in pc.rope.d_offset. 11101 pc.rope.d_offset = get_misalign_bytes(ctx, tensors[5]) / ggml_type_size(tensors[5]->type); 11102 offset[5] &= ~(size_t(ctx->device->properties.limits.minStorageBufferOffsetAlignment) - 1); 11103 11104 std::array elements; 11105 elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] }; 11106 elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 11107 elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]); 11108 11109 static_assert(max_tensors == 7); 11110 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 11111 { 11112 ggml_vk_subbuffer(ctx, buf[0], offset[0]), 11113 ggml_vk_subbuffer(ctx, buf[1], offset[1]), 11114 ggml_vk_subbuffer(ctx, buf[2], offset[2]), 11115 ggml_vk_subbuffer(ctx, buf[3], offset[3]), 11116 ggml_vk_subbuffer(ctx, buf[4], offset[4]), 11117 ggml_vk_subbuffer(ctx, buf[5], offset[5]), 11118 ggml_vk_subbuffer(ctx, buf[6], offset[6]), 11119 }, pc, elements); 11120 } else { 11121 GGML_ASSERT(ctx->fused_rms_norm_mode == RMS_NORM_MUL || ctx->fused_rms_norm_mode == RMS_NORM_COUNT); 11122 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin)); 11123 } 11124 11125 ggml_vk_rms_norm_finish(ctx, src0); 11126 } 11127 11128 void ggml_vk_rms_norm_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11129 float * op_params = (float *)dst->op_params; 11130 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM_BACK, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f, 0.0f, 0.0f }); 11131 } 11132 11133 void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11134 const float * op_params = (const float *)dst->op_params; 11135 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 11136 p.param1 = op_params[0]; 11137 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_L2_NORM, std::move(p)); 11138 } 11139 11140 void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11141 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY, vk_op_unary_push_constants_init(src0, dst)); 11142 } 11143 11144 void ggml_vk_xielu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11145 float * op_params = (float *)dst->op_params; 11146 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 11147 p.param1 = op_params[1]; 11148 p.param2 = op_params[2]; 11149 p.param3 = op_params[3]; 11150 p.param4 = op_params[4]; 11151 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY, std::move(p)); 11152 } 11153 11154 void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11155 const float * op_params_f = (const float *)dst->op_params; 11156 11157 const bool swapped = (bool)dst->op_params[1]; 11158 const bool split = src1 != nullptr; 11159 const float alpha = op_params_f[2]; 11160 const float limit = op_params_f[3]; 11161 11162 if (!split) { 11163 GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]); 11164 } else { 11165 GGML_ASSERT(src0->ne[0] == src1->ne[0]); 11166 GGML_ASSERT(src0->ne[0] == dst->ne[0]); 11167 GGML_ASSERT(src0->type == src1->type); 11168 } 11169 11170 const uint32_t mode = split ? 2 : (swapped ? 1 : 0); 11171 const uint32_t src0_type_size = ggml_type_size(src0->type); 11172 const uint32_t src1_type_size = split ? ggml_type_size(src1->type) : src0_type_size; 11173 const uint32_t dst_type_size = ggml_type_size(dst->type); 11174 11175 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU, 11176 { 11177 (uint32_t)ggml_nelements(dst), 11178 (uint32_t)src0->ne[0], 11179 (uint32_t)dst->ne[0], 11180 mode, 11181 alpha, 11182 limit, 11183 (uint32_t)(src0->nb[0] / src0_type_size), 11184 (uint32_t)(src0->nb[1] / src0_type_size), 11185 (uint32_t)(src0->nb[2] / src0_type_size), 11186 (uint32_t)(src0->nb[3] / src0_type_size), 11187 (uint32_t)((split ? src1->nb[0] : src0->nb[0]) / src1_type_size), 11188 (uint32_t)((split ? src1->nb[1] : src0->nb[1]) / src1_type_size), 11189 (uint32_t)((split ? src1->nb[2] : src0->nb[2]) / src1_type_size), 11190 (uint32_t)((split ? src1->nb[3] : src0->nb[3]) / src1_type_size), 11191 (uint32_t)(dst->nb[0] / dst_type_size), 11192 (uint32_t)(dst->nb[1] / dst_type_size), 11193 (uint32_t)(dst->nb[2] / dst_type_size), 11194 (uint32_t)(dst->nb[3] / dst_type_size), 11195 (uint32_t)dst->ne[1], 11196 (uint32_t)dst->ne[2], 11197 0, 11198 0, 0, 0, 0, 0, 0, 11199 }); 11200 } 11201 11202 void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11203 int32_t * op_params = (int32_t *)dst->op_params; 11204 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] }); 11205 } 11206 11207 void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) { 11208 float * op_params = (float *)dst->op_params; 11209 11210 float scale = op_params[0]; 11211 float max_bias = op_params[1]; 11212 11213 const uint32_t ncols = (uint32_t)src0->ne[0]; 11214 const uint32_t nrows_x = (uint32_t)ggml_nrows(src0); 11215 const uint32_t nrows_y = (uint32_t)src0->ne[1]; 11216 11217 const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u; 11218 const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u; 11219 const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u; 11220 const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u; 11221 const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u; 11222 11223 const uint32_t n_head_kv = src0->ne[2]; 11224 const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv)); 11225 11226 const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); 11227 const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); 11228 11229 vk_op_soft_max_push_constants pc { 11230 ncols, 11231 src1 != nullptr ? nrows_y : (uint32_t)0, 11232 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], 11233 ne12, ne13, 11234 nb11, nb12, nb13, 11235 scale, max_bias, 11236 m0, m1, 11237 n_head_log2, 11238 nrows_x, 11239 src2 != nullptr 11240 }; 11241 11242 if (ncols <= 16384) { 11243 ggml_vk_op_f32(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, std::move(pc)); 11244 } else { 11245 11246 vk_subbuffer buf_a = ggml_vk_tensor_subbuffer(ctx, src0); 11247 vk_subbuffer buf_b = src1 ? ggml_vk_tensor_subbuffer(ctx, src1) : buf_a; 11248 vk_subbuffer buf_c = src2 ? ggml_vk_tensor_subbuffer(ctx, src2) : buf_a; 11249 vk_subbuffer buf_d = ggml_vk_tensor_subbuffer(ctx, dst); 11250 11251 uint32_t elems_per_wg = 128 * 4; 11252 uint32_t num_wgs = CEIL_DIV(ncols, elems_per_wg); 11253 size_t tmp_size = num_wgs * nrows_x * sizeof(float); 11254 11255 if (ctx->prealloc_size_x < tmp_size) { 11256 ctx->prealloc_size_x = tmp_size; 11257 ggml_vk_preallocate_buffers(ctx, subctx); 11258 } 11259 if (ctx->prealloc_size_y < tmp_size) { 11260 ctx->prealloc_size_y = tmp_size; 11261 ggml_vk_preallocate_buffers(ctx, subctx); 11262 } 11263 if (ctx->prealloc_x_need_sync || ctx->prealloc_y_need_sync) { 11264 ggml_vk_sync_buffers(ctx, subctx); 11265 } 11266 11267 vk_subbuffer buf_x = { ctx->prealloc_x, 0, tmp_size }; 11268 vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size }; 11269 11270 // the partial results overwrite a matmul input converted into prealloc_y 11271 ctx->prealloc_y_last_pipeline_used = nullptr; 11272 ctx->prealloc_y_last_tensor_used = nullptr; 11273 11274 std::array elements = { num_wgs, nrows_x, 1 }; 11275 11276 vk_pipeline pipeline1 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large1_f32_f16 : ctx->device->pipeline_soft_max_large1_f32; 11277 vk_pipeline pipeline2 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large2_f32_f16 : ctx->device->pipeline_soft_max_large2_f32; 11278 vk_pipeline pipeline3 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large3_f32_f16 : ctx->device->pipeline_soft_max_large3_f32; 11279 11280 ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1); 11281 ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1); 11282 ggml_pipeline_request_descriptor_sets(ctx, pipeline3, 1); 11283 11284 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements); 11285 ggml_vk_sync_buffers(ctx, subctx); 11286 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements); 11287 ggml_vk_sync_buffers(ctx, subctx); 11288 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline3, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements); 11289 11290 ctx->prealloc_x_need_sync = true; 11291 ctx->prealloc_y_need_sync = true; 11292 } 11293 } 11294 11295 void ggml_vk_soft_max_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11296 float * op_params = (float *)dst->op_params; 11297 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOFT_MAX_BACK, { (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), op_params[0], op_params[1], 0.0f, 0.0f }); 11298 } 11299 11300 void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) { 11301 topk_moe_mode mode = ctx->fused_topk_moe_mode; 11302 const bool has_bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS || mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS; 11303 ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0]; 11304 ggml_tensor * bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? cgraph->nodes[node_idx + 2]->src[1] : 11305 mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS ? cgraph->nodes[node_idx + 3]->src[1] : 11306 logits; 11307 ggml_tensor * weights = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; 11308 ggml_tensor * ids = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? cgraph->nodes[node_idx + 4] : 11309 mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS ? cgraph->nodes[node_idx + 5] : 11310 mode == TOPK_MOE_LATE_SOFTMAX ? cgraph->nodes[node_idx + 1] : 11311 cgraph->nodes[node_idx + 3]; 11312 11313 GGML_ASSERT(logits->type == GGML_TYPE_F32); 11314 GGML_ASSERT(bias->type == GGML_TYPE_F32); 11315 GGML_ASSERT(weights->type == GGML_TYPE_F32); 11316 GGML_ASSERT(ids->type == GGML_TYPE_I32); 11317 11318 const int n_experts = logits->ne[0]; 11319 const int n_rows = logits->ne[1]; 11320 const int n_expert_used = weights->ne[1]; 11321 11322 GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts); 11323 11324 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX); 11325 11326 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11327 11328 vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits); 11329 vk_subbuffer bias_buf = ggml_vk_tensor_subbuffer(ctx, bias); 11330 vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights); 11331 vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids); 11332 11333 vk_op_topk_moe_push_constants pc {}; 11334 pc.n_rows = n_rows; 11335 pc.n_experts_push = n_experts; 11336 pc.n_expert_used = n_expert_used; 11337 pc.clamp_min = -std::numeric_limits::infinity(); 11338 pc.clamp_max = std::numeric_limits::infinity(); 11339 if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) { 11340 ggml_tensor * clamp = cgraph->nodes[node_idx + 7]; 11341 GGML_ASSERT(clamp->op == GGML_OP_CLAMP); 11342 pc.clamp_min = ggml_get_op_params_f32(clamp, 0); 11343 pc.clamp_max = ggml_get_op_params_f32(clamp, 1); 11344 } 11345 if (mode == TOPK_MOE_SIGMOID_NORM_BIAS) { 11346 ggml_tensor * clamp = cgraph->nodes[node_idx + 8]; 11347 GGML_ASSERT(clamp->op == GGML_OP_CLAMP); 11348 pc.clamp_min = ggml_get_op_params_f32(clamp, 0); 11349 pc.clamp_max = ggml_get_op_params_f32(clamp, 1); 11350 } 11351 if (mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS) { 11352 ggml_tensor * clamp = cgraph->nodes[node_idx + 9]; 11353 GGML_ASSERT(clamp->op == GGML_OP_CLAMP); 11354 pc.clamp_min = ggml_get_op_params_f32(clamp, 0); 11355 pc.clamp_max = ggml_get_op_params_f32(clamp, 1); 11356 } 11357 11358 #define GATING_FUNC_SOFTMAX 0 11359 #define GATING_FUNC_SIGMOID 1 11360 #define GATING_FUNC_SOFTMAX_WEIGHT 2 11361 #define GATING_FUNC_SQRT_SOFTPLUS 3 11362 11363 pc.gating_func = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? GATING_FUNC_SIGMOID : 11364 mode == TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS ? GATING_FUNC_SQRT_SOFTPLUS : 11365 mode == TOPK_MOE_LATE_SOFTMAX ? GATING_FUNC_SOFTMAX_WEIGHT : 11366 GATING_FUNC_SOFTMAX; 11367 pc.has_bias = has_bias; 11368 pc.with_norm = mode == TOPK_MOE_EARLY_SOFTMAX_NORM || has_bias; 11369 if (ctx->fused_topk_moe_scale) { 11370 GGML_ASSERT(weights->op == GGML_OP_SCALE); 11371 pc.output_scale = ggml_get_op_params_f32(weights, 0); 11372 pc.output_bias = ggml_get_op_params_f32(weights, 1); 11373 } else { 11374 pc.output_scale = 1.0f; 11375 pc.output_bias = 0.0f; 11376 } 11377 11378 GGML_ASSERT(n_expert_used <= n_experts); 11379 11380 const uint32_t rows_per_block = 4; 11381 std::array elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 }; 11382 11383 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, bias_buf, weights_buf, ids_buf}, pc, elements); 11384 } 11385 11386 void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) { 11387 ggml_tensor * dst = cgraph->nodes[node_idx]; 11388 const ggml_tensor * src0 = dst->src[0]; 11389 const ggml_tensor * src1 = dst->src[1]; 11390 const ggml_tensor * src2 = dst->src[2]; 11391 const ggml_tensor * src3 = nullptr; 11392 const int n_dims = ((int32_t *) dst->op_params)[1]; 11393 const int mode = ((int32_t *) dst->op_params)[2]; 11394 // const int n_ctx = ((int32_t *) dst->op_params)[3]; 11395 const int n_ctx_orig = ((int32_t *) dst->op_params)[4]; 11396 const float freq_base = ((float *) dst->op_params)[5]; 11397 const float beta_fast = ((float *) dst->op_params)[9]; 11398 const float beta_slow = ((float *) dst->op_params)[10]; 11399 int sections[4] {}; 11400 if (mode & GGML_ROPE_TYPE_MROPE) { 11401 memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4); 11402 } 11403 11404 float corr_dims[2]; 11405 ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims); 11406 11407 uint32_t set_rows_stride = 0; 11408 // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride 11409 // and overrides the dst and sets src3=row_indices 11410 if (ctx->num_additional_fused_ops > 0) { 11411 set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type); 11412 src3 = cgraph->nodes[node_idx + 2]->src[1]; 11413 dst = cgraph->nodes[node_idx + 2]; 11414 } 11415 11416 ggml_vk_op_f32(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE, 11417 ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride)); 11418 } 11419 11420 void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11421 const uint32_t * op_params = (const uint32_t *)dst->op_params; 11422 11423 uint32_t ncols = src0->ne[0]; 11424 uint32_t nrows = ggml_nrows(src0); 11425 11426 uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols))); 11427 uint32_t ncolsp2 = 1 << ncols_pad_log2; 11428 11429 vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, }; 11430 11431 // Pick the largest workgroup size <= ncolsp2 11432 uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1); 11433 11434 uint32_t max_wg_log2 = std::min(ctx->device->max_workgroup_size_log2, num_argsort_pipelines - 1); 11435 11436 // Use the "small" argsort shader if the whole sort can be done by a single workgroup. 11437 bool use_small = ncols_pad_log2 <= max_wg_log2 && 11438 ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr; 11439 11440 vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx] 11441 : ctx->device->pipeline_argsort_large_f32[pipeline_idx]; 11442 11443 vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0); 11444 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 11445 vk_subbuffer subbuf1 = dst_buf; 11446 11447 // Reserve space for ivec2 per element, with rows padded to a power of two 11448 if (!use_small) { 11449 const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int); 11450 11451 if (ctx->prealloc_size_x < x_sz) { 11452 ctx->prealloc_size_x = x_sz; 11453 ggml_vk_preallocate_buffers(ctx, subctx); 11454 } 11455 if (ctx->prealloc_x_need_sync) { 11456 ggml_vk_sync_buffers(ctx, subctx); 11457 } 11458 subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size }; 11459 } 11460 11461 std::array elements; 11462 11463 elements[0] = ncolsp2; 11464 elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 11465 elements[2] = 1; 11466 11467 // First dispatch initializes tmp_idx and does the first N passes where 11468 // there is only communication between threads in the same workgroup. 11469 { 11470 vk_op_argsort_push_constants pc2 = pc; 11471 pc2.outer_start = 0; 11472 pc2.outer_end = std::min(ncols_pad_log2, max_wg_log2); 11473 pc2.inner_start = 0; 11474 pc2.inner_end = 100; 11475 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11476 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements); 11477 } 11478 if (!use_small) { 11479 ggml_vk_sync_buffers(ctx, subctx); 11480 // Loop over outer/inner passes, synchronizing between each pass. 11481 for (uint32_t outer = max_wg_log2; outer < ncols_pad_log2; ++outer) { 11482 for (uint32_t inner = 0; inner < outer + 1; ++inner) { 11483 vk_op_argsort_push_constants pc2 = pc; 11484 pc2.outer_start = outer; 11485 pc2.outer_end = outer + 1; 11486 pc2.inner_start = inner; 11487 pc2.inner_end = inner + 1; 11488 // When the inner idx is large enough, there's only communication 11489 // within a workgroup. So the remaining inner iterations can all 11490 // run in the same dispatch. 11491 if (outer - inner < pipeline_idx) { 11492 pc2.inner_end = 100; 11493 inner = outer; 11494 pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx]; 11495 } else { 11496 // Smaller workgroup empirically seems to perform better 11497 pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2]; 11498 } 11499 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11500 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements); 11501 ggml_vk_sync_buffers(ctx, subctx); 11502 } 11503 } 11504 ctx->prealloc_x_need_sync = true; 11505 } 11506 } 11507 11508 void ggml_vk_topk(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11509 uint32_t ncols = src0->ne[0]; 11510 uint32_t nrows = ggml_nrows(src0); 11511 uint32_t k = dst->ne[0]; 11512 11513 // tournament path is faster where it fits; use radix-select only past its k limit 11514 const uint32_t k_min_pipeline = std::max((uint32_t) log2f(float(k)) + 1, ctx->device->subgroup_size_log2); 11515 if (k_min_pipeline >= num_topk_pipelines || ctx->device->pipeline_topk_f32[k_min_pipeline] == nullptr) { 11516 vk_pipeline pipeline = ctx->device->pipeline_topk_radix_f32; 11517 GGML_ASSERT(pipeline != nullptr); 11518 11519 if (ctx->prealloc_x_need_sync) { 11520 ggml_vk_sync_buffers(ctx, subctx); 11521 } 11522 11523 vk_op_topk_radix_push_constants pc { ncols, k, nrows, 0, 0, 0 }; 11524 std::array elements { 11525 pipeline->wg_denoms[0], 11526 std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]), 11527 1, 11528 }; 11529 // the non-QSA path only uses bindings 0/1; bind valid buffers for the unused QSA slots 11530 vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0); 11531 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 11532 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11533 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 11534 { src0_buf, dst_buf, src0_buf, src0_buf, src0_buf }, pc, elements); 11535 return; 11536 } 11537 11538 vk_op_topk_push_constants pc { ncols, ncols, ncols, k, nrows, 0, 0 }; 11539 11540 if (ctx->prealloc_x_need_sync) { 11541 ggml_vk_sync_buffers(ctx, subctx); 11542 } 11543 11544 std::array elements; 11545 elements[1] = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]); 11546 elements[2] = 1; 11547 11548 uint32_t num_elements = ncols; 11549 11550 // Each iteration reduces a workgroup's worth of elements down to the K 11551 // largest elements. Repeat until we have the top K elements. 11552 // Need to do at least one iteration to write out the results. 11553 bool done_one_iter = false; 11554 uint32_t dbl_buf_index = 0; 11555 size_t dbl_buf_size; 11556 while (num_elements > k || !done_one_iter) { 11557 11558 // Prefer going as small as num_topk_pipelines - 3 for perf reasons. 11559 // But if K is larger, then we need a larger workgroup 11560 uint32_t max_pipeline = num_topk_pipelines - 1; 11561 uint32_t preferred_pipeline = std::max(num_topk_pipelines - 3, (uint32_t)log2f(float(k)) + 2); 11562 max_pipeline = std::min(preferred_pipeline, max_pipeline); 11563 uint32_t min_pipeline = (uint32_t)log2f(float(k)) + 1; 11564 // require full subgroup 11565 min_pipeline = std::max(min_pipeline, ctx->device->subgroup_size_log2); 11566 11567 uint32_t pipeline_idx = (uint32_t)ceilf(log2f(float(num_elements))); 11568 pipeline_idx = std::min(pipeline_idx, max_pipeline); 11569 pipeline_idx = std::max(pipeline_idx, min_pipeline); 11570 11571 if (num_elements > (1u << pipeline_idx)) { 11572 // If we could finish on this loop iteration (i.e. a single workgroup) 11573 // then do so. It's better than the overhead of another pass. 11574 for (uint32_t i = pipeline_idx; i < num_topk_pipelines; ++i) { 11575 if (num_elements <= (1u << i)) { 11576 pipeline_idx = i; 11577 break; 11578 } 11579 } 11580 } 11581 11582 vk_pipeline pipeline = ctx->device->pipeline_topk_f32[pipeline_idx]; 11583 // If the device doesn't support a pipeline this large, use smaller 11584 while (!pipeline) { 11585 pipeline_idx--; 11586 GGML_ASSERT(pipeline_idx >= min_pipeline); 11587 pipeline = ctx->device->pipeline_topk_f32[pipeline_idx]; 11588 } 11589 11590 vk_op_topk_push_constants pc2 = pc; 11591 pc2.ncols_input = num_elements; 11592 11593 // Number of elements remaining after this pass 11594 uint32_t num_dst_elements = (num_elements / pipeline->wg_denoms[0]) * k + std::min(k, num_elements % pipeline->wg_denoms[0]); 11595 11596 pc2.ncols_output = num_dst_elements; 11597 11598 if (!done_one_iter) { 11599 // Reserve space for ivec2 per element, double buffered 11600 // K per workgroup per row 11601 dbl_buf_size = num_dst_elements * nrows * 2 * sizeof(int); 11602 dbl_buf_size = ROUNDUP_POW2(dbl_buf_size, ctx->device->properties.limits.minStorageBufferOffsetAlignment); 11603 const size_t x_sz = dbl_buf_size * 2; 11604 11605 if (ctx->prealloc_size_x < x_sz) { 11606 ctx->prealloc_size_x = x_sz; 11607 ggml_vk_preallocate_buffers(ctx, subctx); 11608 } 11609 } 11610 11611 vk_subbuffer src_buf; 11612 vk_subbuffer dst_buf; 11613 11614 if (num_elements == ncols) { 11615 pc2.first_pass = 1; 11616 src_buf = ggml_vk_tensor_subbuffer(ctx, src0); 11617 } else { 11618 src_buf = { ctx->prealloc_x, dbl_buf_index * dbl_buf_size, dbl_buf_size }; 11619 } 11620 if (num_dst_elements == k) { 11621 pc2.last_pass = 1; 11622 dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 11623 } else { 11624 dst_buf = { ctx->prealloc_x, (dbl_buf_index ^ 1) * dbl_buf_size, dbl_buf_size }; 11625 } 11626 11627 elements[0] = num_elements; 11628 11629 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11630 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc2, elements); 11631 num_elements = num_dst_elements; 11632 dbl_buf_index ^= 1; 11633 if (num_elements > k) { 11634 ggml_vk_sync_buffers(ctx, subctx); 11635 } 11636 done_one_iter = true; 11637 } 11638 ctx->prealloc_x_need_sync = true; 11639 } 11640 11641 void ggml_vk_topk_qsa(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx) { 11642 const ggml_tensor * get_rows = cgraph->nodes[node_idx + 0]; 11643 const ggml_tensor * add = cgraph->nodes[node_idx + ctx->num_additional_fused_ops - 1]; 11644 ggml_tensor * top_k = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; 11645 11646 const ggml_tensor * scores = get_rows->src[0]; // [n_tps, n_blocks, n_stream] 11647 const ggml_tensor * cell_blk = get_rows->src[1]; // [n_kv, n_stream] 11648 11649 // raw f16 mask: follow the reshape/cpy chain back to the materialized input 11650 const ggml_tensor * mask = add->src[1]; 11651 while (mask->op == GGML_OP_RESHAPE || mask->op == GGML_OP_CPY) { 11652 mask = mask->src[0]; 11653 } 11654 11655 const uint32_t n_tps = scores->ne[0]; 11656 const uint32_t n_blocks = scores->ne[1]; 11657 const uint32_t n_stream = scores->ne[2]; 11658 const uint32_t n_kv = cell_blk->ne[0]; 11659 const uint32_t width = top_k->ne[0]; 11660 const uint32_t nrows = n_tps * n_stream; 11661 11662 vk_pipeline pipeline = ctx->device->pipeline_topk_radix_qsa; 11663 GGML_ASSERT(pipeline != nullptr); 11664 11665 // scratch holds the gathered+masked input, materialized once and reused across passes 11666 const size_t scratch_size = size_t{ n_kv } * nrows * sizeof(float); 11667 if (ctx->prealloc_size_x < scratch_size) { 11668 ctx->prealloc_size_x = scratch_size; 11669 ggml_vk_preallocate_buffers(ctx, subctx); 11670 } 11671 if (ctx->prealloc_x_need_sync) { 11672 ggml_vk_sync_buffers(ctx, subctx); 11673 } 11674 11675 vk_op_topk_radix_push_constants pc { n_kv, width, nrows, n_tps, n_blocks, n_stream }; 11676 std::array elements { 11677 pipeline->wg_denoms[0], 11678 std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]), 11679 1, 11680 }; 11681 vk_subbuffer scratch_buf { ctx->prealloc_x, 0, ctx->prealloc_x->size }; 11682 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11683 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, 11684 { ggml_vk_tensor_subbuffer(ctx, scores), ggml_vk_tensor_subbuffer(ctx, top_k), 11685 ggml_vk_tensor_subbuffer(ctx, cell_blk), ggml_vk_tensor_subbuffer(ctx, mask), 11686 scratch_buf }, pc, elements); 11687 ctx->prealloc_x_need_sync = true; 11688 } 11689 11690 void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11691 vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0)); 11692 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p); 11693 } 11694 11695 void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11696 vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]); 11697 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p); 11698 } 11699 11700 void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11701 vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]); 11702 p.weight = 1.0f / (float)src0->ne[0]; 11703 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p); 11704 } 11705 11706 void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11707 vk_op_sum_rows_push_constants pc = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]); 11708 // Use the single pass shader when the rows are small or there are enough rows to fill the GPU. 11709 // For fewer, larger rows, use the multipass shader to spread each row across SMs. 11710 if (dst->ne[0] <= 4096 || ggml_nrows(dst) >= ctx->device->shader_core_count) { 11711 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CUMSUM, pc); 11712 return; 11713 } 11714 11715 // First pass computes partial sums within a block, and stores the last partial 11716 // to the temp buffer. Second pass sums the block partials from the temp buffer 11717 // and adds that to the result of the first pass. 11718 vk_pipeline pipeline1 = ctx->device->pipeline_cumsum_multipass1_f32; 11719 vk_pipeline pipeline2 = ctx->device->pipeline_cumsum_multipass2_f32; 11720 GGML_ASSERT(pipeline1 != nullptr && pipeline2 != nullptr); 11721 11722 ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1); 11723 ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1); 11724 11725 std::array elements; 11726 11727 elements[0] = dst->ne[0]; 11728 elements[1] = (uint32_t)ggml_nrows(dst); 11729 elements[2] = 1; 11730 11731 size_t temp_size = sizeof(float) * elements[0] * ggml_nrows(dst); 11732 11733 if (ctx->prealloc_size_split_k < temp_size) { 11734 ctx->prealloc_size_split_k = temp_size; 11735 ggml_vk_preallocate_buffers(ctx, subctx); 11736 } 11737 11738 vk_subbuffer src_buf = ggml_vk_tensor_subbuffer(ctx, src0); 11739 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 11740 vk_subbuffer temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0); 11741 11742 if (ctx->prealloc_split_k_need_sync) { 11743 ggml_vk_sync_buffers(ctx, subctx); 11744 } 11745 11746 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, {src_buf, dst_buf, temp_buf}, pc, elements); 11747 ggml_vk_sync_buffers(ctx, subctx); 11748 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, {src_buf, dst_buf, temp_buf}, pc, elements); 11749 11750 ctx->prealloc_split_k_need_sync = true; 11751 } 11752 11753 static std::array ggml_vk_nrows_elements(uint32_t nr) { 11754 if (nr > 262144) { 11755 return { 512, 512, CEIL_DIV(nr, 262144) }; 11756 } 11757 if (nr > 512) { 11758 return { 512, CEIL_DIV(nr, 512), 1 }; 11759 } 11760 return { nr, 1, 1 }; 11761 } 11762 11763 void ggml_vk_cross_entropy_loss(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 11764 const ggml_tensor * src0 = dst->src[0]; 11765 const ggml_tensor * src1 = dst->src[1]; 11766 11767 GGML_ASSERT(src0->type == GGML_TYPE_F32); 11768 GGML_ASSERT(src1->type == GGML_TYPE_F32); 11769 GGML_ASSERT(dst->type == GGML_TYPE_F32); 11770 GGML_ASSERT(ggml_is_contiguous(src0)); 11771 GGML_ASSERT(ggml_is_contiguous(src1)); 11772 GGML_ASSERT(ggml_is_contiguous(dst)); 11773 GGML_ASSERT(ggml_are_same_shape(src0, src1)); 11774 GGML_ASSERT(ggml_is_scalar(dst)); 11775 11776 const uint32_t nclasses = (uint32_t)src0->ne[0]; 11777 const uint32_t nrows = (uint32_t)ggml_nrows(src0); 11778 11779 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, nullptr, dst, GGML_OP_CROSS_ENTROPY_LOSS); 11780 GGML_ASSERT(pipeline != nullptr); 11781 11782 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11783 ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_sum_rows_f32, 1); 11784 11785 vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0); 11786 vk_subbuffer src1_buf = ggml_vk_tensor_subbuffer(ctx, src1); 11787 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); 11788 11789 const vk_op_push_constants pc = { nclasses, nrows, 0.0f, 0.0f, 0.0f, 0.0f }; 11790 11791 const size_t tmp_size = (size_t)nrows * sizeof(float); 11792 if (ctx->prealloc_size_x < tmp_size) { 11793 ctx->prealloc_size_x = tmp_size; 11794 ggml_vk_preallocate_buffers(ctx, subctx); 11795 } 11796 if (ctx->prealloc_x_need_sync) { 11797 ggml_vk_sync_buffers(ctx, subctx); 11798 } 11799 11800 vk_subbuffer tmp_buf = { ctx->prealloc_x, 0, tmp_size }; 11801 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, tmp_buf }, pc, ggml_vk_nrows_elements(nrows)); 11802 ggml_vk_sync_buffers(ctx, subctx); 11803 11804 vk_op_sum_rows_push_constants sp = {}; 11805 sp.n_cols = nrows; 11806 sp.ne01 = 1; 11807 sp.ne02 = 1; 11808 sp.weight = 1.0f; 11809 init_pushconst_fastdiv(sp); 11810 sp.misalign_offsets = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type); 11811 11812 ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_sum_rows_f32, { tmp_buf, dst_buf }, sp, { 1, 1, 1 }); 11813 ctx->prealloc_x_need_sync = true; 11814 } 11815 11816 void ggml_vk_cross_entropy_loss_back(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { 11817 const ggml_tensor * grad = dst->src[0]; 11818 const ggml_tensor * logits = dst->src[1]; 11819 const ggml_tensor * labels = dst->src[2]; 11820 11821 GGML_ASSERT(grad->type == GGML_TYPE_F32); 11822 GGML_ASSERT(logits->type == GGML_TYPE_F32); 11823 GGML_ASSERT(labels->type == GGML_TYPE_F32); 11824 GGML_ASSERT(dst->type == GGML_TYPE_F32); 11825 GGML_ASSERT(ggml_is_scalar(grad)); 11826 GGML_ASSERT(ggml_is_contiguous(grad)); 11827 GGML_ASSERT(ggml_is_contiguous(logits)); 11828 GGML_ASSERT(ggml_is_contiguous(labels)); 11829 GGML_ASSERT(ggml_is_contiguous(dst)); 11830 GGML_ASSERT(ggml_are_same_shape(logits, labels)); 11831 GGML_ASSERT(ggml_are_same_shape(logits, dst)); 11832 11833 const uint32_t nclasses = (uint32_t)logits->ne[0]; 11834 const uint32_t nrows = (uint32_t)ggml_nrows(logits); 11835 11836 vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, grad, logits, labels, dst, GGML_OP_CROSS_ENTROPY_LOSS_BACK); 11837 GGML_ASSERT(pipeline != nullptr); 11838 11839 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 11840 11841 vk_subbuffer grad_buf = ggml_vk_tensor_subbuffer(ctx, grad); 11842 vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits); 11843 vk_subbuffer labels_buf = ggml_vk_tensor_subbuffer(ctx, labels); 11844 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); 11845 11846 const vk_op_push_constants pc = { nclasses, nrows, 0.0f, 0.0f, 0.0f, 0.0f }; 11847 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { grad_buf, logits_buf, labels_buf, dst_buf }, pc, ggml_vk_nrows_elements(nrows)); 11848 } 11849 11850 void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11851 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGMAX, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f, 0.0f, 0.0f }); 11852 } 11853 11854 void ggml_vk_count_equal(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11855 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_COUNT_EQUAL, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f, 0.0f, 0.0f }); 11856 } 11857 11858 void ggml_vk_solve_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11859 const uint32_t src0_type_size = ggml_type_size(src0->type); 11860 const uint32_t src1_type_size = ggml_type_size(src1->type); 11861 const uint32_t dst_type_size = ggml_type_size(dst->type); 11862 11863 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOLVE_TRI, { 11864 (uint32_t)ggml_nelements(src0), 11865 (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, 11866 (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, 11867 (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, 11868 0, 11869 0.0f, 0.0f, 0, 11870 }); 11871 } 11872 11873 void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11874 const int32_t s0 = dst->op_params[0]; 11875 const int32_t s1 = dst->op_params[1]; 11876 const int32_t p0 = dst->op_params[2]; 11877 const int32_t p1 = dst->op_params[3]; 11878 const int32_t d0 = dst->op_params[4]; 11879 const int32_t d1 = dst->op_params[5]; 11880 11881 const bool is_2D = dst->op_params[6] == 1; 11882 11883 const uint32_t IC = src1->ne[is_2D ? 2 : 1]; 11884 const uint32_t IH = is_2D ? src1->ne[1] : 1; 11885 const uint32_t IW = src1->ne[0]; 11886 11887 const uint32_t KH = is_2D ? src0->ne[1] : 1; 11888 const uint32_t KW = src0->ne[0]; 11889 11890 const uint32_t OH = is_2D ? dst->ne[2] : 1; 11891 const uint32_t OW = dst->ne[1]; 11892 11893 const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32 11894 const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32 11895 11896 const uint32_t batch = src1->ne[is_2D ? 3 : 2]; 11897 11898 const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; 11899 const vk_buffer d_buf = d_buf_ctx->dev_buffer; 11900 11901 const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs; 11902 11903 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, { 11904 dst_addr, 11905 batch_offset, offset_delta, 11906 IC, IW, IH, OW, OH, KW, KH, 11907 OH * batch, 11908 IC * KH * KW, 11909 s0, s1, p0, p1, d0, d1, batch * IC 11910 }); 11911 } 11912 11913 void ggml_vk_im2col_3d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11914 GGML_TENSOR_BINARY_OP_LOCALS 11915 11916 const int32_t s0 = ((const int32_t *)(dst->op_params))[0]; 11917 const int32_t s1 = ((const int32_t *)(dst->op_params))[1]; 11918 const int32_t s2 = ((const int32_t *)(dst->op_params))[2]; 11919 const int32_t p0 = ((const int32_t *)(dst->op_params))[3]; 11920 const int32_t p1 = ((const int32_t *)(dst->op_params))[4]; 11921 const int32_t p2 = ((const int32_t *)(dst->op_params))[5]; 11922 const int32_t d0 = ((const int32_t *)(dst->op_params))[6]; 11923 const int32_t d1 = ((const int32_t *)(dst->op_params))[7]; 11924 const int32_t d2 = ((const int32_t *)(dst->op_params))[8]; 11925 const int32_t IC = ((const int32_t *)(dst->op_params))[9]; 11926 11927 const int64_t N = ne13 / IC; 11928 const int64_t ID = ne12; 11929 const int64_t IH = ne11; 11930 const int64_t IW = ne10; 11931 11932 const int64_t KD = ne02; 11933 const int64_t KH = ne01; 11934 const int64_t KW = ne00; 11935 11936 const int64_t OD = ne3 / N; 11937 const int64_t OH = ne2; 11938 const int64_t OW = ne1; 11939 11940 const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; 11941 const vk_buffer d_buf = d_buf_ctx->dev_buffer; 11942 11943 const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs; 11944 11945 vk_op_im2col_3d_push_constants pc {}; 11946 11947 pc.dst_addr = dst_addr; 11948 pc.nb10 = nb10 / ggml_type_size(src1->type); 11949 pc.nb11 = nb11 / ggml_type_size(src1->type); 11950 pc.nb12 = nb12 / ggml_type_size(src1->type); 11951 pc.nb13 = nb13 / ggml_type_size(src1->type); 11952 pc.s0 = s0; 11953 pc.s1 = s1; 11954 pc.s2 = s2; 11955 pc.p0 = p0; 11956 pc.p1 = p1; 11957 pc.p2 = p2; 11958 pc.d0 = d0; 11959 pc.d1 = d1; 11960 pc.d2 = d2; 11961 pc.IW = IW; 11962 pc.IH = IH; 11963 pc.ID = ID; 11964 pc.IC = IC; 11965 pc.KW = KW; 11966 pc.OH = OH; 11967 pc.KD_KH_KW = KD*KH*KW; 11968 pc.KH_KW = KH*KW; 11969 pc.IC_KD_KH_KW = IC*KD*KH*KW; 11970 pc.N_OD_OH = N*OD*OH; 11971 pc.OD_OH = OD*OH; 11972 pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW; 11973 pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW; 11974 pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW; 11975 11976 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc)); 11977 } 11978 11979 void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 11980 const uint32_t dim = dst->op_params[0]; 11981 const uint32_t max_period = dst->op_params[1]; 11982 const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type); 11983 11984 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, { 11985 nb1, dim, max_period, 11986 }); 11987 } 11988 11989 void ggml_vk_conv_transpose_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 11990 // src0: (K, Cout, Cin, 1) -- kernel 11991 // src1: (L, Cin, 1, 1) -- input 11992 // dst: (*, Cout, 1, 1) 11993 11994 GGML_ASSERT(src0->type == GGML_TYPE_F32); 11995 GGML_ASSERT(src1->type == GGML_TYPE_F32); 11996 GGML_ASSERT( dst->type == GGML_TYPE_F32); 11997 11998 GGML_TENSOR_BINARY_OP_LOCALS 11999 12000 GGML_ASSERT(nb00 == sizeof(float)); 12001 GGML_ASSERT(nb10 == sizeof(float)); 12002 12003 const int32_t s0 = dst->op_params[0]; 12004 12005 vk_op_conv_transpose_1d_push_constants p{}; 12006 p.Cout = static_cast(ne01); 12007 p.Cin = static_cast(ne02); 12008 p.K = static_cast(ne00); 12009 p.L = static_cast(ne10); 12010 p.KL = static_cast(ne0); 12011 p.nb01 = static_cast(nb01 / nb00); 12012 p.nb02 = static_cast(nb02 / nb00); 12013 p.nb11 = static_cast(nb11 / nb10); 12014 p.nb1 = static_cast(nb1 / nb0); 12015 p.s0 = static_cast(s0); 12016 12017 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p)); 12018 } 12019 12020 void ggml_vk_col2im_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 12021 // src0: [K_OC, T_in] columns from matmul 12022 // dst: [T_out, OC] 12023 12024 const int32_t stride = dst->op_params[0]; 12025 const int32_t oc = dst->op_params[1]; 12026 const int32_t p0 = dst->op_params[2]; 12027 12028 const uint32_t K_OC = static_cast(src0->ne[0]); 12029 const uint32_t T_in = static_cast(src0->ne[1]); 12030 const uint32_t T_out = static_cast(dst->ne[0]); 12031 const uint32_t OC = static_cast(oc); 12032 const uint32_t K = K_OC / OC; 12033 12034 vk_op_col2im_1d_push_constants p{}; 12035 p.T_out = T_out; 12036 p.OC = OC; 12037 p.K_OC = K_OC; 12038 p.T_in = T_in; 12039 p.K = K; 12040 p.stride = stride; 12041 p.p0 = p0; 12042 12043 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COL2IM_1D, std::move(p)); 12044 } 12045 12046 void ggml_vk_snake_dispatch_fused(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) { 12047 const ggml_tensor * mul0 = cgraph->nodes[node_idx + 0]; 12048 const ggml_tensor * sqr = cgraph->nodes[node_idx + 2]; 12049 const ggml_tensor * mul1 = cgraph->nodes[node_idx + 3]; 12050 ggml_tensor * add = cgraph->nodes[node_idx + 4]; 12051 12052 // x carries the full activation shape, a is the broadcast operand 12053 const ggml_tensor * x = ggml_are_same_shape(mul0, mul0->src[0]) ? mul0->src[0] : mul0->src[1]; 12054 const ggml_tensor * a = (x == mul0->src[0]) ? mul0->src[1] : mul0->src[0]; 12055 12056 // mul1 reads sqr and inv_b in either operand order 12057 const ggml_tensor * inv_b = (mul1->src[0] == sqr) ? mul1->src[1] : mul1->src[0]; 12058 12059 vk_pipeline pipeline = nullptr; 12060 switch (x->type) { 12061 case GGML_TYPE_F32: pipeline = ctx->device->pipeline_snake_f32; break; 12062 case GGML_TYPE_F16: pipeline = ctx->device->pipeline_snake_f16; break; 12063 case GGML_TYPE_BF16: pipeline = ctx->device->pipeline_snake_bf16; break; 12064 default: GGML_ABORT("unsupported type"); 12065 } 12066 ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); 12067 12068 vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x); 12069 vk_subbuffer a_buf = ggml_vk_tensor_subbuffer(ctx, a); 12070 vk_subbuffer inv_b_buf = ggml_vk_tensor_subbuffer(ctx, inv_b); 12071 vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, add); 12072 12073 vk_op_snake_push_constants pc{}; 12074 pc.ne0 = static_cast(x->ne[0]); 12075 pc.ne1 = static_cast(x->ne[1]); 12076 12077 std::array elements = { pc.ne0, pc.ne1, 1 }; 12078 ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { x_buf, a_buf, inv_b_buf, dst_buf }, pc, elements); 12079 } 12080 12081 void ggml_vk_pool_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 12082 uint32_t op = static_cast(dst->op_params[0]); 12083 const int32_t k0 = dst->op_params[1]; 12084 const int32_t s0 = dst->op_params[2]; 12085 const int32_t p0 = dst->op_params[3]; 12086 12087 const uint32_t IL = src0->ne[0]; 12088 12089 const uint32_t N = dst->ne[3] * dst->ne[2]; 12090 12091 const uint32_t OC = dst->ne[1]; 12092 const uint32_t OL = dst->ne[0]; 12093 12094 const uint32_t parallel_elements = N * OC * OL; 12095 12096 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_1D, { 12097 IL, OL, OC, 12098 parallel_elements, 12099 op, 12100 k0, s0, p0, 12101 }); 12102 } 12103 12104 void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 12105 uint32_t op = static_cast(dst->op_params[0]); 12106 const int32_t k1 = dst->op_params[1]; 12107 const int32_t k0 = dst->op_params[2]; 12108 const int32_t s1 = dst->op_params[3]; 12109 const int32_t s0 = dst->op_params[4]; 12110 const int32_t p1 = dst->op_params[5]; 12111 const int32_t p0 = dst->op_params[6]; 12112 12113 const uint32_t IH = src0->ne[1]; 12114 const uint32_t IW = src0->ne[0]; 12115 12116 const uint32_t N = dst->ne[3]; 12117 12118 const uint32_t OC = dst->ne[2]; 12119 const uint32_t OH = dst->ne[1]; 12120 const uint32_t OW = dst->ne[0]; 12121 12122 const uint32_t parallel_elements = N * OC * OH * OW; 12123 12124 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, { 12125 IW, IH, OW, OH, OC, 12126 parallel_elements, 12127 op, 12128 k0, k1, s0, s1, p0, p1, 12129 }); 12130 } 12131 12132 void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0, 12133 const ggml_tensor * src1, ggml_tensor * dst) { 12134 GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); 12135 GGML_ASSERT(src1->type == GGML_TYPE_F32); 12136 GGML_ASSERT(dst->type == GGML_TYPE_F32); 12137 12138 GGML_TENSOR_BINARY_OP_LOCALS 12139 GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t)); 12140 GGML_ASSERT(nb10 == sizeof(float)); 12141 GGML_ASSERT(nb0 == sizeof(float)); 12142 12143 bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D; 12144 12145 vk_op_conv2d_push_constants p{}; 12146 p.Cout = static_cast(!transpose ? ne03 : ne02); 12147 p.Cin = static_cast(!transpose ? ne02 : ne03); 12148 p.N = static_cast(ne13); 12149 GGML_ASSERT(p.Cout == ne2); 12150 GGML_ASSERT(p.Cin == ne12); 12151 12152 p.W = static_cast(ne10); 12153 p.H = static_cast(ne11); 12154 p.OW = static_cast(ne0); 12155 p.OH = static_cast(ne1); 12156 12157 p.nb01 = static_cast(nb01 / nb00); 12158 p.nb02 = static_cast(nb02 / nb00); 12159 p.nb03 = static_cast(nb03 / nb00); 12160 12161 p.nb11 = static_cast(nb11 / nb10); 12162 p.nb12 = static_cast(nb12 / nb10); 12163 p.nb13 = static_cast(nb13 / nb10); 12164 12165 p.nb1 = static_cast(nb1 / nb0); 12166 p.nb2 = static_cast(nb2 / nb0); 12167 p.nb3 = static_cast(nb3 / nb0); 12168 12169 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, std::move(p)); 12170 } 12171 12172 void ggml_vk_conv_3d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0, 12173 const ggml_tensor * src1, ggml_tensor * dst) { 12174 GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); 12175 GGML_ASSERT(src1->type == GGML_TYPE_F32); 12176 GGML_ASSERT(dst->type == GGML_TYPE_F32); 12177 12178 GGML_TENSOR_BINARY_OP_LOCALS 12179 GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t)); 12180 GGML_ASSERT(nb10 == sizeof(float)); 12181 GGML_ASSERT(nb0 == sizeof(float)); 12182 12183 vk_op_conv3d_push_constants p{}; 12184 p.IC = static_cast(ggml_get_op_params_i32(dst, 9)); 12185 p.N = static_cast(ggml_get_op_params_i32(dst, 10)); 12186 p.OC = static_cast(ggml_get_op_params_i32(dst, 11)); 12187 GGML_ASSERT(src0->ne[3] == (int64_t)p.IC * p.OC); 12188 GGML_ASSERT(src1->ne[3] == (int64_t)p.IC * p.N); 12189 GGML_ASSERT(dst->ne[3] == (int64_t)p.OC * p.N); 12190 12191 p.IW = static_cast(ne10); 12192 p.IH = static_cast(ne11); 12193 p.ID = static_cast(ne12); 12194 p.OW = static_cast(ne0); 12195 p.OH = static_cast(ne1); 12196 p.OD = static_cast(ne2); 12197 12198 // the shader clamps src addresses to p.IC * p.N * p.IW * p.IH * p.ID - 1 in uint32, so the 12199 // total input element count must fit in a uint32. 12200 GGML_ASSERT((uint64_t)p.IC * p.N * p.IW * p.IH * p.ID <= 0xFFFFFFFFull); 12201 12202 p.nb01 = static_cast(nb01 / nb00); 12203 p.nb02 = static_cast(nb02 / nb00); 12204 p.nb03 = static_cast(nb03 / nb00); 12205 12206 p.nb11 = static_cast(nb11 / nb10); 12207 p.nb12 = static_cast(nb12 / nb10); 12208 p.nb13 = static_cast(nb13 / nb10); 12209 12210 p.nb1 = static_cast(nb1 / nb0); 12211 p.nb2 = static_cast(nb2 / nb0); 12212 p.nb3 = static_cast(nb3 / nb0); 12213 12214 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_3D, std::move(p)); 12215 } 12216 12217 void ggml_vk_conv_2d_dw(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { 12218 vk_op_conv2d_dw_push_constants p{}; 12219 p.ne = ggml_nelements(dst); 12220 p.channels = dst->ne[2]; 12221 p.batches = dst->ne[3]; 12222 p.dst_w = dst->ne[0]; 12223 p.dst_h = dst->ne[1]; 12224 p.src_w = src1->ne[0]; 12225 p.src_h = src1->ne[1]; 12226 p.knl_w = src0->ne[0]; 12227 p.knl_h = src0->ne[1]; 12228 p.stride_x = dst->op_params[0]; 12229 p.stride_y = dst->op_params[1]; 12230 p.pad_x = dst->op_params[2]; 12231 p.pad_y = dst->op_params[3]; 12232 p.dilation_x = dst->op_params[4]; 12233 p.dilation_y = dst->op_params[5]; 12234 12235 GGML_ASSERT(src0->ne[3] == p.channels); 12236 GGML_ASSERT(src1->ne[3] == p.batches); 12237 12238 ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p)); 12239 } 12240 12241 void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { 12242 const float * op_params = (const float *)dst->op_params; 12243 vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst); 12244 p.param1 = op_params[0]; 12245 12246 ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, std::move(p)); 12247 } 12248 12249 void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) { 12250 #if defined(GGML_VULKAN_RUN_TESTS) 12251 const std::vector vals { 12252 512, 512, 128, 12253 128, 512, 512, 12254 4096, 512, 4096, 12255 11008, 512, 4096, 12256 4096, 512, 11008, 12257 32000, 512, 4096, 12258 8, 8, 8, 12259 100, 46, 576, 12260 623, 111, 128, 12261 100, 46, 558, 12262 512, 1, 256, 12263 128, 110, 622, 12264 511, 511, 127, 12265 511, 511, 7, 12266 511, 511, 17, 12267 49, 49, 128, 12268 128, 49, 49, 12269 4096, 49, 4096, 12270 }; 12271 const size_t num_it = 100; 12272 12273 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0); 12274 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0); 12275 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0); 12276 12277 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true); 12278 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true); 12279 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true); 12280 12281 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0); 12282 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0); 12283 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0); 12284 12285 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true); 12286 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true); 12287 ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true); 12288 12289 abort(); 12290 12291 for (size_t i = 0; i < vals.size(); i += 3) { 12292 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0); 12293 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1); 12294 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2); 12295 std::cerr << '\n'; 12296 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0); 12297 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1); 12298 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2); 12299 std::cerr << '\n'; 12300 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0); 12301 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1); 12302 ggml_vk_test_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2); 12303 std::cerr << '\n' << std::endl; 12304 12305 if (vals[i + 2] % 32 == 0) { 12306 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0); 12307 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0); 12308 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0); 12309 std::cerr << '\n'; 12310 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0); 12311 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0); 12312 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0); 12313 std::cerr << '\n'; 12314 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0); 12315 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0); 12316 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0); 12317 std::cerr << '\n' << std::endl; 12318 } 12319 12320 if (vals[i + 2] % 256 == 0) { 12321 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K); 12322 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K); 12323 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K); 12324 std::cerr << '\n'; 12325 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K); 12326 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K); 12327 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K); 12328 std::cerr << '\n'; 12329 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K); 12330 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K); 12331 ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K); 12332 std::cerr << '\n' << std::endl; 12333 } 12334 } 12335 12336 GGML_ABORT("fatal error"); 12337 #endif 12338 12339 if (subctx) { 12340 // Submit and wait for any pending work before reallocating the buffers 12341 ggml_vk_ctx_end(subctx); 12342 ggml_vk_submit(subctx, {}); 12343 ctx->submit_pending = true; 12344 ggml_vk_synchronize(ctx); 12345 GGML_ASSERT(ctx->compute_ctx.expired()); 12346 ggml_vk_ctx_begin(ctx->device, subctx); 12347 ctx->compute_ctx = subctx; 12348 } 12349 12350 if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) { 12351 VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")"); 12352 // Resize buffer 12353 if (ctx->prealloc_x != nullptr) { 12354 ggml_vk_destroy_buffer(ctx->prealloc_x); 12355 } 12356 ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x); 12357 } 12358 if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) { 12359 VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")"); 12360 // Resize buffer 12361 if (ctx->prealloc_y != nullptr) { 12362 ggml_vk_destroy_buffer(ctx->prealloc_y); 12363 } 12364 ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y); 12365 ctx->prealloc_y_last_pipeline_used = nullptr; 12366 ctx->prealloc_y_last_tensor_used = nullptr; 12367 ctx->prealloc_y_last_k_padded = false; 12368 } 12369 if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) { 12370 VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")"); 12371 // Resize buffer 12372 if (ctx->prealloc_split_k != nullptr) { 12373 ggml_vk_destroy_buffer(ctx->prealloc_split_k); 12374 } 12375 ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k); 12376 } 12377 if (ctx->prealloc_add_rms_partials == nullptr || (ctx->prealloc_size_add_rms_partials > 0 && ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) { 12378 VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")"); 12379 // Resize buffer 12380 if (ctx->prealloc_add_rms_partials != nullptr) { 12381 ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials); 12382 } 12383 ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials); 12384 } 12385 } 12386 12387 bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool last_node, bool almost_ready, bool submit){ 12388 ggml_tensor * node = cgraph->nodes[node_idx]; 12389 if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || !node->buffer) { 12390 return false; 12391 } 12392 if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { 12393 return false; 12394 } 12395 12396 VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")"); 12397 ctx->semaphore_idx = 0; 12398 12399 ggml_tensor * src0 = node->src[0]; 12400 ggml_tensor * src1 = node->src[1]; 12401 ggml_tensor * src2 = node->src[2]; 12402 ggml_tensor * src3 = node->src[3]; 12403 12404 if (node->op == GGML_OP_ADD) { 12405 int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops; 12406 if (next_node_idx < cgraph->n_nodes && 12407 cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM && 12408 cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] && 12409 ggml_nrows(cgraph->nodes[next_node_idx]) == 1 && 12410 ctx->device->add_rms_fusion) { 12411 uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]); 12412 ctx->do_add_rms_partials_offset_calculation = true; 12413 if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) { 12414 ctx->do_add_rms_partials = true; 12415 } 12416 } 12417 } 12418 12419 vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); 12420 12421 { 12422 // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers 12423 // to synchronize them. This handles most "normal" synchronization when computing the graph, and when 12424 // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers 12425 // outside of this logic. When a node uses one of the prealloc buffers for something like 12426 // dequantization or split_k, additional synchronization is needed between those passes. 12427 bool need_sync = false; 12428 12429 // Check whether "node" requires synchronization. The node requires synchronization if it 12430 // overlaps in memory with another unsynchronized node and at least one of them is a write. 12431 // Destination nodes are checked against both the written/read lists. Source nodes are only 12432 // checked against the written list. Two nodes overlap in memory if they come from the same 12433 // buffer and the tensor or view ranges overlap. 12434 auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector &unsynced_nodes) -> bool { 12435 if (unsynced_nodes.size() == 0) { 12436 return false; 12437 } 12438 auto n_base = vk_tensor_offset(node) + node->view_offs; 12439 auto n_size = ggml_nbytes(node); 12440 ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context; 12441 vk_buffer a_buf = a_buf_ctx->dev_buffer; 12442 for (auto &other : unsynced_nodes) { 12443 ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context; 12444 vk_buffer o_buf = o_buf_ctx->dev_buffer; 12445 if (a_buf == o_buf) { 12446 auto o_base = vk_tensor_offset(other) + other->view_offs; 12447 auto o_size = ggml_nbytes(other); 12448 12449 if ((o_base <= n_base && n_base < o_base + o_size) || 12450 (n_base <= o_base && o_base < n_base + n_size)) { 12451 return true; 12452 } 12453 } 12454 } 12455 return false; 12456 }; 12457 12458 // For all fused ops, check if the destination node or any of the source 12459 // nodes require synchronization. 12460 for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) { 12461 const ggml_tensor *cur_node = cgraph->nodes[node_idx + i]; 12462 // If the node actually writes to memory, then check if it needs to sync 12463 if (ctx->fused_ops_write_mask & (1 << i)) { 12464 if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) { 12465 need_sync = true; 12466 break; 12467 } 12468 } 12469 for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) { 12470 if (!cur_node->src[j]) { 12471 continue; 12472 } 12473 if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) { 12474 need_sync = true; 12475 break; 12476 } 12477 } 12478 } 12479 12480 if (need_sync) { 12481 if (vk_enable_sync_logger) { 12482 std::cerr << "sync" << std::endl; 12483 } 12484 ctx->unsynced_nodes_written.clear(); 12485 ctx->unsynced_nodes_read.clear(); 12486 ggml_vk_sync_buffers(ctx, compute_ctx); 12487 12488 if (vk_perf_logger_enabled && vk_perf_logger_concurrent) { 12489 ctx->query_node_idx[ctx->query_idx] = node_idx; 12490 compute_ctx->s->buffer->buf.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++); 12491 ggml_vk_sync_buffers(ctx, compute_ctx); 12492 } 12493 } 12494 // Add all fused nodes to the unsynchronized lists. 12495 for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) { 12496 const ggml_tensor *cur_node = cgraph->nodes[node_idx + i]; 12497 // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list. 12498 if (ctx->fused_ops_write_mask & (1 << i)) { 12499 ctx->unsynced_nodes_written.push_back(cur_node); 12500 } 12501 for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) { 12502 if (!cur_node->src[j]) { 12503 continue; 12504 } 12505 ctx->unsynced_nodes_read.push_back(cur_node->src[j]); 12506 } 12507 } 12508 } 12509 if (vk_enable_sync_logger) { 12510 for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) { 12511 auto *n = cgraph->nodes[node_idx + i]; 12512 std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name; 12513 if (n->op == GGML_OP_GLU) { 12514 std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " "; 12515 } 12516 if (n->op == GGML_OP_ROPE) { 12517 const int mode = ((const int32_t *) n->op_params)[2]; 12518 std::cerr << " rope mode: " << mode; 12519 } 12520 std::cerr << std::endl; 12521 } 12522 } 12523 12524 // closed explicitly below, and by the destructor on the early returns 12525 ggml_vk_debug_label dbg(compute_ctx, cgraph, node_idx, ctx->num_additional_fused_ops); 12526 12527 switch (node->op) { 12528 case GGML_OP_REPEAT: 12529 ggml_vk_repeat(ctx, compute_ctx, src0, node); 12530 12531 break; 12532 case GGML_OP_REPEAT_BACK: 12533 ggml_vk_repeat_back(ctx, compute_ctx, src0, node); 12534 12535 break; 12536 case GGML_OP_ACC: 12537 case GGML_OP_SET: 12538 ggml_vk_acc(ctx, compute_ctx, src0, src1, node); 12539 12540 break; 12541 case GGML_OP_GET_ROWS: 12542 if (ctx->fused_topk_qsa) { 12543 ggml_vk_topk_qsa(ctx, compute_ctx, cgraph, node_idx); 12544 } else { 12545 ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node); 12546 } 12547 12548 break; 12549 case GGML_OP_GET_ROWS_BACK: 12550 ggml_vk_get_rows_back(ctx, compute_ctx, src0, src1, node); 12551 12552 break; 12553 case GGML_OP_ADD: 12554 if (ctx->num_additional_fused_ops) { 12555 ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx); 12556 } else { 12557 ggml_vk_add(ctx, compute_ctx, src0, src1, node); 12558 } 12559 break; 12560 case GGML_OP_OUT_PROD: 12561 ggml_vk_out_prod(ctx, compute_ctx, src0, src1, node); 12562 break; 12563 case GGML_OP_SUB: 12564 ggml_vk_sub(ctx, compute_ctx, src0, src1, node); 12565 12566 break; 12567 case GGML_OP_MUL: 12568 if (ctx->num_additional_fused_ops) { 12569 ggml_vk_snake_dispatch_fused(ctx, compute_ctx, cgraph, node_idx); 12570 } else { 12571 ggml_vk_mul(ctx, compute_ctx, src0, src1, node); 12572 } 12573 12574 break; 12575 case GGML_OP_DIV: 12576 ggml_vk_div(ctx, compute_ctx, src0, src1, node); 12577 12578 break; 12579 case GGML_OP_ADD_ID: 12580 ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node); 12581 12582 break; 12583 case GGML_OP_CONCAT: 12584 ggml_vk_concat(ctx, compute_ctx, src0, src1, node); 12585 12586 break; 12587 case GGML_OP_UPSCALE: 12588 ggml_vk_upscale(ctx, compute_ctx, src0, node); 12589 12590 break; 12591 case GGML_OP_ADD1: 12592 ggml_vk_add1(ctx, compute_ctx, src0, src1, node); 12593 12594 break; 12595 case GGML_OP_ARANGE: 12596 ggml_vk_arange(ctx, compute_ctx, node); 12597 12598 break; 12599 case GGML_OP_FILL: 12600 ggml_vk_fill(ctx, compute_ctx, node); 12601 12602 break; 12603 case GGML_OP_SCALE: 12604 if (ctx->fused_hc_post_gate) { 12605 ggml_tensor * hc_post = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; 12606 ggml_vk_dsv4_hc_post(ctx, compute_ctx, hc_post->src[0], hc_post->src[1], hc_post->src[2], hc_post->src[3], hc_post, node); 12607 } else { 12608 ggml_vk_scale(ctx, compute_ctx, src0, node); 12609 } 12610 12611 break; 12612 case GGML_OP_SQR: 12613 ggml_vk_sqr(ctx, compute_ctx, src0, node); 12614 12615 break; 12616 case GGML_OP_SQRT: 12617 ggml_vk_sqrt(ctx, compute_ctx, src0, node); 12618 12619 break; 12620 case GGML_OP_SIN: 12621 ggml_vk_sin(ctx, compute_ctx, src0, node); 12622 12623 break; 12624 case GGML_OP_COS: 12625 ggml_vk_cos(ctx, compute_ctx, src0, node); 12626 12627 break; 12628 case GGML_OP_LOG: 12629 ggml_vk_log(ctx, compute_ctx, src0, node); 12630 12631 break; 12632 case GGML_OP_TRI: 12633 ggml_vk_tri(ctx, compute_ctx, src0, node); 12634 12635 break; 12636 case GGML_OP_DIAG: 12637 ggml_vk_diag(ctx, compute_ctx, src0, node); 12638 12639 break; 12640 case GGML_OP_CLAMP: 12641 ggml_vk_clamp(ctx, compute_ctx, src0, node); 12642 12643 break; 12644 case GGML_OP_PAD: 12645 ggml_vk_pad(ctx, compute_ctx, src0, node); 12646 12647 break; 12648 case GGML_OP_PAD_REFLECT_1D: 12649 ggml_vk_pad_reflect_1d(ctx, compute_ctx, src0, node); 12650 12651 break; 12652 case GGML_OP_ROLL: 12653 ggml_vk_roll(ctx, compute_ctx, src0, node); 12654 12655 break; 12656 case GGML_OP_CPY: 12657 case GGML_OP_CONT: 12658 case GGML_OP_DUP: 12659 ggml_vk_cpy(ctx, compute_ctx, src0, node); 12660 12661 break; 12662 case GGML_OP_SET_ROWS: 12663 ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node); 12664 12665 break; 12666 case GGML_OP_SILU_BACK: 12667 ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node); 12668 12669 break; 12670 case GGML_OP_NORM: 12671 ggml_vk_norm(ctx, compute_ctx, src0, node); 12672 12673 break; 12674 case GGML_OP_GROUP_NORM: 12675 ggml_vk_group_norm(ctx, compute_ctx, src0, node); 12676 12677 break; 12678 case GGML_OP_RMS_NORM: 12679 ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params); 12680 break; 12681 case GGML_OP_RMS_NORM_BACK: 12682 ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node); 12683 12684 break; 12685 case GGML_OP_L2_NORM: 12686 ggml_vk_l2_norm(ctx, compute_ctx, src0, node); 12687 12688 break; 12689 case GGML_OP_UNARY: 12690 if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) { 12691 ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx); 12692 break; 12693 } 12694 if (ctx->num_additional_fused_ops) { 12695 ggml_vk_unary_mul(ctx, compute_ctx, cgraph, node_idx); 12696 break; 12697 } 12698 12699 switch (ggml_get_unary_op(node)) { 12700 case GGML_UNARY_OP_ELU: 12701 case GGML_UNARY_OP_EXP: 12702 case GGML_UNARY_OP_EXPM1: 12703 case GGML_UNARY_OP_SILU: 12704 case GGML_UNARY_OP_GELU: 12705 case GGML_UNARY_OP_GELU_ERF: 12706 case GGML_UNARY_OP_GELU_QUICK: 12707 case GGML_UNARY_OP_RELU: 12708 case GGML_UNARY_OP_NEG: 12709 case GGML_UNARY_OP_TANH: 12710 case GGML_UNARY_OP_SIGMOID: 12711 case GGML_UNARY_OP_HARDSIGMOID: 12712 case GGML_UNARY_OP_HARDSWISH: 12713 case GGML_UNARY_OP_ABS: 12714 case GGML_UNARY_OP_SOFTPLUS: 12715 case GGML_UNARY_OP_STEP: 12716 case GGML_UNARY_OP_ROUND: 12717 case GGML_UNARY_OP_CEIL: 12718 case GGML_UNARY_OP_FLOOR: 12719 case GGML_UNARY_OP_TRUNC: 12720 case GGML_UNARY_OP_SGN: 12721 ggml_vk_unary(ctx, compute_ctx, src0, node); 12722 break; 12723 case GGML_UNARY_OP_XIELU: 12724 ggml_vk_xielu(ctx, compute_ctx, src0, node); 12725 break; 12726 default: 12727 return false; 12728 } 12729 break; 12730 case GGML_OP_GLU: 12731 switch (ggml_get_glu_op(node)) { 12732 case GGML_GLU_OP_GEGLU: 12733 case GGML_GLU_OP_REGLU: 12734 case GGML_GLU_OP_SWIGLU: 12735 case GGML_GLU_OP_SWIGLU_OAI: 12736 case GGML_GLU_OP_GEGLU_ERF: 12737 case GGML_GLU_OP_GEGLU_QUICK: 12738 case GGML_GLU_OP_SWIGLU_CLAMP: 12739 ggml_vk_glu(ctx, compute_ctx, src0, src1, node); 12740 break; 12741 default: 12742 return false; 12743 } 12744 break; 12745 case GGML_OP_DIAG_MASK_INF: 12746 ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node); 12747 12748 break; 12749 case GGML_OP_SOFT_MAX: 12750 if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) { 12751 ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx); 12752 } else { 12753 ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node); 12754 } 12755 12756 break; 12757 case GGML_OP_SOFT_MAX_BACK: 12758 ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node); 12759 12760 break; 12761 case GGML_OP_ROPE: 12762 ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false); 12763 12764 break; 12765 case GGML_OP_ROPE_BACK: 12766 ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true); 12767 12768 break; 12769 case GGML_OP_ARGSORT: 12770 if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) { 12771 ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx); 12772 } else { 12773 ggml_vk_argsort(ctx, compute_ctx, src0, node); 12774 } 12775 12776 break; 12777 case GGML_OP_TOP_K: 12778 ggml_vk_topk(ctx, compute_ctx, src0, node); 12779 12780 break; 12781 case GGML_OP_SUM: 12782 ggml_vk_sum(ctx, compute_ctx, src0, node); 12783 12784 break; 12785 case GGML_OP_SUM_ROWS: 12786 ggml_vk_sum_rows(ctx, compute_ctx, src0, node); 12787 12788 break; 12789 case GGML_OP_CUMSUM: 12790 ggml_vk_cumsum(ctx, compute_ctx, src0, node); 12791 12792 break; 12793 case GGML_OP_DSV4_HC_COMB: 12794 ggml_vk_dsv4_hc_comb(ctx, compute_ctx, src0, src1, src2, node); 12795 12796 break; 12797 case GGML_OP_DSV4_HC_PRE: 12798 ggml_vk_dsv4_hc_pre(ctx, compute_ctx, src0, src1, node); 12799 12800 break; 12801 case GGML_OP_DSV4_HC_POST: 12802 ggml_vk_dsv4_hc_post(ctx, compute_ctx, src0, src1, src2, src3, node); 12803 12804 break; 12805 case GGML_OP_MEAN: 12806 ggml_vk_mean(ctx, compute_ctx, src0, node); 12807 12808 break; 12809 case GGML_OP_ARGMAX: 12810 ggml_vk_argmax(ctx, compute_ctx, src0, node); 12811 12812 break; 12813 case GGML_OP_CROSS_ENTROPY_LOSS: 12814 ggml_vk_cross_entropy_loss(ctx, compute_ctx, node); 12815 12816 break; 12817 case GGML_OP_CROSS_ENTROPY_LOSS_BACK: 12818 ggml_vk_cross_entropy_loss_back(ctx, compute_ctx, node); 12819 12820 break; 12821 case GGML_OP_COUNT_EQUAL: 12822 ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node); 12823 12824 break; 12825 case GGML_OP_SOLVE_TRI: 12826 ggml_vk_solve_tri(ctx, compute_ctx, src0, src1, node); 12827 12828 break; 12829 case GGML_OP_IM2COL: 12830 ggml_vk_im2col(ctx, compute_ctx, src0, src1, node); 12831 12832 break; 12833 case GGML_OP_IM2COL_3D: 12834 ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node); 12835 12836 break; 12837 case GGML_OP_TIMESTEP_EMBEDDING: 12838 ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node); 12839 12840 break; 12841 case GGML_OP_COL2IM_1D: 12842 ggml_vk_col2im_1d(ctx, compute_ctx, src0, node); 12843 12844 break; 12845 case GGML_OP_CONV_TRANSPOSE_1D: 12846 ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node); 12847 12848 break; 12849 case GGML_OP_POOL_1D: 12850 ggml_vk_pool_1d(ctx, compute_ctx, src0, node); 12851 12852 break; 12853 case GGML_OP_POOL_2D: 12854 ggml_vk_pool_2d(ctx, compute_ctx, src0, node); 12855 12856 break; 12857 case GGML_OP_CONV_2D: 12858 case GGML_OP_CONV_TRANSPOSE_2D: 12859 ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node); 12860 12861 break; 12862 case GGML_OP_CONV_3D: 12863 ggml_vk_conv_3d(ctx, compute_ctx, src0, src1, node); 12864 12865 break; 12866 case GGML_OP_CONV_2D_DW: 12867 ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node); 12868 12869 break; 12870 case GGML_OP_LEAKY_RELU: 12871 ggml_vk_leaky_relu(ctx, compute_ctx, src0, node); 12872 12873 break; 12874 case GGML_OP_MUL_MAT: 12875 ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx); 12876 12877 break; 12878 case GGML_OP_MUL_MAT_ID: 12879 ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx); 12880 12881 break; 12882 12883 case GGML_OP_FLASH_ATTN_EXT: 12884 ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node); 12885 12886 break; 12887 12888 case GGML_OP_RWKV_WKV6: 12889 ggml_vk_rwkv_wkv6(ctx, compute_ctx, node); 12890 12891 break; 12892 12893 case GGML_OP_RWKV_WKV7: 12894 ggml_vk_rwkv_wkv7(ctx, compute_ctx, node); 12895 12896 break; 12897 12898 case GGML_OP_GATED_LINEAR_ATTN: 12899 ggml_vk_gated_linear_attn(ctx, compute_ctx, node); 12900 12901 break; 12902 12903 case GGML_OP_LIGHTNING_INDEXER: 12904 ggml_vk_lightning_indexer(ctx, compute_ctx, node); 12905 12906 break; 12907 12908 case GGML_OP_GATED_DELTA_NET: 12909 ggml_vk_gated_delta_net(ctx, compute_ctx, node); 12910 12911 break; 12912 12913 case GGML_OP_SSM_SCAN: 12914 ggml_vk_ssm_scan(ctx, compute_ctx, node); 12915 12916 break; 12917 12918 case GGML_OP_SSM_CONV: 12919 ggml_vk_ssm_conv(ctx, compute_ctx, cgraph, node_idx); 12920 12921 break; 12922 12923 case GGML_OP_OPT_STEP_ADAMW: 12924 ggml_vk_opt_step_adamw(ctx, compute_ctx, node); 12925 12926 break; 12927 12928 case GGML_OP_OPT_STEP_SGD: 12929 ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node); 12930 12931 break; 12932 default: 12933 return false; 12934 } 12935 12936 // the submit path below can end the command buffer, so close the region first 12937 dbg.close(); 12938 12939 ctx->tensor_ctxs[node_idx] = compute_ctx; 12940 12941 #if defined(GGML_VULKAN_CHECK_RESULTS) 12942 // Force context reset on each node so that each tensor ends up in its own context 12943 // and can be run and compared to its CPU equivalent separately 12944 last_node = true; 12945 #endif 12946 12947 if (submit || last_node) { 12948 ggml_vk_ctx_end(compute_ctx); 12949 12950 // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward 12951 if (last_node) { 12952 compute_ctx->exit_tensor_idx = node_idx_begin; 12953 } 12954 else { 12955 compute_ctx->exit_tensor_idx = -1; 12956 } 12957 12958 ctx->compute_ctx.reset(); 12959 12960 ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready); 12961 } 12962 return true; 12963 } 12964 12965 void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready) { 12966 GGML_UNUSED(cgraph); 12967 GGML_UNUSED(tensor); 12968 12969 VK_LOG_DEBUG("ggml_vk_compute_forward(" << tensor << ", name=" << tensor->name << ", op=" << ggml_op_name(tensor->op) << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << ", view_src=" << tensor->view_src << ", view_offs=" << tensor->view_offs << ")"); 12970 12971 vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock(); 12972 12973 // Only run if ctx hasn't been submitted yet 12974 if (!subctx->seqs.empty()) { 12975 #ifdef GGML_VULKAN_CHECK_RESULTS 12976 ggml_vk_check_results_0(ctx, cgraph, tensor_idx); 12977 #endif 12978 12979 // Do staging buffer copies 12980 for (auto& cpy : subctx->in_memcpys) { 12981 memcpy(cpy.dst, cpy.src, cpy.n); 12982 } 12983 12984 for (auto& mset : subctx->memsets) { 12985 memset(mset.dst, mset.val, mset.n); 12986 } 12987 12988 if (ctx->device->serialize_submissions) { 12989 ggml_vk_submit(subctx, ctx->fence); 12990 } else if (almost_ready && !ctx->almost_ready_fence_pending) { 12991 ggml_vk_submit(subctx, ctx->almost_ready_fence); 12992 ctx->almost_ready_fence_pending = true; 12993 } else { 12994 ggml_vk_submit(subctx, {}); 12995 } 12996 ctx->submit_pending = true; 12997 12998 #ifdef GGML_VULKAN_CHECK_RESULTS 12999 ggml_vk_synchronize(ctx); 13000 ggml_vk_check_results_1(ctx, cgraph, tensor_idx); 13001 #endif 13002 } 13003 13004 if (tensor_idx == subctx->exit_tensor_idx) { 13005 // Do staging buffer copies 13006 for (auto& cpy : subctx->out_memcpys) { 13007 memcpy(cpy.dst, cpy.src, cpy.n); 13008 } 13009 subctx->in_memcpys.clear(); 13010 subctx->out_memcpys.clear(); 13011 subctx->memsets.clear(); 13012 } 13013 } 13014 13015 void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) { 13016 VK_LOG_DEBUG("ggml_vk_graph_cleanup()"); 13017 ctx->prealloc_y_last_pipeline_used = {}; 13018 ctx->prealloc_y_last_tensor_used = nullptr; 13019 ctx->prealloc_y_last_k_padded = false; 13020 13021 ctx->unsynced_nodes_written.clear(); 13022 ctx->unsynced_nodes_read.clear(); 13023 ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false; 13024 13025 ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool); 13026 if (ctx->device->async_use_transfer_queue) { 13027 ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool); 13028 } 13029 13030 ctx->binary_semaphore_idx = 0; 13031 13032 for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) { 13033 ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s }); 13034 } 13035 ctx->gc.tl_semaphores.clear(); 13036 ctx->semaphore_idx = 0; 13037 13038 ctx->event_idx = 0; 13039 13040 for (auto& event : ctx->gc.events) { 13041 ctx->device->device.resetEvent(event); 13042 } 13043 13044 ctx->tensor_ctxs.clear(); 13045 ctx->gc.contexts.clear(); 13046 ctx->pipeline_descriptor_set_requirements = 0; 13047 ctx->descriptor_set_idx = 0; 13048 } 13049 13050 void ggml_vk_cleanup(ggml_backend_vk_context * ctx) { 13051 VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")"); 13052 // discard any unsubmitted command buffers 13053 ctx->compute_ctx.reset(); 13054 // wait for any pending command buffers to finish 13055 ggml_vk_synchronize(ctx); 13056 13057 ggml_vk_graph_cleanup(ctx); 13058 13059 ggml_vk_destroy_buffer(ctx->prealloc_x); 13060 ggml_vk_destroy_buffer(ctx->prealloc_y); 13061 ggml_vk_destroy_buffer(ctx->prealloc_split_k); 13062 ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials); 13063 ggml_vk_destroy_buffer(ctx->sync_staging); 13064 13065 ctx->prealloc_y_last_pipeline_used = nullptr; 13066 ctx->prealloc_y_last_tensor_used = nullptr; 13067 ctx->prealloc_y_last_k_padded = false; 13068 13069 ctx->prealloc_size_x = 0; 13070 ctx->prealloc_size_y = 0; 13071 ctx->prealloc_size_split_k = 0; 13072 13073 for (auto& event : ctx->gc.events) { 13074 ctx->device->device.destroyEvent(event); 13075 } 13076 ctx->gc.events.clear(); 13077 13078 for (auto & sem : ctx->gc.semaphores) { 13079 ctx->device->device.destroySemaphore(sem.s); 13080 } 13081 ctx->gc.semaphores.clear(); 13082 13083 ctx->device->device.destroyFence(ctx->fence); 13084 ctx->device->device.destroyFence(ctx->almost_ready_fence); 13085 13086 for (auto& pool : ctx->descriptor_pools) { 13087 ctx->device->device.destroyDescriptorPool(pool); 13088 } 13089 ctx->descriptor_pools.clear(); 13090 ctx->descriptor_sets.clear(); 13091 ctx->descriptor_set_bindings.clear(); 13092 13093 ctx->compute_cmd_pool.destroy(ctx->device->device); 13094 if (ctx->device->async_use_transfer_queue) { 13095 ctx->device->device.destroySemaphore(ctx->transfer_semaphore.s); 13096 13097 ctx->transfer_cmd_pool.destroy(ctx->device->device); 13098 } 13099 if (vk_perf_logger_enabled) { 13100 ctx->perf_logger->print_timings(true); 13101 } 13102 } 13103 13104 int ggml_vk_get_device_count() { 13105 ggml_vk_instance_init(); 13106 13107 return vk_instance.device_indices.size(); 13108 } 13109 13110 void ggml_vk_get_device_description(int device, char * description, size_t description_size) { 13111 ggml_vk_instance_init(); 13112 13113 std::vector devices = vk_instance.instance.enumeratePhysicalDevices(); 13114 13115 vk::PhysicalDeviceProperties props; 13116 devices[device].getProperties(&props); 13117 13118 snprintf(description, description_size, "%s", props.deviceName.data()); 13119 } 13120 13121 bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) { 13122 return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name; 13123 } 13124 13125 void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) { 13126 VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()"); 13127 ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context; 13128 ggml_vk_destroy_buffer(ctx->dev_buffer); 13129 delete ctx; 13130 } 13131 13132 void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) { 13133 return vk_ptr_base; 13134 13135 UNUSED(buffer); 13136 } 13137 13138 enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) { 13139 VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")"); 13140 if (tensor->view_src != nullptr) { 13141 GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft); 13142 } 13143 return GGML_STATUS_SUCCESS; 13144 } 13145 13146 void ggml_backend_vk_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) { 13147 VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")"); 13148 ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context; 13149 vk_buffer buf = buf_ctx->dev_buffer; 13150 13151 if (size == 0) { 13152 return; 13153 } 13154 13155 uint32_t val32 = (uint32_t)value * 0x01010101; 13156 ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size); 13157 } 13158 13159 void ggml_backend_vk_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { 13160 VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")"); 13161 ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context; 13162 vk_buffer buf = buf_ctx->dev_buffer; 13163 13164 if (size == 0) { 13165 return; 13166 } 13167 13168 ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size); 13169 } 13170 13171 void ggml_backend_vk_buffer_set_tensor_2d(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, 13172 size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { 13173 VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor_2d(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ", " << 13174 n_copies << ", " << stride_tensor << ", " << stride_data << ")"); 13175 ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context; 13176 vk_buffer buf = buf_ctx->dev_buffer; 13177 13178 if (size == 0) { 13179 return; 13180 } 13181 13182 ggml_vk_buffer_write_2d(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, stride_data, stride_tensor, size, n_copies); 13183 } 13184 13185 void ggml_backend_vk_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { 13186 VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")"); 13187 ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context; 13188 13189 if (size == 0) { 13190 return; 13191 } 13192 13193 vk_buffer buf = buf_ctx->dev_buffer; 13194 13195 ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size); 13196 } 13197 13198 void ggml_backend_vk_buffer_get_tensor_2d(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, 13199 size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { 13200 VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor_2d(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ", " << 13201 n_copies << ", " << stride_tensor << ", " << stride_data << ")"); 13202 ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context; 13203 13204 if (size == 0) { 13205 return; 13206 } 13207 13208 vk_buffer buf = buf_ctx->dev_buffer; 13209 13210 ggml_vk_buffer_read_2d(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, stride_tensor, stride_data, size, n_copies); 13211 } 13212 13213 bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) { 13214 if (ggml_nbytes(src) == 0) { 13215 return true; 13216 } 13217 13218 if (ggml_backend_buffer_is_vk(src->buffer)) { 13219 ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context; 13220 ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; 13221 13222 vk_buffer src_buf = src_buf_ctx->dev_buffer; 13223 vk_buffer dst_buf = dst_buf_ctx->dev_buffer; 13224 13225 ggml_vk_buffer_copy(dst_buf, vk_tensor_offset(dst) + dst->view_offs, src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src)); 13226 13227 return true; 13228 } 13229 return false; 13230 13231 UNUSED(buffer); 13232 } 13233 13234 void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { 13235 ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context; 13236 13237 ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size); 13238 } 13239 13240 const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) { 13241 ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context; 13242 13243 return ctx->name.c_str(); 13244 } 13245 13246 ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { 13247 VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")"); 13248 ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context; 13249 13250 vk_buffer dev_buffer = nullptr; 13251 try { 13252 dev_buffer = ggml_vk_create_buffer_device(ctx->device, size); 13253 } catch (const vk::SystemError& e) { 13254 return nullptr; 13255 } 13256 13257 ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name); 13258 13259 return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size); 13260 } 13261 13262 size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) { 13263 ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context; 13264 return ctx->device->properties.limits.minStorageBufferOffsetAlignment; 13265 } 13266 13267 size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) { 13268 ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context; 13269 return ctx->device->suballocation_block_size; 13270 } 13271 13272 size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) { 13273 return ggml_nbytes(tensor); 13274 13275 UNUSED(buft); 13276 } 13277 13278 ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) { 13279 ggml_vk_instance_init(); 13280 13281 VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")"); 13282 13283 vk_device dev = ggml_vk_get_device(dev_num); 13284 13285 return &dev->buffer_type; 13286 } 13287 13288 static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) { 13289 return GGML_VK_NAME "_Host"; 13290 13291 UNUSED(buft); 13292 } 13293 13294 static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) { 13295 VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()"); 13296 ggml_vk_host_free(buffer->context); 13297 } 13298 13299 static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { 13300 VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")"); 13301 13302 size += 32; // Behave like the CPU buffer type 13303 void * ptr = ggml_vk_host_malloc(size); 13304 if (ptr == nullptr) { 13305 GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory\n"); 13306 // fallback to cpu buffer 13307 return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size); 13308 } 13309 13310 ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size); 13311 buffer->buft = buft; 13312 buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer; 13313 13314 return buffer; 13315 13316 UNUSED(buft); 13317 } 13318 13319 static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) { 13320 return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment; 13321 13322 UNUSED(buft); 13323 } 13324 13325 static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) { 13326 return vk_instance.devices[0]->suballocation_block_size; 13327 13328 UNUSED(buft); 13329 } 13330 13331 ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() { 13332 static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = { 13333 /* .iface = */ { 13334 /* .get_name = */ ggml_backend_vk_host_buffer_type_name, 13335 /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer, 13336 /* .alloc_buffer_n = */ nullptr, 13337 /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment, 13338 /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size, 13339 /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size, 13340 /* .get_alloc_size_n = */ NULL, 13341 /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host, 13342 }, 13343 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0), 13344 /* .context = */ nullptr, 13345 }; 13346 13347 // Make sure device 0 is initialized 13348 ggml_vk_instance_init(); 13349 ggml_vk_get_device(0); 13350 13351 return &ggml_backend_vk_buffer_type_host; 13352 } 13353 13354 static const char * ggml_backend_vk_name(ggml_backend_t backend) { 13355 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 13356 13357 return ctx->name.c_str(); 13358 } 13359 13360 void ggml_backend_vk_free(ggml_backend_t backend) { 13361 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 13362 VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")"); 13363 13364 ggml_vk_cleanup(ctx); 13365 13366 delete ctx; 13367 delete backend; 13368 } 13369 13370 static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) { 13371 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 13372 13373 return &ctx->device->buffer_type; 13374 } 13375 13376 static void ggml_backend_vk_set_tensor_2d_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, 13377 size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { 13378 VK_LOG_DEBUG("ggml_backend_vk_set_tensor_2d_async(" << size << ", " << n_copies << ")"); 13379 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 13380 GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type"); 13381 13382 if (size == 0) { 13383 return; 13384 } 13385 13386 ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context; 13387 13388 vk_context cpy_ctx; 13389 13390 if (ctx->device->async_use_transfer_queue) { 13391 cpy_ctx = ggml_vk_get_transfer_ctx(ctx); 13392 } else { 13393 cpy_ctx = ggml_vk_get_compute_ctx(ctx); 13394 } 13395 13396 vk_buffer buf = buf_ctx->dev_buffer; 13397 13398 auto dst_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset; 13399 13400 bool ret = ggml_vk_buffer_write_2d_async(cpy_ctx, buf, dst_offset, data, stride_data, stride_tensor, size, n_copies); 13401 13402 if (!ret) { 13403 const size_t staging_size = size * n_copies; 13404 ggml_vk_ensure_sync_staging_buffer(ctx, staging_size); 13405 ggml_vk_sync_buffers(nullptr, cpy_ctx); 13406 13407 std::vector slices(1); 13408 if (size == stride_tensor) { 13409 slices[0].srcOffset = 0; 13410 slices[0].dstOffset = dst_offset; 13411 slices[0].size = staging_size; 13412 } else { 13413 slices.resize(n_copies); 13414 for (size_t i = 0; i < n_copies; i++) { 13415 slices[i].srcOffset = i * size; 13416 slices[i].dstOffset = dst_offset + i * stride_tensor; 13417 slices[i].size = size; 13418 } 13419 } 13420 13421 cpy_ctx->s->buffer->buf.copyBuffer(ctx->sync_staging->buffer, buf->buffer, slices); 13422 13423 if (size == stride_data) { 13424 deferred_memcpy(ctx->sync_staging->ptr, data, staging_size, &cpy_ctx->in_memcpys); 13425 } else { 13426 for (size_t i = 0; i < n_copies; i++) { 13427 deferred_memcpy((uint8_t *)ctx->sync_staging->ptr + i * size, (const uint8_t *)data + i * stride_data, size, &cpy_ctx->in_memcpys); 13428 } 13429 } 13430 ggml_vk_synchronize(ctx); 13431 } 13432 } 13433 13434 static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { 13435 VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")"); 13436 ggml_backend_vk_set_tensor_2d_async(backend, tensor, data, offset, size, 1, size, size); 13437 } 13438 13439 static void ggml_backend_vk_get_tensor_2d_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, 13440 size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { 13441 VK_LOG_DEBUG("ggml_backend_vk_get_tensor_2d_async(" << size << ", " << n_copies << ")"); 13442 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 13443 GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type"); 13444 13445 if (size == 0) { 13446 return; 13447 } 13448 13449 ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context; 13450 13451 vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); 13452 13453 vk_buffer buf = buf_ctx->dev_buffer; 13454 13455 auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset; 13456 bool ret = ggml_vk_buffer_read_2d_async(compute_ctx, buf, src_offset, data, stride_tensor, stride_data, size, n_copies); 13457 13458 if (!ret) { 13459 const size_t staging_size = size * n_copies; 13460 ggml_vk_ensure_sync_staging_buffer(ctx, staging_size); 13461 ggml_vk_sync_buffers(nullptr, compute_ctx); 13462 13463 std::vector slices(1); 13464 if (size == stride_tensor) { 13465 slices[0].srcOffset = src_offset; 13466 slices[0].dstOffset = 0; 13467 slices[0].size = staging_size; 13468 } else { 13469 slices.resize(n_copies); 13470 for (size_t i = 0; i < n_copies; i++) { 13471 slices[i].srcOffset = src_offset + i * stride_tensor; 13472 slices[i].dstOffset = i * size; 13473 slices[i].size = size; 13474 } 13475 } 13476 13477 compute_ctx->s->buffer->buf.copyBuffer(buf->buffer, ctx->sync_staging->buffer, slices); 13478 13479 if (size == stride_data) { 13480 deferred_memcpy(data, ctx->sync_staging->ptr, staging_size, &compute_ctx->out_memcpys); 13481 } else { 13482 for (size_t i = 0; i < n_copies; i++) { 13483 deferred_memcpy((uint8_t *)data + i * stride_data, (const uint8_t *)ctx->sync_staging->ptr + i * size, size, &compute_ctx->out_memcpys); 13484 } 13485 } 13486 ggml_vk_synchronize(ctx); 13487 } 13488 } 13489 13490 static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { 13491 VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")"); 13492 ggml_backend_vk_get_tensor_2d_async(backend, tensor, data, offset, size, 1, size, size); 13493 } 13494 13495 static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const ggml_tensor * src, ggml_tensor * dst) { 13496 VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async(" << src << " -> " << dst << ", size=" << ggml_nbytes(src) << ")"); 13497 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend_dst->context; 13498 13499 // Skip zero-size tensors 13500 if (ggml_nbytes(src) == 0) { 13501 return true; 13502 } 13503 13504 if (dst->buffer->buft != ggml_backend_vk_get_default_buffer_type(backend_dst)) { 13505 return false; 13506 } 13507 13508 ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context; 13509 vk_buffer dst_buf = dst_buf_ctx->dev_buffer; 13510 13511 if (ggml_backend_buffer_is_vk(src->buffer)) { 13512 ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context; 13513 13514 // Async copy only works within the same device 13515 if (src_buf_ctx->dev_buffer->device != dst_buf->device) { 13516 return false; 13517 } 13518 13519 vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); 13520 13521 ggml_vk_buffer_copy_async(compute_ctx, dst_buf, vk_tensor_offset(dst) + dst->view_offs, 13522 src_buf_ctx->dev_buffer, vk_tensor_offset(src) + src->view_offs, 13523 ggml_nbytes(src)); 13524 return true; 13525 } 13526 13527 if (ggml_backend_buffer_is_host(src->buffer)) { 13528 vk_buffer pinned_buf = nullptr; 13529 size_t pinned_offset = 0; 13530 ggml_vk_host_get(ctx->device, src->data, pinned_buf, pinned_offset); 13531 if (pinned_buf == nullptr) { 13532 return false; 13533 } 13534 13535 // If the backend is idle, use a CPU copy to avoid GPU synchronization overhead. 13536 static constexpr size_t max_cpu_copy_size = 128 * 1024; 13537 const bool src_backend_synchronous = backend_src->iface.synchronize == nullptr; 13538 const bool transfer_idle = !ctx->device->async_use_transfer_queue || 13539 ctx->transfer_semaphore_last_submitted == ctx->transfer_semaphore.value; 13540 const bool backend_idle = ctx->compute_ctx.expired() && ctx->transfer_ctx.expired() && 13541 !ctx->submit_pending && !ctx->almost_ready_fence_pending && transfer_idle; 13542 const bool dst_host_coherent = 13543 (dst_buf->memory_property_flags & (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent)) == 13544 (vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); 13545 13546 if ((backend_src == backend_dst || src_backend_synchronous) && backend_idle && dst_host_coherent && ggml_nbytes(src) <= max_cpu_copy_size) { 13547 ggml_vk_buffer_write(dst_buf, vk_tensor_offset(dst) + dst->view_offs, src->data, ggml_nbytes(src)); 13548 return true; 13549 } 13550 13551 vk_context cpy_ctx; 13552 if (ctx->device->async_use_transfer_queue) { 13553 cpy_ctx = ggml_vk_get_transfer_ctx(ctx); 13554 } else { 13555 cpy_ctx = ggml_vk_get_compute_ctx(ctx); 13556 } 13557 13558 return ggml_vk_buffer_write_async(cpy_ctx, dst_buf, 13559 vk_tensor_offset(dst) + dst->view_offs, 13560 src->data, ggml_nbytes(src)); 13561 } 13562 13563 return false; 13564 } 13565 13566 void ggml_vk_synchronize(ggml_backend_vk_context * ctx) { 13567 VK_LOG_DEBUG("ggml_vk_synchronize()"); 13568 13569 bool do_transfer = !ctx->compute_ctx.expired(); 13570 13571 if (ggml_vk_submit_transfer_ctx(ctx)) { 13572 ctx->submit_pending = true; 13573 } 13574 13575 vk_context compute_ctx; 13576 vk_command_buffer* cmd_buf = nullptr; 13577 if (do_transfer) { 13578 compute_ctx = ctx->compute_ctx.lock(); 13579 if (compute_ctx->s) { 13580 cmd_buf = compute_ctx->s->buffer; 13581 } 13582 13583 ggml_vk_ctx_end(compute_ctx); 13584 13585 for (auto& cpy : compute_ctx->in_memcpys) { 13586 memcpy(cpy.dst, cpy.src, cpy.n); 13587 } 13588 13589 if (ctx->device->serialize_submissions) { 13590 ggml_vk_submit(compute_ctx, ctx->fence); 13591 VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "synchronize waitForFences", ctx->device); 13592 ctx->device->device.resetFences({ ctx->fence }); 13593 } else { 13594 ggml_vk_submit(compute_ctx, {}); 13595 } 13596 ctx->submit_pending = true; 13597 } 13598 13599 if (ctx->submit_pending) { 13600 if (ctx->device->serialize_submissions) { 13601 ctx->submit_pending = false; 13602 } else if (ctx->device->async_use_transfer_queue && ctx->transfer_semaphore_last_submitted < ctx->transfer_semaphore.value) { 13603 vk::TimelineSemaphoreSubmitInfo tl_info{ 13604 1, &ctx->transfer_semaphore.value, 13605 0, nullptr, 13606 }; 13607 vk::PipelineStageFlags stage = ctx->device->transfer_queue->stage_flags; 13608 vk::SubmitInfo si{ 13609 1, &ctx->transfer_semaphore.s, &stage, 13610 0, nullptr, 13611 0, nullptr, 13612 }; 13613 si.setPNext(&tl_info); 13614 ctx->device->compute_queue->handle->submit({ si }, ctx->fence); 13615 ctx->transfer_semaphore_last_submitted = ctx->transfer_semaphore.value; 13616 } else { 13617 ctx->device->compute_queue->handle->submit({}, ctx->fence); 13618 } 13619 if (!ctx->device->serialize_submissions) { 13620 ggml_vk_wait_for_fence(ctx); 13621 } 13622 ctx->submit_pending = false; 13623 if (cmd_buf) { 13624 cmd_buf->in_use = false; 13625 cmd_buf->buf.reset(); 13626 } 13627 } 13628 13629 if (do_transfer) { 13630 for (auto& cpy : compute_ctx->out_memcpys) { 13631 memcpy(cpy.dst, cpy.src, cpy.n); 13632 } 13633 ctx->compute_ctx.reset(); 13634 } 13635 } 13636 13637 static void ggml_backend_vk_synchronize(ggml_backend_t backend) { 13638 VK_LOG_DEBUG("ggml_backend_vk_synchronize()"); 13639 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 13640 13641 ggml_vk_synchronize(ctx); 13642 13643 ggml_vk_graph_cleanup(ctx); 13644 } 13645 13646 bool ggml_vk_is_empty(ggml_tensor * node) { 13647 return ggml_is_empty(node) || node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE; 13648 } 13649 13650 static bool ggml_vk_can_fuse_unary_mul(const struct ggml_cgraph * cgraph, int unary_idx, int mul_idx) { 13651 const ggml_tensor * unary = cgraph->nodes[unary_idx]; 13652 const ggml_tensor * mul = cgraph->nodes[mul_idx]; 13653 13654 if (ggml_vk_unary_mul_op_index(ggml_get_unary_op(unary)) < 0) { 13655 return false; 13656 } 13657 if (unary->type != GGML_TYPE_F32 && unary->type != GGML_TYPE_F16) { 13658 return false; 13659 } 13660 if (unary->type != mul->type) { 13661 return false; 13662 } 13663 if (mul->src[0] != unary && mul->src[1] != unary) { 13664 return false; 13665 } 13666 const ggml_tensor * other = (mul->src[0] == unary) ? mul->src[1] : mul->src[0]; 13667 if (other == nullptr || other->type != unary->type) { 13668 return false; 13669 } 13670 if (!ggml_is_contiguous_1(other) || !ggml_is_contiguous_1(unary->src[0])) { 13671 return false; 13672 } 13673 // fastmod needs src to tile into dst 13674 if (mul->src[0] == unary) { 13675 return ggml_can_repeat(other, unary); 13676 } 13677 return ggml_can_repeat(unary, mul->src[0]); 13678 } 13679 13680 static bool ggml_vk_can_fuse_unary_mul_pair(const struct ggml_cgraph * cgraph, int node_idx) { 13681 const enum ggml_op ops[] = { GGML_OP_UNARY, GGML_OP_MUL }; 13682 const int outputs[] = { node_idx + 1 }; 13683 return ggml_can_fuse_subgraph(cgraph, node_idx, 2, ops, outputs, 1) && 13684 ggml_vk_can_fuse_unary_mul(cgraph, node_idx, node_idx + 1); 13685 } 13686 13687 static bool ggml_vk_can_fuse_hc_post_gate(const struct ggml_cgraph * cgraph, int node_idx) { 13688 const ggml_tensor * scale_in = cgraph->nodes[node_idx]; 13689 const ggml_tensor * sigmoid = cgraph->nodes[node_idx + 1]; 13690 const ggml_tensor * scale_out = cgraph->nodes[node_idx + 2]; 13691 13692 // the shader folds scale -> sigmoid -> scale; a bias on either scale is not handled 13693 return ggml_get_unary_op(sigmoid) == GGML_UNARY_OP_SIGMOID && 13694 ggml_get_op_params_f32(scale_in, 1) == 0.0f && 13695 ggml_get_op_params_f32(scale_out, 1) == 0.0f && 13696 scale_in->src[0]->type == GGML_TYPE_F32 && 13697 ggml_are_same_shape(scale_in->src[0], scale_out); 13698 } 13699 13700 bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list ops) { 13701 if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_MUL) { 13702 return ggml_vk_can_fuse_unary_mul_pair(cgraph, node_idx); 13703 } 13704 13705 if (!ggml_can_fuse(cgraph, node_idx, ops)) { 13706 return false; 13707 } 13708 13709 if ((ops.size() == 2 || ops.size() == 3 || ops.size() == 4) && 13710 ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) { 13711 // additional constraints specific to this fusion 13712 const ggml_tensor *rms_norm = cgraph->nodes[node_idx]; 13713 const ggml_tensor *mul = cgraph->nodes[node_idx + 1]; 13714 13715 GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32); 13716 GGML_ASSERT(rms_norm->type == GGML_TYPE_F32); 13717 // rms_norm only supports f32 13718 if (mul->src[0]->type != GGML_TYPE_F32 || 13719 mul->src[1]->type != GGML_TYPE_F32 || 13720 mul->type != GGML_TYPE_F32) { 13721 return false; 13722 } 13723 // if rms_norm is the B operand, then we don't handle broadcast 13724 if (rms_norm == mul->src[1] && 13725 !ggml_are_same_shape(mul->src[0], rms_norm)) { 13726 return false; 13727 } 13728 // rms_norm shader assumes contiguous rows 13729 if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) { 13730 return false; 13731 } 13732 13733 if (ops.size() >= 3 && ops.begin()[2] == GGML_OP_ADD) { 13734 const ggml_tensor *add = cgraph->nodes[node_idx + 2]; 13735 const ggml_tensor *residual = add->src[0] == mul ? add->src[1] : add->src[0]; 13736 if (add->src[0] != mul && add->src[1] != mul) { 13737 return false; 13738 } 13739 if (residual->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 || 13740 !ggml_are_same_shape(add, residual) || !ggml_is_contiguous(residual) || 13741 !ggml_is_contiguous(add) || get_misalign_bytes(ctx, residual) != 0) { 13742 return false; 13743 } 13744 13745 const ggml_tensor *dst = add; 13746 if (ops.size() == 4) { 13747 if (ops.begin()[3] != GGML_OP_MUL) { 13748 return false; 13749 } 13750 13751 const ggml_tensor *post_mul = cgraph->nodes[node_idx + 3]; 13752 const ggml_tensor *scale = post_mul->src[0] == add ? post_mul->src[1] : post_mul->src[0]; 13753 if (post_mul->src[0] != add && post_mul->src[1] != add) { 13754 return false; 13755 } 13756 // The shader reads data_e[0], so the final multiply must use a scalar. 13757 if (scale->type != GGML_TYPE_F32 || post_mul->type != GGML_TYPE_F32 || 13758 ggml_nelements(scale) != 1 || !ggml_is_contiguous(post_mul) || 13759 get_misalign_bytes(ctx, scale) != 0) { 13760 return false; 13761 } 13762 dst = post_mul; 13763 } 13764 13765 if (get_misalign_bytes(ctx, dst) != 0) { 13766 return false; 13767 } 13768 } 13769 } 13770 13771 auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) { 13772 const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0]; 13773 13774 // mat-vec only 13775 if (ggml_nrows(mul) != 1) { 13776 return false; 13777 } 13778 // shaders assume the types match 13779 if (mul->type != bias->type) { 13780 return false; 13781 } 13782 // shaders reuse the D shape for bias 13783 if (!ggml_are_same_shape(mul, bias) || 13784 !ggml_are_same_stride(mul, bias)) { 13785 return false; 13786 } 13787 // unaligned bias isn't handled 13788 if (get_misalign_bytes(ctx, bias) != 0) { 13789 return false; 13790 } 13791 return true; 13792 }; 13793 13794 if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) { 13795 // additional constraints specific to this fusion 13796 const ggml_tensor *mul = cgraph->nodes[node_idx]; 13797 const ggml_tensor *add = cgraph->nodes[node_idx + 1]; 13798 13799 if (!mm_add_ok(mul, add)) { 13800 return false; 13801 } 13802 if (ops.size() == 3) { 13803 if (ops.begin()[2] != GGML_OP_ADD) { 13804 return false; 13805 } 13806 if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) { 13807 return false; 13808 } 13809 } 13810 } 13811 13812 auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) { 13813 const ggml_tensor *scale = mul->src[1]; 13814 13815 if (mmid != mul->src[0]) { 13816 return false; 13817 } 13818 // mat-vec only 13819 if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) { 13820 return false; 13821 } 13822 // shaders assume the types match 13823 if (mmid->type != scale->type) { 13824 return false; 13825 } 13826 // shaders assume the bias is contiguous 13827 if (!ggml_is_contiguous(scale)) { 13828 return false; 13829 } 13830 // unaligned bias isn't handled 13831 if (get_misalign_bytes(ctx, scale) != 0) { 13832 return false; 13833 } 13834 // shader only indexes by expert index 13835 if (scale->ne[0] != 1 || 13836 scale->ne[1] != mul->ne[1] || 13837 scale->ne[2] != 1 || 13838 scale->ne[3] != 1) { 13839 return false; 13840 } 13841 return true; 13842 }; 13843 13844 if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) { 13845 // additional constraints specific to this fusion 13846 const ggml_tensor *mul = cgraph->nodes[node_idx]; 13847 const ggml_tensor *add = cgraph->nodes[node_idx + 1]; 13848 const ggml_tensor *bias = add->src[1]; 13849 13850 if (mul != add->src[0]) { 13851 return false; 13852 } 13853 // mat-vec only 13854 if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) { 13855 return false; 13856 } 13857 // shaders assume the types match 13858 if (mul->type != bias->type) { 13859 return false; 13860 } 13861 // shaders assume the bias is contiguous 13862 if (!ggml_is_contiguous(bias)) { 13863 return false; 13864 } 13865 // the ID tensor must be the same for mul_mat_id and add_id 13866 if (mul->src[2] != add->src[2]) { 13867 return false; 13868 } 13869 // unaligned bias isn't handled 13870 if (get_misalign_bytes(ctx, bias) != 0) { 13871 return false; 13872 } 13873 13874 if (ops.size() == 3) { 13875 if (ops.begin()[2] != GGML_OP_MUL) { 13876 return false; 13877 } 13878 const ggml_tensor *mul = cgraph->nodes[node_idx + 2]; 13879 return mmid_mul_ok(add, mul); 13880 } 13881 } 13882 13883 if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) { 13884 // additional constraints specific to this fusion 13885 const ggml_tensor *mmid = cgraph->nodes[node_idx]; 13886 const ggml_tensor *mul = cgraph->nodes[node_idx + 1]; 13887 13888 if (!mmid_mul_ok(mmid, mul)) { 13889 return false; 13890 } 13891 } 13892 13893 return true; 13894 } 13895 13896 bool ggml_vk_can_fuse_ssm_conv(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, 13897 int node_idx, int num_extra) { 13898 const ggml_tensor * conv = cgraph->nodes[node_idx]; 13899 if (conv->op != GGML_OP_SSM_CONV) { 13900 return false; 13901 } 13902 13903 const ggml_tensor * silu = nullptr; 13904 const ggml_tensor * bias = nullptr; 13905 13906 if (num_extra == 1) { 13907 if (!ggml_can_fuse(cgraph, node_idx, { GGML_OP_SSM_CONV, GGML_OP_UNARY })) { 13908 return false; 13909 } 13910 silu = cgraph->nodes[node_idx + 1]; 13911 } else if (num_extra == 2) { 13912 if (!ggml_can_fuse(cgraph, node_idx, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY })) { 13913 return false; 13914 } 13915 const ggml_tensor * add = cgraph->nodes[node_idx + 1]; 13916 silu = cgraph->nodes[node_idx + 2]; 13917 bias = (add->src[0] == conv) ? add->src[1] : add->src[0]; 13918 13919 if (bias->type != GGML_TYPE_F32 || !ggml_is_contiguous(bias)) { 13920 return false; 13921 } 13922 // bias must be channel-wise (one element per channel of the conv output) 13923 if (ggml_nelements(bias) != conv->ne[0] || bias->ne[0] != conv->ne[0]) { 13924 return false; 13925 } 13926 if (add->type != GGML_TYPE_F32) { 13927 return false; 13928 } 13929 // The shader doesn't apply per-tensor offsets, so reject misaligned bias. 13930 if (get_misalign_bytes(ctx, bias) != 0) { 13931 return false; 13932 } 13933 } else { 13934 return false; 13935 } 13936 13937 if (ggml_get_unary_op(silu) != GGML_UNARY_OP_SILU) { 13938 return false; 13939 } 13940 if (conv->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) { 13941 return false; 13942 } 13943 // The shader writes to the fused dst using its own strides, but the push constants don't 13944 // carry a per-tensor offset, so the binding must be naturally aligned. 13945 if (get_misalign_bytes(ctx, silu) != 0) { 13946 return false; 13947 } 13948 return true; 13949 } 13950 13951 bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, 13952 int node_idx, topk_moe_mode mode) { 13953 13954 const ggml_tensor * softmax; 13955 const ggml_tensor * weights; 13956 const ggml_tensor * get_rows; 13957 const ggml_tensor * argsort; 13958 13959 switch (mode) { 13960 case TOPK_MOE_EARLY_SOFTMAX_NORM: 13961 softmax = cgraph->nodes[node_idx + 0]; 13962 weights = cgraph->nodes[node_idx + 9]; 13963 get_rows = cgraph->nodes[node_idx + 4]; 13964 argsort = cgraph->nodes[node_idx + 2]; 13965 break; 13966 case TOPK_MOE_SIGMOID_NORM_BIAS: 13967 softmax = cgraph->nodes[node_idx + 0]; // really sigmoid 13968 weights = cgraph->nodes[node_idx + 10]; 13969 get_rows = cgraph->nodes[node_idx + 5]; 13970 argsort = cgraph->nodes[node_idx + 3]; 13971 if (ggml_get_unary_op(softmax) != GGML_UNARY_OP_SIGMOID) { 13972 return false; 13973 } 13974 // bias is expected to be 1D 13975 if (ggml_nrows(cgraph->nodes[node_idx + 2]->src[1]) != 1 || 13976 !ggml_is_contiguous(cgraph->nodes[node_idx + 2]->src[1])) { 13977 return false; 13978 } 13979 // sigmoid fusion seems to generate infinities on moltenvk 13980 if (ctx->device->driver_id == vk::DriverId::eMoltenvk) { 13981 return false; 13982 } 13983 break; 13984 case TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS: 13985 softmax = cgraph->nodes[node_idx + 0]; // really softplus 13986 weights = cgraph->nodes[node_idx + 11]; 13987 get_rows = cgraph->nodes[node_idx + 6]; 13988 argsort = cgraph->nodes[node_idx + 4]; 13989 if (ggml_get_unary_op(softmax) != GGML_UNARY_OP_SOFTPLUS) { 13990 return false; 13991 } 13992 // bias is expected to be 1D 13993 if (ggml_nrows(cgraph->nodes[node_idx + 3]->src[1]) != 1 || 13994 !ggml_is_contiguous(cgraph->nodes[node_idx + 3]->src[1])) { 13995 return false; 13996 } 13997 break; 13998 case TOPK_MOE_EARLY_SOFTMAX: 13999 softmax = cgraph->nodes[node_idx + 0]; 14000 weights = cgraph->nodes[node_idx + 4]; 14001 get_rows = cgraph->nodes[node_idx + 4]; 14002 argsort = cgraph->nodes[node_idx + 2]; 14003 break; 14004 case TOPK_MOE_LATE_SOFTMAX: 14005 softmax = cgraph->nodes[node_idx + 4]; 14006 weights = cgraph->nodes[node_idx + 5]; 14007 get_rows = cgraph->nodes[node_idx + 2]; 14008 argsort = cgraph->nodes[node_idx + 0]; 14009 break; 14010 default: 14011 return false; 14012 } 14013 14014 ggml_tensor * probs = get_rows->src[0]; 14015 if (probs->op != GGML_OP_RESHAPE) { 14016 return false; 14017 } 14018 probs = probs->src[0]; 14019 ggml_tensor * selection_probs = argsort->src[0]; 14020 14021 if (probs != selection_probs && 14022 mode != TOPK_MOE_SIGMOID_NORM_BIAS && 14023 mode != TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS) { 14024 return false; 14025 } 14026 14027 if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) { 14028 return false; 14029 } 14030 14031 if (softmax->op == GGML_OP_SOFT_MAX) { 14032 const float * op_params = (const float *)softmax->op_params; 14033 14034 float scale = op_params[0]; 14035 float max_bias = op_params[1]; 14036 14037 if (scale != 1.0f || max_bias != 0.0f) { 14038 return false; 14039 } 14040 14041 // don't fuse when masks or sinks are present 14042 if (softmax->src[1] || softmax->src[2]) { 14043 return false; 14044 } 14045 } 14046 14047 const int n_expert = softmax->ne[0]; 14048 if (n_expert > (1 << (num_topk_moe_pipelines-1))) { 14049 return false; 14050 } 14051 14052 if (!ctx->device->subgroup_arithmetic || 14053 !ctx->device->subgroup_shuffle || 14054 !ctx->device->subgroup_require_full_support || 14055 ctx->device->disable_fusion) { 14056 return false; 14057 } 14058 14059 return true; 14060 } 14061 14062 static bool ggml_vk_match_ops(const struct ggml_cgraph * cgraph, int node_idx, 14063 const std::initializer_list & ops) { 14064 if (node_idx + (int) ops.size() > cgraph->n_nodes) { 14065 return false; 14066 } 14067 for (size_t j = 0; j < ops.size(); ++j) { 14068 const ggml_tensor * node = cgraph->nodes[node_idx + j]; 14069 if (node->op != ops.begin()[j] || 14070 (node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || 14071 (node->flags & GGML_TENSOR_FLAG_OUTPUT) != 0) { 14072 return false; 14073 } 14074 } 14075 return true; 14076 } 14077 14078 bool ggml_vk_can_fuse_topk_qsa(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { 14079 if (ctx->device->disable_fusion || !ctx->device->pipeline_topk_radix_qsa) { 14080 return false; 14081 } 14082 14083 const int n_ops = topk_qsa_pattern.size(); 14084 if (!ggml_vk_match_ops(cgraph, node_idx, topk_qsa_pattern) || 14085 !ggml_check_edges(cgraph, node_idx, topk_qsa_edges)) { 14086 return false; 14087 } 14088 14089 // elided nodes must be single-use (cpy counts its own src[1] self-reference) 14090 for (int j = 0; j < n_ops - 1; ++j) { 14091 const ggml_tensor * node = cgraph->nodes[node_idx + j]; 14092 const int32_t want = node->op == GGML_OP_CPY ? 2 : 1; 14093 if (ggml_node_get_use_count(cgraph, node_idx + j) != want) { 14094 return false; 14095 } 14096 } 14097 14098 const ggml_tensor * get_rows = cgraph->nodes[node_idx + 0]; 14099 const ggml_tensor * add = cgraph->nodes[node_idx + n_ops - 2]; 14100 const ggml_tensor * top_k = cgraph->nodes[node_idx + n_ops - 1]; 14101 14102 const ggml_tensor * scores = get_rows->src[0]; // [n_tps, n_blocks, n_stream] 14103 const ggml_tensor * cell_blk = get_rows->src[1]; // [n_kv, n_stream] 14104 const ggml_tensor * expanded = add->src[0]; // [n_kv, n_tps, n_stream] 14105 14106 // raw mask: follow the reshape/cpy chain back to the materialized f16 input 14107 const ggml_tensor * mask = add->src[1]; 14108 while (mask && (mask->op == GGML_OP_RESHAPE || mask->op == GGML_OP_CPY)) { 14109 mask = mask->src[0]; 14110 } 14111 if (!mask || mask->type != GGML_TYPE_F16) { 14112 return false; 14113 } 14114 14115 if (scores->type != GGML_TYPE_F32 || cell_blk->type != GGML_TYPE_I32 || top_k->type != GGML_TYPE_I32) { 14116 return false; 14117 } 14118 if (!ggml_is_contiguous(scores) || !ggml_is_contiguous(cell_blk) || !ggml_is_contiguous(mask) || 14119 !ggml_is_contiguous(expanded) || !ggml_is_contiguous(top_k)) { 14120 return false; 14121 } 14122 14123 const int64_t n_tps = scores->ne[0]; 14124 const int64_t n_blocks = scores->ne[1]; 14125 const int64_t n_stream = scores->ne[2]; 14126 const int64_t n_kv = cell_blk->ne[0]; 14127 const int64_t width = top_k->ne[0]; 14128 14129 // pin the indexer layout the shader's addressing assumes 14130 if (scores->ne[3] != 1 || cell_blk->ne[1] != n_stream || ggml_nrows(cell_blk) != n_stream || 14131 ggml_nelements(mask) != n_kv * n_tps * n_stream || 14132 expanded->ne[0] != n_kv || expanded->ne[1] != n_tps || expanded->ne[2] != n_stream || 14133 top_k->ne[1] != n_tps || top_k->ne[2] != n_stream || top_k->ne[3] != 1 || 14134 n_blocks <= 0 || n_kv <= 0 || width <= 0 || width > n_kv) { 14135 return false; 14136 } 14137 14138 // only worth it in the radix regime; small k uses the faster tournament unfused 14139 const uint32_t k_min_pipeline = std::max((uint32_t) log2f(float(width)) + 1, ctx->device->subgroup_size_log2); 14140 if (k_min_pipeline < num_topk_pipelines && ctx->device->pipeline_topk_f32[k_min_pipeline]) { 14141 return false; 14142 } 14143 return true; 14144 } 14145 14146 bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, 14147 int node_idx) { 14148 const ggml_tensor *rope = cgraph->nodes[node_idx + 0]; 14149 const ggml_tensor *view = cgraph->nodes[node_idx + 1]; 14150 const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2]; 14151 14152 // The set_rows epilogue uses one index per ne2 slice and does not encode ne3. 14153 if (rope->src[0]->ne[3] != 1) { 14154 return false; 14155 } 14156 14157 if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) { 14158 return false; 14159 } 14160 14161 // The shader reads each aligned I64 index as a uvec2 and uses its low 32 bits. 14162 if (set_rows->src[1]->type != GGML_TYPE_I64 || !ggml_is_contiguous(set_rows->src[1]) || 14163 set_rows->nb[0] != ggml_type_size(set_rows->type) || get_misalign_bytes(ctx, set_rows->src[1]) != 0) { 14164 return false; 14165 } 14166 14167 // SET_ROWS consumes one flattened [ne0*ne1] row for each ne2 slice. 14168 if (!ggml_is_contiguous(view) || 14169 view->ne[0] != rope->ne[0] * rope->ne[1] || view->ne[1] != rope->ne[2] || 14170 view->ne[2] != 1 || view->ne[3] != 1 || 14171 ggml_nelements(set_rows->src[1]) != rope->ne[2]) { 14172 return false; 14173 } 14174 14175 // Only norm/neox/mrope/imrope shaders have the fusion code 14176 const int mode = ((const int32_t *) rope->op_params)[2]; 14177 if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && 14178 mode != GGML_ROPE_TYPE_MROPE && mode != GGML_ROPE_TYPE_IMROPE) { 14179 return false; 14180 } 14181 14182 return true; 14183 } 14184 14185 bool ggml_vk_can_fuse_rms_norm_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, 14186 int node_idx) { 14187 const ggml_tensor * rms = cgraph->nodes[node_idx]; 14188 const ggml_tensor * view = cgraph->nodes[node_idx + 1]; 14189 const ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; 14190 14191 // The RMS kernel reads F32 and writes directly to the F32 or F16 SET_ROWS destination. 14192 if (rms->src[0]->type != GGML_TYPE_F32 || rms->type != GGML_TYPE_F32 || 14193 (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) || 14194 set_rows->src[1]->type != GGML_TYPE_I64 || !ggml_is_contiguous(set_rows->src[1]) || 14195 set_rows->nb[0] != ggml_type_size(set_rows->type) || get_misalign_bytes(ctx, set_rows->src[1]) != 0) { 14196 return false; 14197 } 14198 // As with the ROPE epilogue, each ne2 slice supplies one flattened row and ne3 is not encoded. 14199 if (rms->ne[3] != 1 || !ggml_is_contiguous(rms->src[0]) || !ggml_is_contiguous(view)) { 14200 return false; 14201 } 14202 if (view->ne[0] != rms->ne[0] * rms->ne[1] || view->ne[1] != rms->ne[2] || 14203 view->ne[2] != 1 || view->ne[3] != 1 || 14204 ggml_nelements(set_rows->src[1]) != rms->ne[2]) { 14205 return false; 14206 } 14207 14208 return true; 14209 } 14210 14211 bool ggml_vk_can_fuse_snake(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { 14212 GGML_UNUSED(ctx); 14213 if (!ggml_can_fuse(cgraph, node_idx, snake_pattern)) { 14214 return false; 14215 } 14216 14217 const ggml_tensor * mul0 = cgraph->nodes[node_idx + 0]; 14218 const ggml_tensor * sin_node = cgraph->nodes[node_idx + 1]; 14219 const ggml_tensor * sqr = cgraph->nodes[node_idx + 2]; 14220 const ggml_tensor * mul1 = cgraph->nodes[node_idx + 3]; 14221 const ggml_tensor * add = cgraph->nodes[node_idx + 4]; 14222 14223 const ggml_tensor * x = ggml_are_same_shape(mul0, mul0->src[0]) ? mul0->src[0] : mul0->src[1]; 14224 const ggml_tensor * a = (x == mul0->src[0]) ? mul0->src[1] : mul0->src[0]; 14225 14226 const ggml_tensor * inv_b = (mul1->src[0] == sqr) ? mul1->src[1] : mul1->src[0]; 14227 const ggml_tensor * x_in_add = (add->src[0] == mul1) ? add->src[1] : add->src[0]; 14228 14229 if (x_in_add != x) { 14230 return false; 14231 } 14232 if (x->type != GGML_TYPE_F32 && x->type != GGML_TYPE_F16 && x->type != GGML_TYPE_BF16) { 14233 return false; 14234 } 14235 // Shader bindings: data_a is A_TYPE so it follows x's precision, while 14236 // data_b and data_c are hardcoded float, so the broadcast operands must 14237 // be F32 regardless of x's type. 14238 if (a->type != GGML_TYPE_F32) return false; 14239 if (inv_b->type != GGML_TYPE_F32) return false; 14240 // Chain intermediates and output share x's precision (single A_TYPE / D_TYPE pipeline). 14241 if (mul0->type != x->type) return false; 14242 if (sin_node->type != x->type) return false; 14243 if (sqr->type != x->type) return false; 14244 if (mul1->type != x->type) return false; 14245 if (add->type != x->type) return false; 14246 if (!ggml_are_same_shape(a, inv_b)) { 14247 return false; 14248 } 14249 if (a->ne[0] != 1 || a->ne[1] != x->ne[1]) { 14250 return false; 14251 } 14252 // Dispatch is 2D over (ne0, ne1), so x and add must be 2D and a / inv_b 14253 // must collapse to [1, C, 1, 1]. Higher dims are not handled by the shader. 14254 if (x->ne[2] != 1 || x->ne[3] != 1) return false; 14255 if (add->ne[2] != 1 || add->ne[3] != 1) return false; 14256 if (a->ne[2] != 1 || a->ne[3] != 1) return false; 14257 if (inv_b->ne[2] != 1 || inv_b->ne[3] != 1) return false; 14258 // Shader uses idx = i0 + i1 * ne0 and reads data_b[i1] / data_c[i1], 14259 // so every operand must be contiguous. 14260 if (!ggml_is_contiguous(x) || !ggml_is_contiguous(add) || 14261 !ggml_is_contiguous(a) || !ggml_is_contiguous(inv_b)) { 14262 return false; 14263 } 14264 return true; 14265 } 14266 14267 bool ggml_vk_tensors_overlap(const ggml_tensor * a, const ggml_tensor * b, bool elementwise) { 14268 ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context; 14269 vk_buffer a_buf = a_buf_ctx->dev_buffer; 14270 ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context; 14271 vk_buffer b_buf = b_buf_ctx->dev_buffer; 14272 if (a_buf == b_buf) { 14273 auto a_base = vk_tensor_offset(a) + a->view_offs; 14274 auto a_size = ggml_nbytes(a); 14275 auto b_base = vk_tensor_offset(b) + b->view_offs; 14276 auto b_size = ggml_nbytes(b); 14277 14278 if (elementwise && a_base == b_base && a_size == b_size) { 14279 return false; 14280 } 14281 14282 if ((b_base <= a_base && a_base < b_base + b_size) || 14283 (a_base <= b_base && b_base < a_base + a_size)) { 14284 return true; 14285 } 14286 } 14287 return false; 14288 } 14289 14290 bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, 14291 int node_idx) { 14292 const ggml_tensor *rms = cgraph->nodes[node_idx + 0]; 14293 const ggml_tensor *mul = cgraph->nodes[node_idx + 1]; 14294 const ggml_tensor *rope = cgraph->nodes[node_idx + 2]; 14295 14296 const int mode = ((const int32_t *) rope->op_params)[2]; 14297 14298 // noncontig tensors aren't tested, and don't seem common in practice 14299 if (!ggml_is_contiguous(rms) || 14300 !ggml_is_contiguous(mul) || 14301 !ggml_is_contiguous(rope)) { 14302 return false; 14303 } 14304 14305 // only norm/neox are handled in the shader 14306 if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) { 14307 return false; 14308 } 14309 14310 // shared memory size for passing data from mul->rope 14311 if (mul->ne[0] > 1024) { 14312 return false; 14313 } 14314 14315 // conditions for pipeline creation 14316 if (sizeof(vk_op_rms_norm_mul_rope_push_constants) > ctx->device->properties.limits.maxPushConstantsSize) { 14317 return false; 14318 } 14319 14320 return true; 14321 } 14322 14323 uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) { 14324 14325 const ggml_tensor *first_node = cgraph->nodes[node_idx]; 14326 if (first_node->op != GGML_OP_ADD) { 14327 return 0; 14328 } 14329 14330 if (!ctx->device->multi_add) { 14331 return 0; 14332 } 14333 14334 int32_t num_adds = 1; 14335 while (node_idx + num_adds < cgraph->n_nodes && 14336 cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD && 14337 num_adds < MAX_FUSED_ADDS) { 14338 num_adds++; 14339 } 14340 14341 // The shader currently requires same shapes (but different strides are allowed), 14342 // everything f32, and no misalignment 14343 for (int32_t i = 0; i < num_adds; ++i) { 14344 const ggml_tensor *next_node = cgraph->nodes[node_idx + i]; 14345 if (!ggml_are_same_shape(first_node, next_node->src[0]) || 14346 !ggml_are_same_shape(first_node, next_node->src[1]) || 14347 next_node->type != GGML_TYPE_F32 || 14348 next_node->src[0]->type != GGML_TYPE_F32 || 14349 next_node->src[1]->type != GGML_TYPE_F32 || 14350 get_misalign_bytes(ctx, next_node) || 14351 get_misalign_bytes(ctx, next_node->src[0]) || 14352 get_misalign_bytes(ctx, next_node->src[1])) { 14353 num_adds = i; 14354 } 14355 } 14356 14357 // Verify we can fuse these 14358 ggml_op adds[MAX_FUSED_ADDS]; 14359 for (int32_t i = 0; i < num_adds; ++i) { 14360 adds[i] = GGML_OP_ADD; 14361 } 14362 14363 // decrease num_adds if they can't all be fused 14364 while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) { 14365 num_adds--; 14366 } 14367 14368 // a single add is not "fused", so just return zero 14369 if (num_adds == 1) { 14370 return 0; 14371 } 14372 return num_adds; 14373 } 14374 14375 static int32_t find_first_set(uint32_t x) { 14376 int32_t ret = 0; 14377 if (!x) { 14378 return -1; 14379 } 14380 while (!(x & 1)) { 14381 x >>= 1; 14382 ret++; 14383 } 14384 return ret; 14385 } 14386 14387 static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) { 14388 VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)"); 14389 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 14390 14391 ctx->device->diag_cgraph = nullptr; 14392 ctx->device->diag_prev_start = -1; 14393 ctx->device->diag_prev_end = -1; 14394 14395 if (vk_instance.debug_utils_support) { 14396 ctx->device->debug_cmdbuf_idx = 0; 14397 } 14398 14399 // queue scope, so it encloses every submit this evaluation makes. 14400 // closed when the function returns 14401 ggml_vk_debug_label queue_dbg(ctx->device->compute_queue->handle.get(), "ggml_backend_vk_graph_compute"); 14402 14403 ctx->prealloc_size_add_rms_partials_offset = 0; 14404 ctx->do_add_rms_partials = false; 14405 ctx->do_add_rms_partials_offset_calculation = false; 14406 14407 int last_node = cgraph->n_nodes - 1; 14408 14409 // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly 14410 while (last_node > 0 && (ggml_vk_is_empty(cgraph->nodes[last_node]) || ((cgraph->nodes[last_node]->flags & GGML_TENSOR_FLAG_COMPUTE) == 0))) { 14411 last_node -= 1; 14412 } 14413 14414 // Reserve tensor context space for all nodes 14415 ctx->tensor_ctxs.resize(cgraph->n_nodes); 14416 14417 bool first_node_in_batch = true; // true if next node will be first node in a batch 14418 int submit_node_idx = 0; // index to first node in a batch 14419 14420 ggml_vk_submit_transfer_ctx(ctx); 14421 14422 vk_context compute_ctx; 14423 if (vk_perf_logger_enabled) { 14424 // allocate/resize the query pool 14425 if (ctx->num_queries < cgraph->n_nodes + 1) { 14426 if (ctx->query_pool) { 14427 ctx->device->device.destroyQueryPool(ctx->query_pool); 14428 } 14429 vk::QueryPoolCreateInfo query_create_info; 14430 query_create_info.queryType = vk::QueryType::eTimestamp; 14431 query_create_info.queryCount = cgraph->n_nodes + 100; 14432 ctx->query_pool = ctx->device->device.createQueryPool(query_create_info); 14433 ctx->num_queries = query_create_info.queryCount; 14434 ctx->query_fusion_names.resize(ctx->num_queries); 14435 ctx->query_fusion_node_count.resize(ctx->num_queries); 14436 ctx->query_nodes.resize(ctx->num_queries); 14437 ctx->query_node_idx.resize(ctx->num_queries); 14438 } 14439 14440 ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1); 14441 std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr); 14442 std::fill(ctx->query_fusion_node_count.begin(), ctx->query_fusion_node_count.end(), 0); 14443 std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr); 14444 std::fill(ctx->query_node_idx.begin(), ctx->query_node_idx.end(), 0); 14445 14446 GGML_ASSERT(ctx->compute_ctx.expired()); 14447 compute_ctx = ggml_vk_get_compute_ctx(ctx); 14448 ctx->query_idx = 0; 14449 compute_ctx->s->buffer->buf.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++); 14450 ggml_vk_sync_buffers(ctx, compute_ctx); 14451 } 14452 14453 ctx->prealloc_y_last_pipeline_used = nullptr; 14454 ctx->prealloc_y_last_tensor_used = nullptr; 14455 ctx->prealloc_y_last_k_padded = false; 14456 14457 if (ctx->prealloc_size_add_rms_partials) { 14458 ggml_vk_preallocate_buffers(ctx, nullptr); 14459 compute_ctx = ggml_vk_get_compute_ctx(ctx); 14460 // initialize partial sums to zero. 14461 ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials); 14462 ggml_vk_sync_buffers(ctx, compute_ctx); 14463 } 14464 14465 // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution. 14466 // Estimate the amount of compute work using flops, and submit every 200 GFLOP 14467 // (and scaled down based on total graph flops, so smaller models submit earlier). 14468 // Also submit at least every 100 nodes, in case there are workloads without heavy compute. 14469 uint32_t submitted_nodes = 0; 14470 uint32_t submit_count = 0; 14471 uint64_t batch_flops = 0; 14472 uint64_t total_flops = 0; 14473 uint64_t flops_cap = 200'000'000'000ULL; 14474 14475 // On weaker AMD GPUs larger submissions can hit a driver timeout, submit more often to avoid this 14476 if (ctx->device->vendor_id == VK_VENDOR_ID_AMD && ctx->device->shader_core_count > 0) { 14477 if (ctx->device->architecture == AMD_GCN && ctx->device->shader_core_count < 32) { 14478 flops_cap = 500'000'000ULL * ctx->device->shader_core_count; 14479 } else if (ctx->device->architecture != AMD_GCN && ctx->device->shader_core_count < 24) { 14480 flops_cap = 2'000'000'000ULL * ctx->device->shader_core_count; 14481 } 14482 } 14483 // small graphs gain nothing from splitting, each submit costs CPU time 14484 uint64_t flops_per_submit = ctx->last_total_flops < 1'000'000'000ULL ? 0 : 14485 std::clamp(ctx->last_total_flops / 40u, std::min(100'000'000ULL, flops_cap), flops_cap); 14486 14487 auto const submit_after = [&](int start, int end) { 14488 if (ctx->device->serialize_submissions) { 14489 try { 14490 auto res = ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX); 14491 if (res != vk::Result::eSuccess) { 14492 GGML_LOG_ERROR("ggml_vulkan: waitForFences error during serialized submission\n"); 14493 throw vk::SystemError(vk::make_error_code(res), "ggml_vulkan: waitForFences during serialized submission"); 14494 } 14495 } catch (vk::DeviceLostError &) { 14496 ggml_vk_print_device_fault_info(ctx->device); 14497 GGML_LOG_ERROR("ggml_vulkan: device lost on %s waiting for submission (nodes %d to %d):\n", 14498 ctx->device->name.c_str(), start, end); 14499 ggml_vk_print_node_list(cgraph, start, end); 14500 throw; 14501 } 14502 ctx->device->device.resetFences({ ctx->fence }); 14503 ctx->submit_pending = false; 14504 ctx->device->diag_cgraph = cgraph; 14505 ctx->device->diag_prev_start = start; 14506 ctx->device->diag_prev_end = end; 14507 } 14508 first_node_in_batch = true; 14509 submitted_nodes = 0; 14510 batch_flops = 0; 14511 if (submit_count < 3) { 14512 flops_per_submit *= 2; 14513 } 14514 submit_count++; 14515 }; 14516 14517 for (int i = 0; i < cgraph->n_nodes; i++) { 14518 if (first_node_in_batch) { 14519 submit_node_idx = i; 14520 } 14521 14522 { 14523 auto node_flops = ggml_vk_get_node_flops(cgraph->nodes[i]); 14524 total_flops += node_flops; 14525 14526 // Flush the current batch before recording a node that would push it over the flop threshold 14527 if (flops_per_submit != 0 && submitted_nodes > 0 && batch_flops + node_flops >= flops_per_submit) { 14528 vk_context flush_ctx = ggml_vk_get_compute_ctx(ctx); 14529 ggml_vk_ctx_end(flush_ctx); 14530 flush_ctx->exit_tensor_idx = -1; 14531 ctx->compute_ctx.reset(); 14532 ggml_vk_compute_forward(ctx, cgraph, cgraph->nodes[submit_node_idx], submit_node_idx, false); 14533 submit_after(submit_node_idx, i - 1); 14534 submit_node_idx = i; 14535 } 14536 14537 batch_flops += node_flops; 14538 } 14539 14540 // op_srcs_fused_elementwise indicates whether an op's srcs all contribute to 14541 // the fused result in an elementwise-way. This affects whether the memory for 14542 // the src is allowed to overlap the memory for the destination. 14543 // The array is sized to handle the largest fusion (asserted later). 14544 bool op_srcs_fused_elementwise[13]; 14545 14546 ctx->fused_topk_moe_mode = TOPK_MOE_COUNT; 14547 ctx->fused_topk_moe_scale = false; 14548 ctx->fused_topk_qsa = false; 14549 ctx->fused_hc_post_gate = false; 14550 ctx->fused_rms_norm_mode = RMS_NORM_COUNT; 14551 const char *fusion_string {}; 14552 if (!ctx->device->disable_fusion) { 14553 uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i); 14554 if (num_adds) { 14555 ctx->num_additional_fused_ops = num_adds - 1; 14556 fusion_string = "MULTI_ADD"; 14557 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, true); 14558 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) { 14559 ctx->num_additional_fused_ops = 2; 14560 fusion_string = "MUL_MAT_ADD_ADD"; 14561 op_srcs_fused_elementwise[0] = false; 14562 op_srcs_fused_elementwise[1] = true; 14563 op_srcs_fused_elementwise[2] = true; 14564 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) { 14565 ctx->num_additional_fused_ops = 1; 14566 fusion_string = "MUL_MAT_ADD"; 14567 op_srcs_fused_elementwise[0] = false; 14568 op_srcs_fused_elementwise[1] = true; 14569 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) { 14570 ctx->num_additional_fused_ops = 2; 14571 fusion_string = "MUL_MAT_ID_ADD_ID_MUL"; 14572 op_srcs_fused_elementwise[0] = false; 14573 op_srcs_fused_elementwise[1] = true; 14574 op_srcs_fused_elementwise[2] = true; 14575 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) { 14576 ctx->num_additional_fused_ops = 1; 14577 fusion_string = "MUL_MAT_ID_ADD_ID"; 14578 op_srcs_fused_elementwise[0] = false; 14579 op_srcs_fused_elementwise[1] = true; 14580 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) { 14581 ctx->num_additional_fused_ops = 1; 14582 fusion_string = "MUL_MAT_ID_MUL"; 14583 op_srcs_fused_elementwise[0] = false; 14584 op_srcs_fused_elementwise[1] = true; 14585 } else if (ggml_can_fuse_subgraph(cgraph, i, rms_norm_mul_rope_view_set_rows_pattern, { i + 4 }) && 14586 ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) && 14587 ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) && 14588 ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) { 14589 ctx->num_additional_fused_ops = 4; 14590 ctx->fused_rms_norm_mode = RMS_NORM_MUL_ROPE_VIEW_SET_ROWS; 14591 fusion_string = "RMS_NORM_MUL_ROPE_VIEW_SET_ROWS"; 14592 op_srcs_fused_elementwise[0] = false; 14593 op_srcs_fused_elementwise[1] = false; 14594 op_srcs_fused_elementwise[2] = false; 14595 op_srcs_fused_elementwise[3] = false; 14596 op_srcs_fused_elementwise[4] = false; 14597 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE }) && 14598 ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) { 14599 ctx->num_additional_fused_ops = 2; 14600 ctx->fused_rms_norm_mode = RMS_NORM_MUL_ROPE; 14601 fusion_string = "RMS_NORM_MUL_ROPE"; 14602 // rope is approximately elementwise - whole rows are done by a single workgroup and it's row-wise 14603 op_srcs_fused_elementwise[0] = false; 14604 op_srcs_fused_elementwise[1] = true; 14605 op_srcs_fused_elementwise[2] = true; 14606 } else if (ggml_can_fuse_subgraph(cgraph, i, hc_post_gate_pattern, { i + 3 }) && 14607 ggml_check_edges(cgraph, i, hc_post_gate_edges) && 14608 ggml_vk_can_fuse_hc_post_gate(cgraph, i)) { 14609 ctx->num_additional_fused_ops = hc_post_gate_pattern.size() - 1; 14610 ctx->fused_hc_post_gate = true; 14611 fusion_string = "HC_POST_GATE"; 14612 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); 14613 } else if (ggml_vk_can_fuse(ctx, cgraph, i, rms_norm_mul_add_mul_pattern)) { 14614 ctx->num_additional_fused_ops = 3; 14615 ctx->fused_rms_norm_mode = RMS_NORM_MUL_ADD_MUL; 14616 fusion_string = "RMS_NORM_MUL_ADD_MUL"; 14617 std::fill_n(op_srcs_fused_elementwise, 4, true); 14618 } else if (ggml_vk_can_fuse(ctx, cgraph, i, rms_norm_mul_add_pattern)) { 14619 ctx->num_additional_fused_ops = 2; 14620 ctx->fused_rms_norm_mode = RMS_NORM_MUL_ADD; 14621 fusion_string = "RMS_NORM_MUL_ADD"; 14622 std::fill_n(op_srcs_fused_elementwise, 3, true); 14623 } else if (ggml_can_fuse_subgraph(cgraph, i, rms_norm_view_set_rows_pattern, { i + 2 }) && 14624 ggml_check_edges(cgraph, i, rms_norm_view_set_rows_edges) && 14625 ggml_vk_can_fuse_rms_norm_set_rows(ctx, cgraph, i)) { 14626 ctx->num_additional_fused_ops = 2; 14627 ctx->fused_rms_norm_mode = RMS_NORM_VIEW_SET_ROWS; 14628 fusion_string = "RMS_NORM_VIEW_SET_ROWS"; 14629 std::fill_n(op_srcs_fused_elementwise, 3, false); 14630 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) { 14631 ctx->num_additional_fused_ops = 1; 14632 ctx->fused_rms_norm_mode = RMS_NORM_MUL; 14633 fusion_string = "RMS_NORM_MUL"; 14634 // rms_norm is not elementwise, but whole rows must be consumed and the scale factor computed before 14635 // they are overwritten, and one workgroup per row. So close enough. 14636 op_srcs_fused_elementwise[0] = true; 14637 op_srcs_fused_elementwise[1] = true; 14638 } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL })) { 14639 ctx->num_additional_fused_ops = 1; 14640 switch (ggml_get_unary_op(cgraph->nodes[i])) { 14641 case GGML_UNARY_OP_GELU: fusion_string = "GELU_MUL"; break; 14642 case GGML_UNARY_OP_SIGMOID: fusion_string = "SIGMOID_MUL"; break; 14643 case GGML_UNARY_OP_SILU: fusion_string = "SILU_MUL"; break; 14644 default: fusion_string = "SOFTPLUS_MUL"; break; 14645 } 14646 op_srcs_fused_elementwise[0] = true; 14647 op_srcs_fused_elementwise[1] = true; 14648 } else if (ggml_vk_can_fuse_ssm_conv(ctx, cgraph, i, 2)) { 14649 ctx->num_additional_fused_ops = 2; 14650 fusion_string = "SSM_CONV_BIAS_SILU"; 14651 // ssm_conv reads multiple input tokens per output, so it's not elementwise w.r.t. its srcs. 14652 // The downstream add and silu are elementwise on the conv output. 14653 op_srcs_fused_elementwise[0] = false; 14654 op_srcs_fused_elementwise[1] = true; 14655 op_srcs_fused_elementwise[2] = true; 14656 } else if (ggml_vk_can_fuse_ssm_conv(ctx, cgraph, i, 1)) { 14657 ctx->num_additional_fused_ops = 1; 14658 fusion_string = "SSM_CONV_SILU"; 14659 op_srcs_fused_elementwise[0] = false; 14660 op_srcs_fused_elementwise[1] = true; 14661 } else if (ggml_can_fuse_subgraph(cgraph, i, rope_view_set_rows_pattern, { i + 2 }) && 14662 ggml_check_edges(cgraph, i, rope_view_set_rows_edges) && 14663 ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) { 14664 ctx->num_additional_fused_ops = 2; 14665 fusion_string = "ROPE_VIEW_SET_ROWS"; 14666 op_srcs_fused_elementwise[0] = false; 14667 op_srcs_fused_elementwise[1] = false; 14668 op_srcs_fused_elementwise[2] = false; 14669 } else if (ggml_vk_can_fuse_snake(ctx, cgraph, i)) { 14670 ctx->num_additional_fused_ops = 4; 14671 fusion_string = "SNAKE"; 14672 // elementwise=true: snake.comp is safe under exact aliasing because each 14673 // thread reads data_x[idx] into a register before writing data_d[idx] 14674 // with a data dependency on that register. The overlap check still 14675 // rejects partial overlaps (different base or size). 14676 std::fill_n(op_srcs_fused_elementwise, 5, true); 14677 } else if (ggml_vk_can_fuse_topk_qsa(ctx, cgraph, i)) { 14678 ctx->num_additional_fused_ops = topk_qsa_pattern.size() - 1; 14679 ctx->fused_topk_qsa = true; 14680 fusion_string = "TOPK_QSA"; 14681 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); 14682 } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) && 14683 ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) && 14684 ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) { 14685 ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1; 14686 // view of argsort writes to memory 14687 ctx->fused_ops_write_mask |= 1 << 3; 14688 ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX_NORM; 14689 fusion_string = "TOPK_MOE_EARLY_SOFTMAX_NORM"; 14690 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); 14691 } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_sigmoid_norm_bias, { i + 4, i + 10 }) && 14692 ggml_check_edges(cgraph, i, topk_moe_sigmoid_norm_bias_edges) && 14693 ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_SIGMOID_NORM_BIAS)) { 14694 ctx->num_additional_fused_ops = topk_moe_sigmoid_norm_bias.size() - 1; 14695 // view of argsort writes to memory 14696 ctx->fused_ops_write_mask |= 1 << 4; 14697 ctx->fused_topk_moe_mode = TOPK_MOE_SIGMOID_NORM_BIAS; 14698 fusion_string = "TOPK_MOE_SIGMOID_NORM_BIAS"; 14699 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); 14700 } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_sqrt_softplus_norm_bias, { i + 5, i + 11 }) && 14701 ggml_check_edges(cgraph, i, topk_moe_sqrt_softplus_norm_bias_edges) && 14702 ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS)) { 14703 ctx->num_additional_fused_ops = topk_moe_sqrt_softplus_norm_bias.size() - 1; 14704 // view of argsort writes to memory 14705 ctx->fused_ops_write_mask |= 1 << 5; 14706 ctx->fused_topk_moe_mode = TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS; 14707 fusion_string = "TOPK_MOE_SQRT_SOFTPLUS_NORM_BIAS"; 14708 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); 14709 } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) && 14710 ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) && 14711 ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) { 14712 ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1; 14713 // view of argsort writes to memory 14714 ctx->fused_ops_write_mask |= 1 << 3; 14715 ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX; 14716 fusion_string = "TOPK_MOE_EARLY_SOFTMAX"; 14717 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); 14718 } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) && 14719 ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) && 14720 ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) { 14721 ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1; 14722 // view of argsort writes to memory 14723 ctx->fused_ops_write_mask |= 1 << 1; 14724 ctx->fused_topk_moe_mode = TOPK_MOE_LATE_SOFTMAX; 14725 fusion_string = "TOPK_MOE_LATE_SOFTMAX"; 14726 std::fill_n(op_srcs_fused_elementwise, ctx->num_additional_fused_ops + 1, false); 14727 } 14728 if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) { 14729 // Look for an additional scale op to fuse - occurs in deepseek2 and nemotron3 nano. 14730 if (ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops - 1, { GGML_OP_DIV, GGML_OP_RESHAPE, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 }) || 14731 ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops, { GGML_OP_GET_ROWS, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 })) { 14732 ctx->fused_topk_moe_scale = true; 14733 ctx->num_additional_fused_ops++; 14734 op_srcs_fused_elementwise[ctx->num_additional_fused_ops] = false; 14735 } 14736 } 14737 } 14738 GGML_ASSERT(ctx->num_additional_fused_ops < (int)(sizeof(op_srcs_fused_elementwise) / sizeof(op_srcs_fused_elementwise[0]))); 14739 ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops; 14740 14741 // Check whether fusion would overwrite src operands while they're still in use. 14742 // If so, disable fusion. 14743 if (ctx->num_additional_fused_ops) { 14744 // There are up to two output nodes - topk_moe has two. 14745 uint32_t bits = ctx->fused_ops_write_mask & ~(1 << ctx->num_additional_fused_ops); 14746 ggml_tensor *output_nodes[2] {}; 14747 output_nodes[0] = cgraph->nodes[i + ctx->num_additional_fused_ops]; 14748 if (bits) { 14749 int output_idx = find_first_set(bits); 14750 GGML_ASSERT(bits == (1u << output_idx)); 14751 output_nodes[1] = cgraph->nodes[i + output_idx]; 14752 } 14753 14754 bool need_disable = false; 14755 14756 for (int j = 0; j < 2; ++j) { 14757 ggml_tensor *dst = output_nodes[j]; 14758 if (!dst) { 14759 continue; 14760 } 14761 // Loop over all srcs of all nodes in the fusion. If the src overlaps 14762 // the destination and the src is not an intermediate node that's being 14763 // elided, then disable fusion. 14764 for (int k = 0; k <= ctx->num_additional_fused_ops; ++k) { 14765 for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) { 14766 ggml_tensor *src = cgraph->nodes[i + k]->src[s]; 14767 if (!src || src->op == GGML_OP_NONE) { 14768 continue; 14769 } 14770 if (ggml_vk_tensors_overlap(src, dst, op_srcs_fused_elementwise[k])) { 14771 bool found = false; 14772 for (int n = 0; n < k; ++n) { 14773 if (cgraph->nodes[i + n] == src) { 14774 found = true; 14775 break; 14776 } 14777 } 14778 if (!found) { 14779 need_disable = true; 14780 } 14781 } 14782 } 14783 } 14784 } 14785 if (need_disable) { 14786 ctx->num_additional_fused_ops = 0; 14787 ctx->fused_ops_write_mask = 1; 14788 ctx->fused_topk_moe_mode = TOPK_MOE_COUNT; 14789 ctx->fused_topk_moe_scale = false; 14790 ctx->fused_topk_qsa = false; 14791 ctx->fused_hc_post_gate = false; 14792 ctx->fused_rms_norm_mode = RMS_NORM_COUNT; 14793 fusion_string = nullptr; 14794 } 14795 } 14796 14797 // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining) 14798 bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5; 14799 bool submit = (submitted_nodes >= ctx->device->max_nodes_per_submit) || 14800 (flops_per_submit != 0 && batch_flops >= flops_per_submit) || 14801 (i + ctx->num_additional_fused_ops >= last_node) || 14802 (almost_ready && !ctx->almost_ready_fence_pending); 14803 14804 bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit); 14805 14806 if (vk_perf_logger_enabled && enqueued) { 14807 compute_ctx = ggml_vk_get_compute_ctx(ctx); 14808 if (!vk_perf_logger_concurrent) { 14809 // track a single node/fusion for the current query 14810 ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i]; 14811 ctx->query_fusion_names[ctx->query_idx] = fusion_string; 14812 compute_ctx->s->buffer->buf.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++); 14813 ggml_vk_sync_buffers(ctx, compute_ctx); 14814 } else { 14815 // track a fusion string and number of fused ops for the current node_idx 14816 ctx->query_fusion_names[i] = fusion_string; 14817 ctx->query_fusion_node_count[i] = ctx->num_additional_fused_ops; 14818 } 14819 } 14820 14821 if (enqueued) { 14822 ++submitted_nodes; 14823 14824 #ifndef GGML_VULKAN_CHECK_RESULTS 14825 if (first_node_in_batch) { 14826 first_node_in_batch = false; 14827 } 14828 #endif 14829 } 14830 14831 if (submit && enqueued) { 14832 submit_after(submit_node_idx, i + (int)ctx->num_additional_fused_ops); 14833 } 14834 i += ctx->num_additional_fused_ops; 14835 ctx->num_additional_fused_ops = 0; 14836 ctx->fused_ops_write_mask = 0; 14837 } 14838 14839 ctx->last_total_flops = total_flops; 14840 14841 if (vk_perf_logger_enabled) { 14842 // End the command buffer and submit/wait 14843 GGML_ASSERT(!ctx->compute_ctx.expired()); 14844 compute_ctx = ctx->compute_ctx.lock(); 14845 ggml_vk_ctx_end(compute_ctx); 14846 14847 ggml_vk_submit(compute_ctx, ctx->device->fence); 14848 VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences", ctx->device); 14849 ctx->device->device.resetFences({ ctx->device->fence }); 14850 ctx->compute_ctx.reset(); 14851 14852 // Get the results and pass them to the logger 14853 std::vector timestamps(cgraph->n_nodes + 1); 14854 VK_CHECK(ctx->device->device.getQueryPoolResults(ctx->query_pool, 0, ctx->query_idx, (cgraph->n_nodes + 1)*sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait), "get timestamp results", ctx->device); 14855 if (!vk_perf_logger_concurrent) { 14856 // Log each op separately 14857 for (int i = 1; i < ctx->query_idx; i++) { 14858 auto node = ctx->query_nodes[i]; 14859 auto name = ctx->query_fusion_names[i]; 14860 ctx->perf_logger->log_timing(node, name, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod)); 14861 } 14862 } else { 14863 // Log each group of nodes 14864 int prev_node_idx = 0; 14865 for (int i = 1; i < ctx->query_idx; i++) { 14866 auto cur_node_idx = ctx->query_node_idx[i]; 14867 std::vector nodes; 14868 std::vector names; 14869 for (int node_idx = prev_node_idx; node_idx < cur_node_idx; ++node_idx) { 14870 if (ggml_op_is_empty(cgraph->nodes[node_idx]->op)) { 14871 continue; 14872 } 14873 nodes.push_back(cgraph->nodes[node_idx]); 14874 names.push_back(ctx->query_fusion_names[node_idx]); 14875 node_idx += ctx->query_fusion_node_count[node_idx]; 14876 } 14877 prev_node_idx = cur_node_idx; 14878 ctx->perf_logger->log_timing(nodes, names, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod)); 14879 } 14880 } 14881 ctx->perf_logger->print_timings(); 14882 } 14883 14884 if (!ctx->device->support_async) { 14885 ggml_vk_synchronize(ctx); 14886 } 14887 14888 return GGML_STATUS_SUCCESS; 14889 14890 UNUSED(backend); 14891 } 14892 14893 void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph, struct ggml_backend_graph_optimize_params * params) 14894 { 14895 VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)"); 14896 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 14897 14898 if (ctx->device->disable_graph_optimize) { 14899 return; 14900 } 14901 14902 auto const &is_empty = [](const ggml_tensor * node) -> bool { 14903 return node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE; 14904 }; 14905 14906 auto const &is_src_of = [&is_empty](const ggml_tensor *dst, const ggml_tensor *src) -> bool { 14907 auto const &base = [](const ggml_tensor * tensor) { 14908 return tensor->view_src ? tensor->view_src : tensor; 14909 }; 14910 for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) { 14911 if (dst->src[s] == src) { 14912 return true; 14913 } 14914 if (is_empty(dst) || is_empty(src)) { 14915 continue; 14916 } 14917 // A source view of dst may read storage written through a different view by src. 14918 if (dst->src[s] && base(dst->src[s]) == base(src)) { 14919 return true; 14920 } 14921 // Moving dst forward may overwrite storage still read through a view by src. 14922 if (src->src[s] && base(dst) == base(src->src[s])) { 14923 return true; 14924 } 14925 } 14926 // implicit dependency if they view the same tensor 14927 if (base(dst) == base(src)) { 14928 return true; 14929 } 14930 return false; 14931 }; 14932 14933 std::vector new_order; 14934 std::vector used(graph->n_nodes, false); 14935 std::set used_node_set; 14936 14937 int first_unused = 0; 14938 14939 // scheduled or zero-compute nodes in [lo, hi) 14940 auto const &empty_or_scheduled_between = [&](int lo, int hi) -> bool { 14941 for (int v = lo; v < hi; ++v) { 14942 if (!used[v] && !is_empty(graph->nodes[v])) { 14943 return false; 14944 } 14945 } 14946 return true; 14947 }; 14948 while (first_unused < graph->n_nodes) { 14949 std::vector current_set; 14950 14951 // Check for fusion patterns and avoid reordering them 14952 auto const &match_pattern = [&](const std::initializer_list &pattern, int start) -> bool { 14953 if (start + (int)pattern.size() <= graph->n_nodes) { 14954 bool is_pattern = true; 14955 for (size_t j = 0; j < pattern.size(); ++j) { 14956 if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) { 14957 is_pattern = false; 14958 } 14959 } 14960 return is_pattern; 14961 } 14962 return false; 14963 }; 14964 14965 auto const &keep_pattern = [&](const std::initializer_list &pattern) -> bool { 14966 if (match_pattern(pattern, first_unused)) { 14967 for (size_t j = 0; j < pattern.size(); ++j) { 14968 new_order.push_back(graph->nodes[first_unused + j]); 14969 used_node_set.insert(graph->nodes[first_unused + j]); 14970 used[first_unused + j] = true; 14971 } 14972 while (first_unused < graph->n_nodes && used[first_unused]) { 14973 first_unused++; 14974 } 14975 return true; 14976 } 14977 return false; 14978 }; 14979 14980 auto const &add_pattern_alloc_deps = [&](const std::initializer_list &pattern, int last_node) { 14981 // Keep external inputs alive through the fused output. 14982 std::set seen; 14983 for (size_t j = 0; j < pattern.size(); ++j) { 14984 ggml_tensor * node = graph->nodes[first_unused + j]; 14985 for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) { 14986 ggml_tensor * src = node->src[s]; 14987 if (src && seen.insert(src).second) { 14988 params->add_alloc_dep(params->user_data, src, graph->nodes[last_node]); 14989 } 14990 } 14991 seen.insert(node); 14992 } 14993 }; 14994 14995 auto const &keep_topk_moe_pattern = [&](const std::initializer_list &pattern) -> bool { 14996 if (!match_pattern(pattern, first_unused)) { 14997 return false; 14998 } 14999 15000 int last_node = first_unused + (int) pattern.size() - 1; 15001 // Some TOPK_MOE variants fuse a trailing scale. 15002 if (last_node + 1 < graph->n_nodes && graph->nodes[last_node + 1]->op == GGML_OP_SCALE) { 15003 last_node++; 15004 } 15005 15006 add_pattern_alloc_deps(pattern, last_node); 15007 15008 return keep_pattern(pattern); 15009 }; 15010 15011 if (keep_topk_moe_pattern(topk_moe_early_softmax_norm)) { 15012 continue; 15013 } 15014 if (keep_topk_moe_pattern(topk_moe_sigmoid_norm_bias)) { 15015 continue; 15016 } 15017 if (keep_topk_moe_pattern(topk_moe_sqrt_softplus_norm_bias)) { 15018 continue; 15019 } 15020 if (keep_topk_moe_pattern(topk_moe_early_softmax)) { 15021 continue; 15022 } 15023 if (keep_topk_moe_pattern(topk_moe_late_softmax)) { 15024 continue; 15025 } 15026 if (keep_pattern(snake_pattern)) { 15027 continue; 15028 } 15029 if (keep_pattern(topk_qsa_pattern)) { 15030 continue; 15031 } 15032 15033 if (keep_pattern(rms_norm_mul_add_mul_pattern)) { 15034 continue; 15035 } 15036 if (keep_pattern(rms_norm_mul_add_pattern)) { 15037 continue; 15038 } 15039 if (keep_pattern(rms_norm_mul_rope_view_set_rows_pattern)) { 15040 continue; 15041 } 15042 if (keep_pattern(rms_norm_view_set_rows_pattern)) { 15043 continue; 15044 } 15045 if (keep_pattern(rope_view_set_rows_pattern)) { 15046 continue; 15047 } 15048 if (match_pattern(hc_post_gate_pattern, first_unused)) { 15049 add_pattern_alloc_deps(hc_post_gate_pattern, first_unused + (int) hc_post_gate_pattern.size() - 1); 15050 keep_pattern(hc_post_gate_pattern); 15051 continue; 15052 } 15053 15054 // First, grab the next unused node. 15055 current_set.push_back(first_unused); 15056 15057 // Loop through the next N nodes. Grab any that don't depend on other nodes that 15058 // haven't already been run. Nodes that have already been run have used[i] set 15059 // to true. Allow nodes that depend on the previous node if it's a fusion pattern 15060 // that we support (e.g. RMS_NORM + MUL). 15061 // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes. 15062 // The goal is to not interleave real and view nodes in a way that breaks fusion. 15063 const int NUM_TO_CHECK = 20; 15064 for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) { 15065 if (used[j]) { 15066 continue; 15067 } 15068 if (is_empty(graph->nodes[j])) { 15069 continue; 15070 } 15071 // Protect every interior QSA node (not just the start): the mask branch is 15072 // independent, so it gets pulled out and breaks keep_pattern otherwise. 15073 auto const &in_qsa_pattern = [&](int n) -> bool { 15074 for (int o = 0; o < (int) topk_qsa_pattern.size(); ++o) { 15075 if (n - o >= 0 && match_pattern(topk_qsa_pattern, n - o)) { 15076 return true; 15077 } 15078 } 15079 return false; 15080 }; 15081 if (match_pattern(topk_moe_early_softmax_norm, j) || 15082 match_pattern(topk_moe_sigmoid_norm_bias, j) || 15083 match_pattern(topk_moe_sqrt_softplus_norm_bias, j) || 15084 match_pattern(topk_moe_early_softmax, j) || 15085 match_pattern(topk_moe_late_softmax, j) || 15086 match_pattern(snake_pattern, j) || 15087 in_qsa_pattern(j) || 15088 match_pattern(rms_norm_mul_add_mul_pattern, j) || 15089 match_pattern(rms_norm_mul_add_pattern, j) || 15090 match_pattern(rms_norm_mul_rope_view_set_rows_pattern, j) || 15091 match_pattern(rms_norm_view_set_rows_pattern, j) || 15092 match_pattern(rope_view_set_rows_pattern, j) || 15093 match_pattern(hc_post_gate_pattern, j)) { 15094 continue; 15095 } 15096 bool ok = true; 15097 for (int c = first_unused; c < j; ++c) { 15098 if (!used[c] && 15099 is_src_of(graph->nodes[j], graph->nodes[c]) && 15100 !(c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL && empty_or_scheduled_between(c+1, j)) && 15101 !(c == current_set.back() && graph->nodes[c]->op == GGML_OP_UNARY && graph->nodes[j]->op == GGML_OP_MUL && empty_or_scheduled_between(c+1, j)) && 15102 !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) && 15103 !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) && 15104 !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL) && 15105 !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_ADD && graph->nodes[j]->op == GGML_OP_ADD) && 15106 !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_SSM_CONV && graph->nodes[j]->op == GGML_OP_ADD) && 15107 !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_SSM_CONV && graph->nodes[j]->op == GGML_OP_UNARY)) { 15108 ok = false; 15109 break; 15110 } 15111 } 15112 if (ok) { 15113 current_set.push_back(j); 15114 15115 int rope_idx = j; 15116 15117 // When we've found RMS_NORM + MUL, try to find a ROPE that uses it 15118 if (j > 0 && 15119 graph->nodes[j]->op == GGML_OP_MUL && 15120 graph->nodes[j-1]->op == GGML_OP_RMS_NORM) { 15121 for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) { 15122 if (graph->nodes[k]->op == GGML_OP_ROPE && 15123 graph->nodes[k]->src[0] == graph->nodes[j] && 15124 // Check that other srcs are already valid 15125 graph->nodes[k]->src[1]->op == GGML_OP_NONE && 15126 (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) { 15127 rope_idx = k; 15128 current_set.push_back(rope_idx); 15129 used[rope_idx] = true; 15130 break; 15131 } 15132 } 15133 } 15134 // Look for ROPE/RMS_NORM + VIEW + SET_ROWS and make them consecutive 15135 if (graph->nodes[rope_idx]->op == GGML_OP_ROPE || graph->nodes[rope_idx]->op == GGML_OP_RMS_NORM) { 15136 int view_idx = -1; 15137 int set_rows_idx = -1; 15138 for (int k = rope_idx + 1; k < std::min(rope_idx + 15, graph->n_nodes); ++k) { 15139 if (used[k]) { 15140 continue; 15141 } 15142 if (view_idx == -1 && graph->nodes[k]->op == GGML_OP_VIEW && graph->nodes[k]->src[0] == graph->nodes[rope_idx]) { 15143 view_idx = k; 15144 continue; 15145 } 15146 if (view_idx != -1 && graph->nodes[k]->op == GGML_OP_SET_ROWS && graph->nodes[k]->src[0] == graph->nodes[view_idx]) { 15147 set_rows_idx = k; 15148 break; 15149 } 15150 } 15151 if (set_rows_idx != -1) { 15152 const int node_idxs[] = { rope_idx, view_idx, set_rows_idx }; 15153 const ggml_op ops[] = { graph->nodes[rope_idx]->op, GGML_OP_VIEW, GGML_OP_SET_ROWS }; 15154 bool can_pull = ggml_can_fuse_subgraph_ext(graph, node_idxs, 3, ops, &set_rows_idx, 1); 15155 15156 for (int c = rope_idx + 1; can_pull && c < set_rows_idx; ++c) { 15157 if (!used[c] && c != view_idx && !is_empty(graph->nodes[c]) && 15158 is_src_of(graph->nodes[set_rows_idx], graph->nodes[c])) { 15159 can_pull = false; 15160 } 15161 } 15162 15163 if (can_pull) { 15164 current_set.push_back(view_idx); 15165 current_set.push_back(set_rows_idx); 15166 used[view_idx] = true; 15167 used[set_rows_idx] = true; 15168 } 15169 } 15170 } 15171 // Look for MUL_MAT_ID + ADD_ID + MUL 15172 if (j > 0 && 15173 graph->nodes[j]->op == GGML_OP_ADD_ID && 15174 graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) { 15175 for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) { 15176 if (graph->nodes[k]->op == GGML_OP_MUL && 15177 graph->nodes[k]->src[0] == graph->nodes[j] && 15178 // src1 must either be weights or already processed 15179 (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) { 15180 current_set.push_back(k); 15181 used[k] = true; 15182 break; 15183 } 15184 } 15185 } 15186 // Look for MUL_MAT + ADD + ADD 15187 if (j > 0 && 15188 graph->nodes[j]->op == GGML_OP_ADD && 15189 graph->nodes[j-1]->op == GGML_OP_MUL_MAT) { 15190 for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) { 15191 if (graph->nodes[k]->op == GGML_OP_ADD && 15192 graph->nodes[k]->src[0] == graph->nodes[j] && 15193 // src1 must either be weights or already processed 15194 (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) { 15195 current_set.push_back(k); 15196 used[k] = true; 15197 break; 15198 } 15199 } 15200 } 15201 // SSM_CONV + ADD + UNARY: pull the consuming UNARY forward 15202 if (j > 0 && 15203 graph->nodes[j]->op == GGML_OP_ADD && 15204 graph->nodes[j-1]->op == GGML_OP_SSM_CONV) { 15205 for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) { 15206 if (graph->nodes[k]->op == GGML_OP_UNARY && 15207 graph->nodes[k]->src[0] == graph->nodes[j]) { 15208 current_set.push_back(k); 15209 used[k] = true; 15210 break; 15211 } 15212 } 15213 } 15214 // UNARY + MUL: pull the consuming MUL forward 15215 if (j > 0 && 15216 graph->nodes[j]->op == GGML_OP_UNARY) { 15217 for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) { 15218 ggml_tensor * mul = graph->nodes[k]; 15219 if (mul->op != GGML_OP_MUL || (mul->src[0] != graph->nodes[j] && mul->src[1] != graph->nodes[j])) { 15220 continue; 15221 } 15222 ggml_tensor * other = (mul->src[0] == graph->nodes[j]) ? mul->src[1] : mul->src[0]; 15223 // the other src must either be weights or already processed 15224 if (!(other->op == GGML_OP_NONE || used_node_set.find(other) != used_node_set.end())) { 15225 continue; 15226 } 15227 if (!ggml_vk_can_fuse_unary_mul(graph, j, k)) { 15228 continue; 15229 } 15230 current_set.push_back(k); 15231 used[k] = true; 15232 break; 15233 } 15234 } 15235 } 15236 } 15237 // Second pass grabs view nodes. 15238 // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add). 15239 if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) { 15240 for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) { 15241 if (used[j]) { 15242 continue; 15243 } 15244 if (!is_empty(graph->nodes[j])) { 15245 continue; 15246 } 15247 bool ok = true; 15248 for (int c = first_unused; c < j; ++c) { 15249 bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end(); 15250 // skip views whose srcs haven't been processed. 15251 if (!used[c] && 15252 is_src_of(graph->nodes[j], graph->nodes[c]) && 15253 !c_in_current_set) { 15254 ok = false; 15255 break; 15256 } 15257 } 15258 if (ok) { 15259 current_set.push_back(j); 15260 } 15261 } 15262 } 15263 15264 // Push the current set into new_order 15265 for (auto c : current_set) { 15266 new_order.push_back(graph->nodes[c]); 15267 used_node_set.insert(graph->nodes[c]); 15268 used[c] = true; 15269 } 15270 while (first_unused < graph->n_nodes && used[first_unused]) { 15271 first_unused++; 15272 } 15273 } 15274 // Replace the graph with the new order. 15275 for (int i = 0; i < graph->n_nodes; ++i) { 15276 graph->nodes[i] = new_order[i]; 15277 } 15278 } 15279 15280 static void ggml_backend_vk_event_record(ggml_backend_t backend, ggml_backend_event_t event) { 15281 VK_LOG_DEBUG("ggml_backend_vk_event_record(backend=" << backend << ", event=" << event << ")"); 15282 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 15283 vk_event *vkev = (vk_event *)event->context; 15284 15285 ggml_vk_submit_transfer_ctx(ctx); 15286 15287 vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); 15288 auto* cmd_buf = compute_ctx->s->buffer; // retrieve pointer before it gets reset 15289 15290 if (vkev->has_event) { 15291 // Move existing event into submitted 15292 vkev->events_submitted.push_back(vkev->event); 15293 } 15294 15295 // Grab the next event and record it, create one if necessary 15296 if (vkev->events_free.empty()) { 15297 vkev->event = ctx->device->device.createEvent({}); 15298 } else { 15299 vkev->event = vkev->events_free.back(); 15300 vkev->events_free.pop_back(); 15301 } 15302 15303 vkev->has_event = true; 15304 15305 ggml_vk_set_event(compute_ctx, vkev->event); 15306 15307 vkev->tl_semaphore.value++; 15308 compute_ctx->s->signal_semaphores.push_back(vkev->tl_semaphore); 15309 ggml_vk_ctx_end(compute_ctx); 15310 15311 ggml_vk_submit(compute_ctx, {}); 15312 ctx->submit_pending = true; 15313 vkev->cmd_buffer = cmd_buf; 15314 vkev->cmd_buffer_use_counter = cmd_buf->use_counter; 15315 ctx->compute_ctx.reset(); 15316 } 15317 15318 static void ggml_backend_vk_event_wait(ggml_backend_t backend, ggml_backend_event_t event) { 15319 VK_LOG_DEBUG("ggml_backend_vk_event_wait(backend=" << backend << ", event=" << event << ")"); 15320 ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context; 15321 vk_event *vkev = (vk_event *)event->context; 15322 15323 vk_context compute_ctx = ggml_vk_get_compute_ctx(ctx); 15324 15325 if (vkev->has_event) { 15326 // Wait for latest event 15327 ggml_vk_wait_events(compute_ctx, { vkev->event }); 15328 15329 if (ctx->device->async_use_transfer_queue) { 15330 vk_context transfer_ctx = ggml_vk_get_transfer_ctx(ctx); 15331 transfer_ctx->s->wait_semaphores.push_back(vkev->tl_semaphore); 15332 } 15333 } 15334 } 15335 15336 static ggml_backend_i ggml_backend_vk_interface = { 15337 /* .get_name = */ ggml_backend_vk_name, 15338 /* .free = */ ggml_backend_vk_free, 15339 /* .set_tensor_async = */ ggml_backend_vk_set_tensor_async, 15340 /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async, 15341 /* .set_tensor_2d_async = */ ggml_backend_vk_set_tensor_2d_async, 15342 /* .get_tensor_2d_async = */ ggml_backend_vk_get_tensor_2d_async, 15343 /* .cpy_tensor_async = */ ggml_backend_vk_cpy_tensor_async, 15344 /* .synchronize = */ ggml_backend_vk_synchronize, 15345 /* .graph_plan_create = */ NULL, 15346 /* .graph_plan_free = */ NULL, 15347 /* .graph_plan_update = */ NULL, 15348 /* .graph_plan_compute = */ NULL, 15349 /* .graph_compute = */ ggml_backend_vk_graph_compute, 15350 /* .event_record = */ ggml_backend_vk_event_record, 15351 /* .event_wait = */ ggml_backend_vk_event_wait, 15352 /* .graph_optimize = */ ggml_vk_graph_optimize, 15353 }; 15354 15355 static ggml_guid_t ggml_backend_vk_guid() { 15356 static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b }; 15357 return &guid; 15358 } 15359 15360 ggml_backend_t ggml_backend_vk_init(size_t dev_num) { 15361 VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")"); 15362 15363 ggml_backend_vk_context * ctx = new ggml_backend_vk_context; 15364 ggml_vk_init(ctx, dev_num); 15365 15366 ggml_backend_t vk_backend = new ggml_backend { 15367 /* .guid = */ ggml_backend_vk_guid(), 15368 /* .iface = */ ggml_backend_vk_interface, 15369 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num), 15370 /* .context = */ ctx, 15371 }; 15372 15373 if (!ctx->device->support_async) { 15374 vk_backend->iface.get_tensor_async = nullptr; 15375 } 15376 15377 return vk_backend; 15378 } 15379 15380 bool ggml_backend_is_vk(ggml_backend_t backend) { 15381 return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid()); 15382 } 15383 15384 int ggml_backend_vk_get_device_count() { 15385 return ggml_vk_get_device_count(); 15386 } 15387 15388 void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) { 15389 GGML_ASSERT(device < (int) vk_instance.device_indices.size()); 15390 int dev_idx = vk_instance.device_indices[device]; 15391 ggml_vk_get_device_description(dev_idx, description, description_size); 15392 } 15393 15394 void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) { 15395 GGML_ASSERT(device < (int) vk_instance.device_indices.size()); 15396 GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size()); 15397 15398 vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]]; 15399 vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops; 15400 vk::PhysicalDeviceMemoryProperties2 memprops = {}; 15401 const bool membudget_supported = vk_instance.device_supports_membudget[device]; 15402 const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu; 15403 15404 if (membudget_supported) { 15405 memprops.pNext = &budgetprops; 15406 } 15407 vkdev.getMemoryProperties2(&memprops); 15408 15409 *total = 0; 15410 *free = 0; 15411 15412 for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) { 15413 const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i]; 15414 15415 if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) { 15416 *total += heap.size; 15417 15418 if (membudget_supported && i < budgetprops.heapUsage.size()) { 15419 // Driver may report heapBudget > heap.size so we add a safeguard here 15420 // See https://github.com/ggml-org/llama.cpp/issues/29277 15421 const vk::DeviceSize budget = std::min(budgetprops.heapBudget[i], heap.size); 15422 *free += budget > budgetprops.heapUsage[i] ? budget - budgetprops.heapUsage[i] : 0; 15423 } else { 15424 *free += heap.size; 15425 } 15426 } 15427 } 15428 } 15429 15430 static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) { 15431 GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size()); 15432 15433 vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]]; 15434 15435 vk::PhysicalDeviceProperties2 props = {}; 15436 device.getProperties2(&props); 15437 15438 return props.properties.deviceType; 15439 } 15440 15441 static std::string ggml_backend_vk_get_device_pci_id(int device_idx) { 15442 GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size()); 15443 15444 vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]]; 15445 15446 const std::vector ext_props = device.enumerateDeviceExtensionProperties(); 15447 15448 bool ext_support = false; 15449 15450 for (const auto& properties : ext_props) { 15451 if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) { 15452 ext_support = true; 15453 break; 15454 } 15455 } 15456 15457 if (!ext_support) { 15458 return ""; 15459 } 15460 15461 vk::PhysicalDeviceProperties2 props = {}; 15462 vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {}; 15463 15464 props.pNext = &pci_bus_info; 15465 15466 device.getProperties2(&props); 15467 15468 const uint32_t pci_domain = pci_bus_info.pciDomain; 15469 const uint32_t pci_bus = pci_bus_info.pciBus; 15470 const uint32_t pci_device = pci_bus_info.pciDevice; 15471 const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning 15472 15473 char pci_bus_id[16] = {}; 15474 snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function); 15475 15476 return std::string(pci_bus_id); 15477 } 15478 15479 static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) { 15480 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 15481 return ctx->name.c_str(); 15482 } 15483 15484 static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) { 15485 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 15486 return ctx->description.c_str(); 15487 } 15488 15489 static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) { 15490 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context; 15491 ggml_backend_vk_get_device_memory(ctx->device, free, total); 15492 } 15493 15494 static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) { 15495 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 15496 return ggml_backend_vk_buffer_type(ctx->device); 15497 } 15498 15499 static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) { 15500 UNUSED(dev); 15501 return ggml_backend_vk_host_buffer_type(); 15502 } 15503 15504 static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) { 15505 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 15506 15507 return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU; 15508 } 15509 15510 static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) { 15511 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 15512 15513 props->name = ggml_backend_vk_device_get_name(dev); 15514 props->description = ggml_backend_vk_device_get_description(dev); 15515 props->type = ggml_backend_vk_device_get_type(dev); 15516 props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str(); 15517 ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total); 15518 props->caps = { 15519 /* .async = */ true, 15520 /* .host_buffer = */ true, 15521 /* .buffer_from_host_ptr = */ false, 15522 /* .events = */ true, 15523 /* .mmap_support = */ !ctx->is_integrated_gpu, 15524 }; 15525 } 15526 15527 static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) { 15528 UNUSED(params); 15529 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 15530 return ggml_backend_vk_init(ctx->device); 15531 } 15532 15533 static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { 15534 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 15535 const vk_device& device = ggml_vk_get_device(ctx->device); 15536 15537 const bool uses_bda = (op->op == GGML_OP_IM2COL || op->op == GGML_OP_IM2COL_3D) && 15538 device->shader_int64 && device->buffer_device_address; 15539 15540 auto const & tensor_size_supported = [&](size_t tensor_size) { 15541 if (tensor_size > device->max_buffer_size) { 15542 return false; 15543 } 15544 // For im2col shaders using BDA, maxStorageBufferRange limit doesn't apply. 15545 // If shader64BitIndexing is enabled, maxStorageBufferRange limit doesn't apply. 15546 if (!uses_bda && !device->shader_64b_indexing) { 15547 if (tensor_size > device->properties.limits.maxStorageBufferRange) { 15548 return false; 15549 } 15550 } 15551 return true; 15552 }; 15553 // non-compute ops are never executed here; their size is bounded by the buffer allocation limit 15554 const bool non_compute = ggml_op_is_empty(op->op); 15555 for (int i = 0; i < GGML_MAX_SRC; i++) { 15556 if (op->src[i] && !non_compute && !tensor_size_supported(ggml_nbytes(op->src[i]))) { 15557 return false; 15558 } 15559 } 15560 if (!non_compute && !tensor_size_supported(ggml_nbytes(op))) { 15561 return false; 15562 } 15563 15564 switch (op->op) { 15565 case GGML_OP_UNARY: 15566 switch (ggml_get_unary_op(op)) { 15567 case GGML_UNARY_OP_EXP: 15568 case GGML_UNARY_OP_EXPM1: 15569 case GGML_UNARY_OP_ELU: 15570 case GGML_UNARY_OP_GELU: 15571 case GGML_UNARY_OP_GELU_ERF: 15572 case GGML_UNARY_OP_GELU_QUICK: 15573 case GGML_UNARY_OP_SILU: 15574 case GGML_UNARY_OP_RELU: 15575 case GGML_UNARY_OP_XIELU: 15576 case GGML_UNARY_OP_NEG: 15577 case GGML_UNARY_OP_TANH: 15578 case GGML_UNARY_OP_SIGMOID: 15579 case GGML_UNARY_OP_HARDSIGMOID: 15580 case GGML_UNARY_OP_HARDSWISH: 15581 case GGML_UNARY_OP_ABS: 15582 case GGML_UNARY_OP_SOFTPLUS: 15583 case GGML_UNARY_OP_STEP: 15584 case GGML_UNARY_OP_ROUND: 15585 case GGML_UNARY_OP_CEIL: 15586 case GGML_UNARY_OP_FLOOR: 15587 case GGML_UNARY_OP_TRUNC: 15588 case GGML_UNARY_OP_SGN: 15589 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && 15590 (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && 15591 (op->src[0]->type == op->type); 15592 default: 15593 return false; 15594 } 15595 case GGML_OP_GLU: 15596 switch (ggml_get_glu_op(op)) { 15597 case GGML_GLU_OP_GEGLU: 15598 case GGML_GLU_OP_REGLU: 15599 case GGML_GLU_OP_SWIGLU: 15600 case GGML_GLU_OP_SWIGLU_OAI: 15601 case GGML_GLU_OP_GEGLU_ERF: 15602 case GGML_GLU_OP_GEGLU_QUICK: 15603 case GGML_GLU_OP_SWIGLU_CLAMP: 15604 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && 15605 (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && 15606 (op->src[0]->type == op->type) && 15607 (!op->src[1] || op->src[1]->type == op->src[0]->type); 15608 default: 15609 return false; 15610 } 15611 case GGML_OP_MUL_MAT: 15612 case GGML_OP_MUL_MAT_ID: 15613 { 15614 ggml_type src0_type = op->src[0]->type; 15615 if (op->op == GGML_OP_MUL_MAT_ID) { 15616 if (!ggml_vk_use_mul_mat_vec_id(op)) { 15617 const ggml_tensor * ids = op->src[2]; 15618 // Shaders store row IDs as uint16_t slot and token indices. 15619 if (ids->ne[0] > int64_t(UINT16_MAX) + 1 || ids->ne[1] > int64_t(UINT16_MAX) + 1) { 15620 return false; 15621 } 15622 } 15623 if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) { 15624 // If there's not enough shared memory for row_ids and the result tile, fallback to CPU 15625 return false; 15626 } 15627 } 15628 if (ggml_prec_get_src(op, 1) == GGML_PREC_F32) { 15629 return false; 15630 } 15631 switch (src0_type) { 15632 case GGML_TYPE_F32: 15633 case GGML_TYPE_F16: 15634 case GGML_TYPE_BF16: 15635 case GGML_TYPE_Q1_0: 15636 case GGML_TYPE_Q2_0: 15637 case GGML_TYPE_Q4_0: 15638 case GGML_TYPE_Q4_1: 15639 case GGML_TYPE_Q5_0: 15640 case GGML_TYPE_Q5_1: 15641 case GGML_TYPE_Q8_0: 15642 case GGML_TYPE_Q2_K: 15643 case GGML_TYPE_Q3_K: 15644 case GGML_TYPE_Q4_K: 15645 case GGML_TYPE_Q5_K: 15646 case GGML_TYPE_Q6_K: 15647 case GGML_TYPE_IQ1_S: 15648 case GGML_TYPE_IQ1_M: 15649 case GGML_TYPE_IQ2_XXS: 15650 case GGML_TYPE_IQ2_XS: 15651 case GGML_TYPE_IQ2_S: 15652 case GGML_TYPE_IQ3_XXS: 15653 case GGML_TYPE_IQ3_S: 15654 case GGML_TYPE_IQ4_XS: 15655 case GGML_TYPE_IQ4_NL: 15656 case GGML_TYPE_MXFP4: 15657 case GGML_TYPE_NVFP4: 15658 case GGML_TYPE_TQ1_0: 15659 case GGML_TYPE_TQ2_0: 15660 break; 15661 default: 15662 return false; 15663 } 15664 // MUL_MAT broadcasts src0 over dim 3 like dim 2, MUL_MAT_ID needs the ids to match src1 15665 if (op->op == GGML_OP_MUL_MAT_ID && op->src[2]->ne[3] != op->src[1]->ne[3]) { 15666 return false; 15667 } 15668 if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) || 15669 !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) { 15670 return false; 15671 } 15672 if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) { 15673 // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader. 15674 // So don't support this combination for now. 15675 return false; 15676 } 15677 if (op->src[1]->type == GGML_TYPE_BF16 && op->src[0]->type != GGML_TYPE_BF16 && op->op != GGML_OP_MUL_MAT) { 15678 // BF16 in src1 (widened to F32/F16) is only wired up for MUL_MAT 15679 return false; 15680 } 15681 15682 return true; 15683 } 15684 case GGML_OP_FLASH_ATTN_EXT: 15685 { 15686 // K/V row lists (ggml_flash_attn_ext_rows) are not supported 15687 if (op->src[5] != nullptr) { 15688 return false; 15689 } 15690 bool coopmat2 = device->coopmat2; 15691 uint32_t HSK = op->src[1]->ne[0]; 15692 uint32_t HSV = op->src[2]->ne[0]; 15693 if ((HSK % 8) != 0 || (HSV % 8) != 0) { 15694 return false; 15695 } 15696 if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) { 15697 return false; 15698 } 15699 if (op->src[0]->type != GGML_TYPE_F32) { 15700 return false; 15701 } 15702 if (op->type != GGML_TYPE_F32) { 15703 return false; 15704 } 15705 if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) { 15706 return false; 15707 } 15708 auto fa_kv_ok = [](ggml_type t) { 15709 switch (t) { 15710 case GGML_TYPE_F32: 15711 case GGML_TYPE_F16: 15712 case GGML_TYPE_BF16: 15713 case GGML_TYPE_Q8_0: 15714 case GGML_TYPE_Q5_1: 15715 case GGML_TYPE_Q5_0: 15716 case GGML_TYPE_Q4_1: 15717 case GGML_TYPE_Q4_0: 15718 case GGML_TYPE_IQ4_NL: 15719 return true; 15720 default: 15721 return false; 15722 } 15723 }; 15724 if (!fa_kv_ok(op->src[1]->type) || !fa_kv_ok(op->src[2]->type)) { 15725 return false; 15726 } 15727 if ((op->src[1]->type == GGML_TYPE_BF16) != (op->src[2]->type == GGML_TYPE_BF16)) { 15728 return false; 15729 } 15730 if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) { 15731 // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll 15732 return false; 15733 } 15734 return true; 15735 } 15736 case GGML_OP_GET_ROWS: 15737 { 15738 switch (op->src[0]->type) { 15739 case GGML_TYPE_F32: 15740 case GGML_TYPE_F16: 15741 case GGML_TYPE_BF16: 15742 case GGML_TYPE_Q1_0: 15743 case GGML_TYPE_Q2_0: 15744 case GGML_TYPE_Q4_0: 15745 case GGML_TYPE_Q4_1: 15746 case GGML_TYPE_Q5_0: 15747 case GGML_TYPE_Q5_1: 15748 case GGML_TYPE_Q8_0: 15749 case GGML_TYPE_Q2_K: 15750 case GGML_TYPE_Q3_K: 15751 case GGML_TYPE_Q4_K: 15752 case GGML_TYPE_Q5_K: 15753 case GGML_TYPE_Q6_K: 15754 case GGML_TYPE_IQ1_S: 15755 case GGML_TYPE_IQ1_M: 15756 case GGML_TYPE_IQ2_XXS: 15757 case GGML_TYPE_IQ2_XS: 15758 case GGML_TYPE_IQ2_S: 15759 case GGML_TYPE_IQ3_XXS: 15760 case GGML_TYPE_IQ3_S: 15761 case GGML_TYPE_IQ4_XS: 15762 case GGML_TYPE_IQ4_NL: 15763 case GGML_TYPE_MXFP4: 15764 case GGML_TYPE_NVFP4: 15765 case GGML_TYPE_TQ1_0: 15766 case GGML_TYPE_TQ2_0: 15767 case GGML_TYPE_I32: 15768 return true; 15769 default: 15770 return false; 15771 } 15772 } 15773 case GGML_OP_GET_ROWS_BACK: 15774 return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32; 15775 case GGML_OP_SET_ROWS: 15776 { 15777 if ((op->src[0]->type != GGML_TYPE_F32 && op->src[0]->type != GGML_TYPE_F16) || 15778 (op->src[1]->type != GGML_TYPE_I32 && op->src[1]->type != GGML_TYPE_I64)) { 15779 return false; 15780 } 15781 switch (op->type) { 15782 case GGML_TYPE_F32: 15783 case GGML_TYPE_F16: 15784 case GGML_TYPE_BF16: 15785 case GGML_TYPE_Q1_0: 15786 case GGML_TYPE_Q2_0: 15787 case GGML_TYPE_Q4_0: 15788 case GGML_TYPE_Q4_1: 15789 case GGML_TYPE_Q5_0: 15790 case GGML_TYPE_Q5_1: 15791 case GGML_TYPE_Q8_0: 15792 case GGML_TYPE_IQ4_NL: 15793 return true; 15794 default: 15795 return false; 15796 } 15797 } 15798 case GGML_OP_CONT: 15799 case GGML_OP_CPY: 15800 case GGML_OP_DUP: 15801 { 15802 ggml_type src0_type = op->src[0]->type; 15803 ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type; 15804 15805 if (src0_type == GGML_TYPE_F32) { 15806 switch (src1_type) { 15807 case GGML_TYPE_F32: 15808 case GGML_TYPE_F16: 15809 case GGML_TYPE_BF16: 15810 case GGML_TYPE_Q1_0: 15811 case GGML_TYPE_Q2_0: 15812 case GGML_TYPE_Q4_0: 15813 case GGML_TYPE_Q4_1: 15814 case GGML_TYPE_Q5_0: 15815 case GGML_TYPE_Q5_1: 15816 case GGML_TYPE_Q8_0: 15817 case GGML_TYPE_IQ4_NL: 15818 return true; 15819 default: 15820 break; 15821 } 15822 } 15823 if (src1_type == GGML_TYPE_F32) { 15824 switch (src0_type) { 15825 case GGML_TYPE_F16: 15826 case GGML_TYPE_BF16: 15827 case GGML_TYPE_Q1_0: 15828 case GGML_TYPE_Q2_0: 15829 case GGML_TYPE_Q4_0: 15830 case GGML_TYPE_Q4_1: 15831 case GGML_TYPE_Q5_0: 15832 case GGML_TYPE_Q5_1: 15833 case GGML_TYPE_Q8_0: 15834 case GGML_TYPE_IQ4_NL: 15835 return true; 15836 default: 15837 break; 15838 } 15839 } 15840 15841 if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) { 15842 return true; 15843 } 15844 15845 if ( 15846 (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) || 15847 (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32) 15848 ) { 15849 return true; 15850 } 15851 15852 // We can handle copying from a type to the same type if it's 15853 // either not quantized or is quantized and contiguous. 15854 // We use f16 or f32 shaders to do the copy, 15855 // so the type/block size must be a multiple of 4. 15856 if (src0_type == src1_type && 15857 (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) && 15858 (ggml_type_size(src0_type) % 2) == 0) { 15859 return true; 15860 } 15861 return false; 15862 } 15863 case GGML_OP_REPEAT: 15864 return ggml_type_size(op->type) == ggml_type_size(op->src[0]->type) && 15865 (ggml_type_size(op->type) == sizeof(float) || ggml_type_size(op->type) == 2); 15866 case GGML_OP_REPEAT_BACK: 15867 return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32; 15868 case GGML_OP_ROPE: 15869 return ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0]); 15870 case GGML_OP_ROPE_BACK: 15871 case GGML_OP_NONE: 15872 case GGML_OP_RESHAPE: 15873 case GGML_OP_VIEW: 15874 case GGML_OP_PERMUTE: 15875 case GGML_OP_TRANSPOSE: 15876 case GGML_OP_RMS_NORM: 15877 return true; 15878 case GGML_OP_GROUP_NORM: 15879 return ggml_is_contiguous(op->src[0]); 15880 case GGML_OP_NORM: 15881 case GGML_OP_L2_NORM: 15882 return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; 15883 case GGML_OP_ADD: 15884 case GGML_OP_SUB: 15885 case GGML_OP_MUL: 15886 case GGML_OP_DIV: 15887 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && 15888 (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && 15889 (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); 15890 case GGML_OP_ADD_ID: 15891 return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 && 15892 op->type == GGML_TYPE_F32; 15893 case GGML_OP_SILU_BACK: 15894 case GGML_OP_RMS_NORM_BACK: 15895 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 15896 case GGML_OP_SQR: 15897 case GGML_OP_SQRT: 15898 case GGML_OP_SIN: 15899 case GGML_OP_COS: 15900 case GGML_OP_CLAMP: 15901 case GGML_OP_LEAKY_RELU: 15902 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && 15903 op->type == op->src[0]->type; 15904 case GGML_OP_OPT_STEP_ADAMW: 15905 case GGML_OP_OPT_STEP_SGD: 15906 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 15907 case GGML_OP_OUT_PROD: 15908 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 15909 && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 15910 && op->type == GGML_TYPE_F32; 15911 case GGML_OP_LOG: 15912 case GGML_OP_TRI: 15913 case GGML_OP_DIAG: 15914 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && 15915 op->type == op->src[0]->type; 15916 case GGML_OP_ARGSORT: 15917 { 15918 if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) { 15919 return false; 15920 } 15921 // pipeline_argsort_large_f32 requires vulkan memory model. 15922 if (device->vulkan_memory_model) { 15923 return true; 15924 } else { 15925 return op->ne[0] <= (1 << std::min(device->max_workgroup_size_log2, num_argsort_pipelines - 1)); 15926 } 15927 } 15928 case GGML_OP_TOP_K: 15929 { 15930 if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) { 15931 return false; 15932 } 15933 // large k falls back to radix-select 15934 const uint32_t min_pipeline = 15935 std::max((uint32_t) log2f(float(op->ne[0])) + 1, device->subgroup_size_log2); 15936 if (min_pipeline < num_topk_pipelines && device->pipeline_topk_f32[min_pipeline]) { 15937 return true; 15938 } 15939 return device->pipeline_topk_radix_f32 != nullptr; 15940 } 15941 case GGML_OP_UPSCALE: 15942 if (op->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS) { 15943 if ((op->op_params[0] & 0xFF) != GGML_SCALE_MODE_BILINEAR) { 15944 return false; 15945 } 15946 } 15947 return op->src[0]->type == GGML_TYPE_F32; 15948 case GGML_OP_ACC: 15949 return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; 15950 case GGML_OP_SET: 15951 return op->src[0]->type == op->src[1]->type && op->src[0]->type == op->type && 15952 (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_I32); 15953 case GGML_OP_CONCAT: { 15954 return ggml_vk_concat_supported(op->src[0], op->src[1], op); 15955 } 15956 case GGML_OP_ADD1: 15957 return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32) 15958 || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32) 15959 || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16); 15960 case GGML_OP_ARANGE: 15961 return op->type == GGML_TYPE_F32; 15962 case GGML_OP_FILL: 15963 return op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16; 15964 case GGML_OP_SCALE: 15965 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 15966 case GGML_OP_PAD: 15967 case GGML_OP_PAD_REFLECT_1D: 15968 case GGML_OP_ROLL: 15969 return op->src[0]->type == GGML_TYPE_F32; 15970 case GGML_OP_DIAG_MASK_INF: 15971 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 15972 case GGML_OP_SOFT_MAX: 15973 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 15974 && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)); 15975 case GGML_OP_SOFT_MAX_BACK: 15976 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 15977 && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32; 15978 case GGML_OP_SUM: 15979 return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguously_allocated(op->src[0]); 15980 case GGML_OP_SUM_ROWS: 15981 case GGML_OP_MEAN: 15982 return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]); 15983 case GGML_OP_CUMSUM: 15984 { 15985 if (device->subgroup_arithmetic && device->subgroup_require_full_support) { 15986 return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]); 15987 } 15988 return false; 15989 } 15990 case GGML_OP_DSV4_HC_COMB: 15991 case GGML_OP_DSV4_HC_PRE: 15992 case GGML_OP_DSV4_HC_POST: 15993 { 15994 if (op->type != GGML_TYPE_F32) { 15995 return false; 15996 } 15997 for (uint32_t i = 0; i < GGML_MAX_SRC; ++i) { 15998 if (op->src[i] && op->src[i]->type != GGML_TYPE_F32) { 15999 return false; 16000 } 16001 } 16002 // hc is hardcoded to 4 in the shaders. ggml only constrains it 16003 // to 4 for COMB, so PRE/POST have to be checked here. 16004 if (op->op == GGML_OP_DSV4_HC_PRE && op->src[0]->ne[1] != 4) { 16005 return false; 16006 } 16007 if (op->op == GGML_OP_DSV4_HC_POST && op->src[1]->ne[1] != 4) { 16008 return false; 16009 } 16010 if (op->op == GGML_OP_DSV4_HC_COMB) { 16011 return device->pipeline_dsv4_hc_comb_f32 != nullptr; 16012 } 16013 return true; 16014 } 16015 case GGML_OP_SOLVE_TRI: 16016 { 16017 if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32) { 16018 return false; 16019 } 16020 const uint32_t N = op->src[0]->ne[0]; 16021 const uint32_t K = op->src[1]->ne[0]; 16022 // K dimension limited to workgroup size 16023 if (K > 1u << device->max_workgroup_size_log2) { 16024 return false; 16025 } 16026 const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((N + K) * sizeof(float)); 16027 16028 if (batch_N == 0) { 16029 return false; 16030 } 16031 return true; 16032 } 16033 case GGML_OP_ARGMAX: 16034 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 16035 case GGML_OP_CROSS_ENTROPY_LOSS: 16036 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 16037 && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 16038 && ggml_are_same_shape(op->src[0], op->src[1]) 16039 && ggml_is_contiguous(op) && ggml_is_scalar(op) && op->type == GGML_TYPE_F32; 16040 case GGML_OP_CROSS_ENTROPY_LOSS_BACK: 16041 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 && ggml_is_scalar(op->src[0]) 16042 && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 16043 && ggml_is_contiguous(op->src[2]) && op->src[2]->type == GGML_TYPE_F32 16044 && ggml_are_same_shape(op->src[1], op->src[2]) 16045 && ggml_are_same_shape(op->src[1], op) 16046 && ggml_is_contiguous(op) && op->type == GGML_TYPE_F32; 16047 case GGML_OP_COUNT_EQUAL: 16048 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_I32 16049 && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_I32; 16050 case GGML_OP_IM2COL: 16051 return ggml_is_contiguous(op->src[1]) 16052 && op->src[1]->type == GGML_TYPE_F32 16053 && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); 16054 case GGML_OP_IM2COL_3D: 16055 return op->src[1]->type == GGML_TYPE_F32 16056 && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); 16057 case GGML_OP_TIMESTEP_EMBEDDING: 16058 return op->src[0]->type == GGML_TYPE_F32; 16059 case GGML_OP_CONV_2D_DW: 16060 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) 16061 && op->src[1]->type == GGML_TYPE_F32; 16062 case GGML_OP_POOL_1D: 16063 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 16064 case GGML_OP_POOL_2D: 16065 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 16066 case GGML_OP_RWKV_WKV6: 16067 case GGML_OP_RWKV_WKV7: 16068 return true; // all inputs are contiguous, see ggml.c 16069 case GGML_OP_GATED_LINEAR_ATTN: 16070 // the shader block size is hardcoded to head_size 64 16071 return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && op->src[0]->ne[0] == 64; 16072 case GGML_OP_LIGHTNING_INDEXER: 16073 { 16074 const ggml_tensor * q = op->src[0]; 16075 const ggml_tensor * k = op->src[1]; 16076 const ggml_tensor * w = op->src[2]; 16077 const ggml_tensor * m = op->src[3]; 16078 16079 // the q/w/m types and the shape relationships between q, k, w, m and dst 16080 // are already asserted in ggml_lightning_indexer() 16081 if (!ggml_vk_lightning_indexer_k_type_supported(k->type) || !device->fp16) { 16082 return false; 16083 } 16084 16085 // the shader block size is hardcoded to head size 128 16086 if (q->ne[0] != 128) { 16087 return false; 16088 } 16089 16090 // the shader indexes the buffers by element stride, and is dispatched 16091 // without allow_misalign 16092 for (const ggml_tensor * t : {q, k, w, m, op}) { 16093 if (t->nb[0] != ggml_type_size(t->type) || 16094 (vk_tensor_offset(t) + t->view_offs) % device->properties.limits.minStorageBufferOffsetAlignment != 0) { 16095 return false; 16096 } 16097 // the strides get scaled down from bytes, so the division must be exact 16098 for (int i = 1; i < GGML_MAX_DIMS; ++i) { 16099 if (t->nb[i] % ggml_type_size(t->type) != 0) { 16100 return false; 16101 } 16102 } 16103 } 16104 return true; 16105 } 16106 case GGML_OP_GATED_DELTA_NET: 16107 { 16108 const uint32_t S_v = op->src[2]->ne[0]; 16109 if (S_v != 16 && S_v != 32 && S_v != 64 && S_v != 128) { 16110 return false; 16111 } 16112 for (int i = 0; i < 6; i++) { 16113 if (op->src[i] == nullptr || op->src[i]->type != GGML_TYPE_F32) { 16114 return false; 16115 } 16116 } 16117 return op->type == GGML_TYPE_F32; 16118 } 16119 case GGML_OP_SSM_SCAN: 16120 { 16121 for (int i = 0; i < 6; i++) { 16122 if (op->src[i] && ggml_is_quantized(op->src[i]->type)) { 16123 return false; 16124 } 16125 } 16126 if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) { 16127 return false; 16128 } 16129 if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) { 16130 return false; 16131 } 16132 16133 const uint32_t d_state = op->src[0]->ne[0]; 16134 const uint32_t head_dim = op->src[0]->ne[1]; 16135 16136 bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float)); 16137 if (!is_mamba2) { 16138 return false; 16139 } 16140 16141 if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) { 16142 return false; 16143 } 16144 16145 size_t shmem_size = d_state * sizeof(float); 16146 16147 if (shmem_size > device->properties.limits.maxComputeSharedMemorySize) { 16148 return false; 16149 } 16150 16151 if (!device->subgroup_basic) { 16152 return false; 16153 } 16154 16155 return true; 16156 } 16157 case GGML_OP_SSM_CONV: 16158 return op->src[0]->type == GGML_TYPE_F32; 16159 case GGML_OP_CONV_TRANSPOSE_1D: 16160 return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32; 16161 case GGML_OP_COL2IM_1D: 16162 return (op->src[0]->type == GGML_TYPE_F32 || 16163 op->src[0]->type == GGML_TYPE_F16 || 16164 op->src[0]->type == GGML_TYPE_BF16) && 16165 op->type == op->src[0]->type && 16166 ggml_is_contiguous(op->src[0]) && 16167 ggml_is_contiguous(op); 16168 case GGML_OP_CONV_2D: 16169 case GGML_OP_CONV_TRANSPOSE_2D: 16170 { 16171 const bool transpose = op->op == GGML_OP_CONV_TRANSPOSE_2D; 16172 const int64_t cout = !transpose ? op->src[0]->ne[3] : op->src[0]->ne[2]; 16173 const int64_t cin = !transpose ? op->src[0]->ne[2] : op->src[0]->ne[3]; 16174 16175 // Channel-contiguous format is not supported yet. 16176 return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && 16177 (op->src[0]->nb[0] == sizeof(float) || op->src[0]->nb[0] == sizeof(ggml_fp16_t) ) && 16178 op->src[1]->type == GGML_TYPE_F32 && 16179 op->type == GGML_TYPE_F32 && 16180 cout == op->ne[2] && 16181 cin == op->src[1]->ne[2] && 16182 ggml_is_contiguous(op->src[0]) && 16183 ggml_is_contiguous(op->src[1]) && 16184 ggml_is_contiguous(op)); 16185 } 16186 case GGML_OP_CONV_3D: 16187 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && 16188 op->src[1]->type == GGML_TYPE_F32 && 16189 op->type == GGML_TYPE_F32 && 16190 ggml_is_contiguous(op->src[0]) && 16191 ggml_is_contiguous(op->src[1]) && 16192 ggml_is_contiguous(op); 16193 default: 16194 return false; 16195 } 16196 16197 UNUSED(dev); 16198 } 16199 16200 static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) { 16201 if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) { 16202 return false; 16203 } 16204 16205 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 16206 ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context; 16207 16208 return buft_ctx->device->idx == ctx->device; 16209 } 16210 16211 static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) { 16212 ggml_backend_vk_device_context * dev_ctx = (ggml_backend_vk_device_context *)dev->context; 16213 16214 return ggml_vk_get_op_batch_size(op) >= dev_ctx->op_offload_min_batch_size; 16215 } 16216 16217 static ggml_backend_event_t ggml_backend_vk_device_event_new(ggml_backend_dev_t dev) { 16218 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 16219 auto device = ggml_vk_get_device(ctx->device); 16220 16221 vk_event *vkev = new vk_event; 16222 if (!vkev) { 16223 return nullptr; 16224 } 16225 16226 // No events initially, they get created on demand 16227 vkev->has_event = false; 16228 16229 vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 }; 16230 vk::SemaphoreCreateInfo ci{}; 16231 ci.setPNext(&tci); 16232 vkev->tl_semaphore = { device->device.createSemaphore(ci), 0 }; 16233 16234 return new ggml_backend_event { 16235 /* .device = */ dev, 16236 /* .context = */ vkev, 16237 }; 16238 } 16239 16240 static void ggml_backend_vk_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) { 16241 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 16242 auto device = ggml_vk_get_device(ctx->device); 16243 16244 vk_event *vkev = (vk_event *)event->context; 16245 16246 device->device.destroySemaphore(vkev->tl_semaphore.s); 16247 for (auto& event : vkev->events_free) { 16248 device->device.destroyEvent(event); 16249 } 16250 for (auto& event : vkev->events_submitted) { 16251 device->device.destroyEvent(event); 16252 } 16253 if (vkev->has_event) { 16254 device->device.destroyEvent(vkev->event); 16255 } 16256 delete vkev; 16257 delete event; 16258 } 16259 16260 static void ggml_backend_vk_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) { 16261 VK_LOG_DEBUG("ggml_backend_vk_device_event_synchronize(backend=" << dev << ", event=" << event << ")"); 16262 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 16263 auto device = ggml_vk_get_device(ctx->device); 16264 vk_event *vkev = (vk_event *)event->context; 16265 16266 // Only do something if the event has actually been used 16267 if (vkev->has_event) { 16268 vk::Semaphore sem = vkev->tl_semaphore.s; 16269 uint64_t val = vkev->tl_semaphore.value; 16270 vk::SemaphoreWaitInfo swi{vk::SemaphoreWaitFlags{}, sem, val}; 16271 VK_CHECK(device->device.waitSemaphores(swi, UINT64_MAX), "event_synchronize", device); 16272 16273 // Reset and move submitted events 16274 for (auto& event : vkev->events_submitted) { 16275 device->device.resetEvent(event); 16276 } 16277 vkev->events_free.insert(vkev->events_free.end(), vkev->events_submitted.begin(), vkev->events_submitted.end()); 16278 vkev->events_submitted.clear(); 16279 16280 // Finished using current command buffer so we flag for reuse 16281 if (vkev->cmd_buffer) { 16282 // Only flag for reuse if it hasn't been reused already 16283 if (vkev->cmd_buffer_use_counter == vkev->cmd_buffer->use_counter) { 16284 vkev->cmd_buffer->in_use = false; 16285 vkev->cmd_buffer->buf.reset(); 16286 } 16287 vkev->cmd_buffer = nullptr; 16288 } 16289 } 16290 } 16291 16292 ggml_backend_buffer_t ggml_backend_vk_device_buffer_from_host_ptr(ggml_backend_dev_t dev, void * ptr, size_t size, size_t max_tensor_size) { 16293 VK_LOG_DEBUG("ggml_backend_vk_device_buffer_from_host_ptr(backend=" << dev << ", ptr=" << ptr << ", size=" << size << ")"); 16294 GGML_UNUSED(max_tensor_size); 16295 16296 ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context; 16297 auto device = ggml_vk_get_device(ctx->device); 16298 16299 vk_buffer buf = ggml_vk_buffer_from_host_ptr(device, ptr, size); 16300 16301 if (!buf) { 16302 return {}; 16303 } 16304 16305 ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(device, std::move(buf), device->name); 16306 16307 ggml_backend_buffer_t ret = ggml_backend_buffer_init(ggml_backend_vk_device_get_buffer_type(dev), ggml_backend_vk_buffer_interface, bufctx, size); 16308 16309 return ret; 16310 } 16311 16312 static const struct ggml_backend_device_i ggml_backend_vk_device_i = { 16313 /* .get_name = */ ggml_backend_vk_device_get_name, 16314 /* .get_description = */ ggml_backend_vk_device_get_description, 16315 /* .get_memory = */ ggml_backend_vk_device_get_memory, 16316 /* .get_type = */ ggml_backend_vk_device_get_type, 16317 /* .get_props = */ ggml_backend_vk_device_get_props, 16318 /* .init_backend = */ ggml_backend_vk_device_init, 16319 /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type, 16320 /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type, 16321 /* .buffer_from_host_ptr = */ ggml_backend_vk_device_buffer_from_host_ptr, 16322 /* .supports_op = */ ggml_backend_vk_device_supports_op, 16323 /* .supports_buft = */ ggml_backend_vk_device_supports_buft, 16324 /* .offload_op = */ ggml_backend_vk_device_offload_op, 16325 /* .event_new = */ ggml_backend_vk_device_event_new, 16326 /* .event_free = */ ggml_backend_vk_device_event_free, 16327 /* .event_synchronize = */ ggml_backend_vk_device_event_synchronize, 16328 }; 16329 16330 static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) { 16331 UNUSED(reg); 16332 return GGML_VK_NAME; 16333 } 16334 16335 static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) { 16336 UNUSED(reg); 16337 return ggml_backend_vk_get_device_count(); 16338 } 16339 16340 static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) { 16341 static std::vector devices; 16342 16343 static bool initialized = false; 16344 16345 { 16346 static std::mutex mutex; 16347 std::lock_guard lock(mutex); 16348 if (!initialized) { 16349 const int min_batch_size = getenv("GGML_OP_OFFLOAD_MIN_BATCH") ? atoi(getenv("GGML_OP_OFFLOAD_MIN_BATCH")) : 32; 16350 for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) { 16351 ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context; 16352 char desc[256]; 16353 ggml_backend_vk_get_device_description(i, desc, sizeof(desc)); 16354 ctx->device = i; 16355 ctx->name = GGML_VK_NAME + std::to_string(i); 16356 ctx->description = desc; 16357 ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu; 16358 ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i); 16359 ctx->op_offload_min_batch_size = min_batch_size; 16360 devices.push_back(new ggml_backend_device { 16361 /* .iface = */ ggml_backend_vk_device_i, 16362 /* .reg = */ reg, 16363 /* .context = */ ctx, 16364 }); 16365 } 16366 initialized = true; 16367 } 16368 } 16369 16370 GGML_ASSERT(device < devices.size()); 16371 return devices[device]; 16372 } 16373 16374 static void * ggml_backend_vk_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) { 16375 UNUSED(reg); 16376 #if !defined(_WIN32) 16377 if (strcmp(name, "ggml_backend_comm_init") == 0) { 16378 return (void *) ggml_backend_vk_comm_init; 16379 } 16380 if (strcmp(name, "ggml_backend_comm_free") == 0) { 16381 return (void *) ggml_backend_vk_comm_free; 16382 } 16383 if (strcmp(name, "ggml_backend_comm_allreduce_tensor") == 0) { 16384 return (void *) ggml_backend_vk_comm_allreduce_tensor; 16385 } 16386 #else 16387 UNUSED(name); 16388 #endif 16389 return nullptr; 16390 } 16391 16392 static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = { 16393 /* .get_name = */ ggml_backend_vk_reg_get_name, 16394 /* .get_device_count = */ ggml_backend_vk_reg_get_device_count, 16395 /* .get_device = */ ggml_backend_vk_reg_get_device, 16396 /* .get_proc_address = */ ggml_backend_vk_reg_get_proc_address, 16397 }; 16398 16399 ggml_backend_reg_t ggml_backend_vk_reg() { 16400 static ggml_backend_reg reg = { 16401 /* .api_version = */ GGML_BACKEND_API_VERSION, 16402 /* .iface = */ ggml_backend_vk_reg_i, 16403 /* .context = */ nullptr, 16404 }; 16405 try { 16406 ggml_vk_instance_init(); 16407 return ® 16408 } catch (const vk::SystemError& e) { 16409 VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what()); 16410 return nullptr; 16411 } catch (const std::exception &e) { 16412 VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what()); 16413 return nullptr; 16414 } catch (...) { 16415 VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init"); 16416 return nullptr; 16417 } 16418 } 16419 16420 bool ggml_vk_instance_layer_settings_available() { 16421 #ifdef GGML_VULKAN_VALIDATE 16422 // Check if validation layer provides the extension 16423 const std::string layer_name = "VK_LAYER_KHRONOS_validation"; 16424 for (const auto& layer : vk::enumerateInstanceLayerProperties()) { 16425 if (layer_name == layer.layerName.data()) { 16426 for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) { 16427 if (strcmp("VK_EXT_layer_settings", ext.extensionName.data()) == 0) { 16428 return true; 16429 } 16430 } 16431 } 16432 } 16433 16434 std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_layer_settings not found." << std::endl; 16435 #endif 16436 return false; 16437 } 16438 16439 bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector& instance_extensions) { 16440 #ifdef __APPLE__ 16441 // Check for portability enumeration extension for MoltenVK support 16442 for (const auto& properties : instance_extensions) { 16443 if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) { 16444 return true; 16445 } 16446 } 16447 std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl; 16448 #endif 16449 return false; 16450 16451 UNUSED(instance_extensions); 16452 } 16453 16454 bool ggml_vk_instance_debug_utils_ext_available( 16455 const std::vector & instance_extensions) { 16456 // Check for portability enumeration extension for MoltenVK support 16457 for (const auto & properties : instance_extensions) { 16458 if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) { 16459 return true; 16460 } 16461 } 16462 16463 std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl; 16464 return false; 16465 16466 UNUSED(instance_extensions); 16467 } 16468 16469 bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) { 16470 VkPhysicalDeviceFeatures2 device_features2; 16471 device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; 16472 16473 VkPhysicalDeviceVulkan11Features vk11_features; 16474 vk11_features.pNext = nullptr; 16475 vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; 16476 device_features2.pNext = &vk11_features; 16477 16478 vkGetPhysicalDeviceFeatures2(vkdev, &device_features2); 16479 16480 return vk11_features.storageBuffer16BitAccess; 16481 } 16482 16483 bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) { 16484 switch (props.vendorID) { 16485 case VK_VENDOR_ID_INTEL: 16486 // Only allowing Xe2/Xe3 GPU and integrated Xe GPUs at the moment since older hardware (ex. Arc A770) has performance regressions. 16487 return (arch == vk_device_architecture::INTEL_XE2) || 16488 (arch == vk_device_architecture::INTEL_XE1 && props.deviceType == vk::PhysicalDeviceType::eIntegratedGpu && driver_props.driverID == vk::DriverId::eIntelProprietaryWindows); 16489 case VK_VENDOR_ID_AMD: 16490 if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) { 16491 // Workaround for AMD proprietary driver reporting support on all GPUs 16492 return arch == vk_device_architecture::AMD_RDNA3 || arch == vk_device_architecture::AMD_RDNA4; 16493 } 16494 return true; 16495 case VK_VENDOR_ID_QUALCOMM: 16496 // Only allow Adreno GPUs with hardware matrix cores (Gen 6+). 16497 return arch == vk_device_architecture::QUALCOMM_ADRENO; 16498 default: 16499 return true; 16500 } 16501 } 16502 16503 uint32_t ggml_vk_intel_shader_core_count(const vk::PhysicalDevice& vkdev) { 16504 VkPhysicalDeviceProperties2 props = vkdev.getProperties2(); 16505 16506 if (props.properties.vendorID != VK_VENDOR_ID_INTEL) { 16507 return 0; 16508 } 16509 16510 const uint32_t device_id = props.properties.deviceID; 16511 16512 switch (device_id) { 16513 case 0x56A6: // A310 16514 return 6; 16515 case 0x5693: // A370M 16516 case 0x56A5: // A380 16517 case 0x56B1: // Pro A40/A50 16518 return 8; 16519 case 0x5697: // A530M 16520 return 12; 16521 case 0x5692: // A550M 16522 case 0x56B3: // Pro A60 16523 return 16; 16524 case 0x56A2: // A580 16525 return 24; 16526 case 0x5691: // A730M 16527 case 0x56A1: // A750 16528 return 28; 16529 case 0x56A0: // A770 16530 case 0x5690: // A770M 16531 return 32; 16532 case 0xE212: // Pro B50 16533 return 16; 16534 case 0xE20C: // B570 16535 return 18; 16536 case 0xE20B: // B580 16537 case 0xE211: // Pro B60 16538 case 0xE222: // Pro B65 16539 return 20; 16540 case 0xE223: // Pro B70 16541 return 32; 16542 case 0xB080: // PTL Xe3 LPG 2x6 (12 subslices) 16543 return 12; 16544 default: 16545 return 0; 16546 } 16547 } 16548 16549 bool ggml_vk_intel_windows_driver_in_range(uint32_t driver_version, uint32_t lower_major, uint32_t lower_minor, uint32_t upper_major, uint32_t upper_minor) { 16550 #if defined(_WIN32) 16551 // Intel Windows encodes xxx.yyyy as [31:14].[13:0]. 16552 const uint32_t major = driver_version >> 14; 16553 const uint32_t minor = driver_version & 0x3fff; 16554 16555 const bool ge_lower = major > lower_major || (major == lower_major && minor >= lower_minor); 16556 const bool lt_upper = major < upper_major || (major == upper_major && minor < upper_minor); 16557 16558 return ge_lower && lt_upper; 16559 #else 16560 GGML_UNUSED(driver_version); 16561 GGML_UNUSED(lower_major); 16562 GGML_UNUSED(lower_minor); 16563 GGML_UNUSED(upper_major); 16564 GGML_UNUSED(upper_minor); 16565 return true; 16566 #endif 16567 } 16568 16569 GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg) 16570 16571 16572 // out-of-lined header method definitions 16573 16574 void vk_queue_handle_synchronized::submit(vk::ArrayProxy submits, vk::Fence fence) { 16575 // Workaround for NVIDIA driver bug 16576 std::unique_lock device_guard; 16577 if (device_submit_mutex) { 16578 device_guard = std::unique_lock(*device_submit_mutex); 16579 } 16580 std::lock_guard guard(mutex); 16581 try { 16582 queue.submit(submits, fence); 16583 } catch (vk::DeviceLostError &) { 16584 if (auto dev = device.lock()) { 16585 ggml_vk_print_device_lost_info(dev); 16586 } 16587 throw; 16588 } 16589 } 16590 16591 void vk_queue_handle_unsynchronized::submit(vk::ArrayProxy submits, vk::Fence fence) { 16592 // Workaround for NVIDIA driver bug 16593 std::unique_lock device_guard; 16594 if (device_submit_mutex) { 16595 device_guard = std::unique_lock(*device_submit_mutex); 16596 } 16597 try { 16598 queue.submit(submits, fence); 16599 } catch (vk::DeviceLostError &) { 16600 if (auto dev = device.lock()) { 16601 ggml_vk_print_device_lost_info(dev); 16602 } 16603 throw; 16604 } 16605 } 16606 16607 vk_device_struct::~vk_device_struct() { 16608 // the build failed before the device was created, nothing to destroy 16609 if (device == VK_NULL_HANDLE) { 16610 return; 16611 } 16612 16613 VK_LOG_DEBUG("destroy device " << name); 16614 16615 device.destroyFence(fence); 16616 16617 ggml_vk_destroy_buffer(sync_staging); 16618 16619 if (compute_queue) compute_queue->cmd_pool.destroy(device); 16620 if (transfer_queue) transfer_queue->cmd_pool.destroy(device); 16621 16622 // Explicitly clear to ensure queues drop their shared_ptrs to handles 16623 // before the Vulkan logical device instance is destroyed 16624 compute_queue.reset(); 16625 transfer_queue.reset(); 16626 16627 for (auto& pipeline : all_pipelines) { 16628 if (pipeline.expired()) { 16629 continue; 16630 } 16631 16632 vk_pipeline pl = pipeline.lock(); 16633 ggml_vk_destroy_pipeline(device, pl); 16634 } 16635 all_pipelines.clear(); 16636 16637 device.destroyDescriptorSetLayout(dsl); 16638 16639 device.destroy(); 16640 } 16641 16642 void vk_perf_logger::print_timings(bool force) { 16643 if (timings.empty()) { 16644 return; 16645 } 16646 print_count++; 16647 if ((print_count % vk_perf_logger_frequency) != 0 && !force) { 16648 return; 16649 } 16650 print_count = 0; 16651 uint64_t total_all_op_times = 0; 16652 std::cerr << "----------------\nVulkan Timings:" << std::endl; 16653 for (const auto & t : timings) { 16654 uint64_t total_op_times = 0; 16655 for (const auto & time : t.second) { 16656 total_op_times += time; 16657 } 16658 std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0) 16659 << " us = " << (total_op_times / 1000.0) << " us"; 16660 16661 // If we have as many flops entries as timing entries for the op, then compute and log the flops/S. 16662 auto it = flops.find(t.first); 16663 if (it != flops.end() && (it->second).size() == t.second.size()) { 16664 uint64_t total_op_flops = 0; 16665 for (const auto & elem : it->second) { 16666 total_op_flops += elem; 16667 } 16668 std::cerr << " (" 16669 << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) / 16670 (double(total_op_times) / (1000.0 * 1000.0 * 1000.0)) 16671 << " GFLOPS/s)"; 16672 } 16673 16674 total_all_op_times += total_op_times; 16675 16676 std::cerr << std::endl; 16677 } 16678 16679 if (timings.size() > 0) { 16680 std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl; 16681 } 16682 16683 timings.clear(); 16684 flops.clear(); 16685 } 16686 16687 std::string vk_perf_logger::get_node_fusion_name(const ggml_tensor * node, const char *fusion_name, uint64_t *n_flops) { 16688 *n_flops = ggml_vk_get_node_flops(node); 16689 std::string fusion_str; 16690 if (fusion_name) { 16691 fusion_str = fusion_name + std::string(" "); 16692 } 16693 if (node->op == GGML_OP_UNARY) { 16694 return fusion_str + ggml_unary_op_name(ggml_get_unary_op(node)); 16695 } 16696 if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) { 16697 const uint64_t m = node->ne[0]; 16698 const uint64_t n = node->ne[1]; 16699 const uint64_t k = node->src[1]->ne[0]; 16700 const uint64_t batch = node->ne[2] * node->ne[3]; 16701 std::string name = ggml_op_name(node->op); 16702 if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) || 16703 (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) { 16704 name += "_VEC"; 16705 } 16706 name += " "; 16707 name += ggml_type_name(node->src[0]->type); 16708 name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k); 16709 if (node->op == GGML_OP_MUL_MAT_ID) { 16710 name += " n_expert=" + std::to_string(node->src[0]->ne[2]); 16711 } 16712 if (batch > 1) { 16713 name += " batch=" + std::to_string(batch); 16714 } 16715 return fusion_str + name; 16716 } 16717 if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) { 16718 std::string name = ggml_op_name(node->op); 16719 const ggml_tensor * knl = node->src[0]; 16720 uint64_t Cout = node->ne[2]; 16721 uint64_t size_K = node->src[1]->ne[2] * knl->ne[0] * knl->ne[1]; 16722 uint64_t size_N = node->ne[3] * node->ne[0] * node->ne[1]; 16723 name += " M=Cout=" + std::to_string(Cout) + ", K=Cin*KW*KH=" + std::to_string(size_K) + 16724 ", N=N*OW*OH=" + std::to_string(size_N); 16725 return fusion_str + name; 16726 } 16727 if (node->op == GGML_OP_RMS_NORM) { 16728 std::string name = ggml_op_name(node->op); 16729 name += "(" + std::to_string(node->ne[0]) + "," + std::to_string(node->ne[1]) + "," + std::to_string(node->ne[2]) + "," + std::to_string(node->ne[3]) + ")"; 16730 return fusion_str + name; 16731 } 16732 if (node->op == GGML_OP_FLASH_ATTN_EXT) { 16733 const ggml_tensor * dst = node; 16734 const ggml_tensor * q = node->src[0]; 16735 const ggml_tensor * k = node->src[1]; 16736 const ggml_tensor * v = node->src[2]; 16737 const ggml_tensor * m = node->src[3]; 16738 std::stringstream name; 16739 name << fusion_str; 16740 name << ggml_op_name(node->op) << 16741 " dst(" << dst->ne[0] << "," << dst->ne[1] << "," << dst->ne[2] << "," << dst->ne[3] << "), " << 16742 " q(" << q->ne[0] << "," << q->ne[1] << "," << q->ne[2] << "," << q->ne[3] << "), " << 16743 " k(" << k->ne[0] << "," << k->ne[1] << "," << k->ne[2] << "," << k->ne[3] << "), " << 16744 " v(" << v->ne[0] << "," << v->ne[1] << "," << v->ne[2] << "," << v->ne[3] << "), " << 16745 " m(" << (m?m->ne[0]:0) << "," << (m?m->ne[1]:0) << "," << (m?m->ne[2]:0) << "," << (m?m->ne[3]:0) << ")"; 16746 return name.str(); 16747 } 16748 if (node->op == GGML_OP_TOP_K) { 16749 std::stringstream name; 16750 name << fusion_str; 16751 name << ggml_op_name(node->op) << 16752 " K=" << node->ne[0] << 16753 " (" << node->src[0]->ne[0] << "," << node->src[0]->ne[1] << "," << node->src[0]->ne[2] << "," << node->src[0]->ne[3] << ")"; 16754 return name.str(); 16755 } 16756 return fusion_str + ggml_op_name(node->op); 16757 } 16758 16759 ggml_backend_vk_buffer_context::~ggml_backend_vk_buffer_context() { 16760 ggml_vk_destroy_buffer(dev_buffer); 16761 } 16762 16763 ggml_vk_debug_label::ggml_vk_debug_label(vk_context & ctx, const std::string & pipeline_name, uint32_t wg0, uint32_t wg1, uint32_t wg2) { 16764 if (!vk_instance.debug_utils_support || ctx->s == nullptr) { 16765 return; 16766 } 16767 begin(ctx, pipeline_name + " (" + std::to_string(wg0) + "," + std::to_string(wg1) + "," + std::to_string(wg2) + ")"); 16768 } 16769 16770 ggml_vk_debug_label::ggml_vk_debug_label(vk_context & ctx, const ggml_cgraph * cgraph, int node_idx, int n_fused) { 16771 if (!vk_instance.debug_utils_support || ctx->s == nullptr) { 16772 return; 16773 } 16774 std::string name = ggml_op_name(cgraph->nodes[node_idx]->op); 16775 for (int i = 1; i <= n_fused; i++) { 16776 name += "+"; 16777 name += ggml_op_name(cgraph->nodes[node_idx + i]->op); 16778 } 16779 name += " "; 16780 name += cgraph->nodes[node_idx]->name; 16781 begin(ctx, name); 16782 } 16783 16784 ggml_vk_debug_label::ggml_vk_debug_label(vk_queue_handle * handle, const char * name) { 16785 if (!vk_instance.debug_utils_support || handle == nullptr) { 16786 return; 16787 } 16788 vk::DebugUtilsLabelEXT label = {}; 16789 label.pLabelName = name; 16790 label.color = std::array{1.0f, 1.0f, 1.0f, 1.0f}; 16791 16792 qhandle = handle; 16793 std::lock_guard guard(*qhandle); 16794 vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(qhandle->queue, reinterpret_cast(&label)); 16795 } 16796 16797 void ggml_vk_debug_label::close() { 16798 if (subctx != nullptr) { 16799 // close on the current command buffer, which may differ from the one begin used 16800 if (subctx->s != nullptr) { 16801 vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT(subctx->s->buffer->buf); 16802 } 16803 subctx->debug_labels.pop_back(); 16804 subctx = nullptr; 16805 } 16806 if (qhandle != nullptr) { 16807 std::lock_guard guard(*qhandle); 16808 vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT(qhandle->queue); 16809 qhandle = nullptr; 16810 } 16811 } 16812 16813 void ggml_vk_debug_label::begin(vk_context & ctx, const std::string & name) { 16814 if (!vk_instance.debug_utils_support || ctx->s == nullptr) { 16815 return; 16816 } 16817 subctx = ctx.get(); 16818 subctx->debug_labels.push_back(name); 16819 ggml_vk_cmd_label_begin(subctx->s->buffer->buf, subctx->debug_labels.back().c_str()); 16820 } 16821