Spaces:
Running on Zero
Running on Zero
Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+25
- backend/llama.cpp/LICENSEAdded+21
- backend/llama.cpp/MakefileAdded+9
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-apir.hAdded+15
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-backend.cppAdded+58
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-buffer-type.cppAdded+110
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-buffer.cppAdded+173
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-device.cppAdded+192
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-impl.hAdded+36
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward.gen.hAdded+53
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-shm.cppAdded+99
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-shm.hAdded+23
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-utils.cppAdded+179
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-utils.hAdded+86
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu.cppAdded+545
- backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu.hAdded+115
- backend/llama.cpp/ggml/src/ggml-vulkan/CMakeLists.txtAdded+236
- backend/llama.cpp/ggml/src/ggml-vulkan/cmake/host-toolchain.cmake.inAdded+15
- backend/llama.cpp/ggml/src/ggml-vulkan/ggml-vulkan.cppAdded
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txtAdded+35
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/acc.compAdded+37
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/add.compAdded+69
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/add1.compAdded+28
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/add_id.compAdded+42
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/arange.compAdded+20
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/argmax.compAdded+60
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/argsort.compAdded+86
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/argsort_large.compAdded+114
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/col2im_1d.compAdded+61
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/concat.compAdded+41
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/contig_copy.compAdded+53
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv2d_dw.compAdded+105
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv2d_mm.compAdded+480
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv3d_mm.compAdded+431
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv_transpose_1d.compAdded+98
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy.compAdded+25
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy_from_quant.compAdded+51
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy_to_quant.compAdded+320
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy_transpose.compAdded+67
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/count_equal.compAdded+31
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/count_experts.compAdded+51
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/cumsum.compAdded+83
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/cumsum_multipass1.compAdded+60
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/cumsum_multipass2.compAdded+66
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_f32.compAdded+20
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs.glslAdded+692
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs_cm2.glslAdded+1376
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_head.glslAdded+13
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_iq1_m.compAdded+42
- backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_iq1_s.compAdded+35
35 unmodified lines36373835 unmodified linesbackend/llama.cpp/conversion/__pycache__/base.cpython-313.pyc filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/docs/android/imported-into-android-studio.jpg filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/docs/development/llama-star/idea-arch.key filter=lfs diff=lfs merge=lfs -text35 unmodified lines3637383940414243444546474849505152535455565758596061626335 unmodified linesbackend/llama.cpp/conversion/__pycache__/base.cpython-313.pyc filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/docs/android/imported-into-android-studio.jpg filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/docs/development/llama-star/idea-arch.key filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/gguf-py/gguf/__pycache__/constants.cpython-313.pyc filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/gguf-py/gguf/__pycache__/gguf_writer.cpython-313.pyc filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/gguf-py/gguf/__pycache__/quants.cpython-313.pyc filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/media/llama0-banner.png filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/media/llama0-logo.png filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/media/matmul.png filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-aquila.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-baichuan.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-bert-bge.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-command-r.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-deepseek-coder.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-deepseek-llm.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-falcon.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-gemma-4.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-gpt-2.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-gpt-neox.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-llama-bpe.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-llama-spm.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-mpt.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-nomic-bert-moe.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-phi-3.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-qwen2.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-qwen35.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-refact.gguf filter=lfs diff=lfs merge=lfs -textbackend/llama.cpp/models/ggml-vocab-starcoder.gguf filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021MIT License
Copyright (c) 2023-2026 The ggml authors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789define newline
endef
$(error Build system changed:$(newline)\The Makefile build has been replaced by CMake.$(newline)$(newline)\For build instructions see:$(newline)\https://github.com/ggml-org/llama.cpp/blob/master/docs/build.md$(newline)${newline})123456789101112131415#include "backend/shared/apir_backend.h"#include "ggml-alloc.h"#include "ggml-impl.h"#include "ggml.h"#include "virtgpu-shm.h"#include "virtgpu-utils.h"
struct apir_buffer_context_t { apir_buffer_host_handle_t host_handle;
struct virtgpu_shmem shmem; apir_buffer_type_host_handle_t buft_host_handle;};
#include "virtgpu-forward.gen.h"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#include "virtgpu-forward-impl.h"
static long long current_time_ms() { timespec ts; clock_gettime(CLOCK_REALTIME, &ts); // Use CLOCK_MONOTONIC for elapsed time return (long long) ts.tv_sec * 1000000000LL + ts.tv_nsec;}
ggml_status apir_backend_graph_compute(virtgpu * gpu, ggml_cgraph * cgraph) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BACKEND_GRAPH_COMPUTE);
std::vector<uint8_t> cgraph_data; size_t cgraph_size = apir_serialize_ggml_cgraph(cgraph, cgraph_data);
virtgpu_shmem temp_shmem; // Local storage for large buffers virtgpu_shmem * shmem = &temp_shmem; bool using_shared_shmem = false;
if (cgraph_size <= gpu->data_shmem.mmap_size) { // Lock mutex before using shared data_shmem buffer if (mtx_lock(&gpu->data_shmem_mutex) != thrd_success) { GGML_ABORT(GGML_VIRTGPU "%s: Failed to lock data_shmem mutex", __func__); } using_shared_shmem = true; shmem = &gpu->data_shmem; } else if (virtgpu_shmem_create(gpu, cgraph_size, shmem)) { GGML_ABORT(GGML_VIRTGPU "%s: Couldn't allocate the guest-host shared buffer", __func__); }
apir_encode_virtgpu_shmem_res_id(encoder, shmem->res_id);
apir_encode_size_t(encoder, &cgraph_size);
char * shmem_data = (char *) shmem->mmap_ptr; apir_encoder secondary_enc = apir_new_encoder(shmem_data, cgraph_size);
apir_encode_cgraph_data(&secondary_enc, cgraph_data);
REMOTE_CALL(gpu, encoder, decoder, ret);
ggml_status status = GGML_STATUS_ABORTED; apir_decode_ggml_status(decoder, &status);
remote_call_finish(gpu, encoder, decoder);
// Unlock mutex before cleanup if (using_shared_shmem) { mtx_unlock(&gpu->data_shmem_mutex); } else { virtgpu_shmem_destroy(gpu, shmem); }
return status;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110#include "virtgpu-forward-impl.h"
char * apir_buffer_type_get_name(virtgpu * gpu, apir_buffer_type_host_handle_t host_handle) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_TYPE_GET_NAME);
apir_encode_apir_buffer_type_host_handle(encoder, host_handle);
REMOTE_CALL(gpu, encoder, decoder, ret);
const size_t string_size = apir_decode_array_size_unchecked(decoder); char * string = (char *) apir_decoder_alloc_array(sizeof(char), string_size); if (!string) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: Could not allocate the device name buffer\n", __func__); apir_decoder_set_fatal(decoder); } apir_decode_char_array(decoder, string, string_size);
remote_call_finish(gpu, encoder, decoder);
return string;}
size_t apir_buffer_type_get_alignment(virtgpu * gpu, apir_buffer_type_host_handle_t host_handle) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_TYPE_GET_ALIGNMENT);
apir_encode_apir_buffer_type_host_handle(encoder, host_handle);
REMOTE_CALL(gpu, encoder, decoder, ret);
size_t alignment; apir_decode_size_t(decoder, &alignment);
remote_call_finish(gpu, encoder, decoder);
return alignment;}
size_t apir_buffer_type_get_max_size(virtgpu * gpu, apir_buffer_type_host_handle_t host_handle) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_TYPE_GET_MAX_SIZE);
apir_encode_apir_buffer_type_host_handle(encoder, host_handle);
REMOTE_CALL(gpu, encoder, decoder, ret);
size_t max_size; apir_decode_size_t(decoder, &max_size);
remote_call_finish(gpu, encoder, decoder);
return max_size;}
apir_buffer_context_t apir_buffer_type_alloc_buffer(virtgpu * gpu, apir_buffer_type_host_handle_t host_handle, size_t size) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
apir_buffer_context_t buffer_context;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_TYPE_ALLOC_BUFFER);
apir_encode_apir_buffer_type_host_handle(encoder, host_handle);
apir_encode_size_t(encoder, &size);
REMOTE_CALL(gpu, encoder, decoder, ret);
apir_decode_apir_buffer_host_handle_t(decoder, &buffer_context.host_handle);
remote_call_finish(gpu, encoder, decoder);
return buffer_context;}
size_t apir_buffer_type_get_alloc_size(virtgpu * gpu, apir_buffer_type_host_handle_t host_handle, const ggml_tensor * op) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_TYPE_GET_ALLOC_SIZE);
apir_encode_apir_buffer_type_host_handle(encoder, host_handle);
apir_encode_ggml_tensor_inline(encoder, op);
REMOTE_CALL(gpu, encoder, decoder, ret);
size_t alloc_size; apir_decode_size_t(decoder, &alloc_size);
remote_call_finish(gpu, encoder, decoder);
return alloc_size;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173#include "virtgpu-forward-impl.h"
void * apir_buffer_get_base(virtgpu * gpu, apir_buffer_context_t * buffer_context) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_GET_BASE);
apir_encode_apir_buffer_host_handle_t(encoder, &buffer_context->host_handle);
REMOTE_CALL(gpu, encoder, decoder, ret);
uintptr_t base; apir_decode_uintptr_t(decoder, &base);
remote_call_finish(gpu, encoder, decoder);
return (void *) base;}
void apir_buffer_set_tensor(virtgpu * gpu, apir_buffer_context_t * buffer_context, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_SET_TENSOR);
apir_encode_apir_buffer_host_handle_t(encoder, &buffer_context->host_handle); apir_encode_ggml_tensor(encoder, tensor);
virtgpu_shmem temp_shmem; // Local storage for large buffers virtgpu_shmem * shmem = &temp_shmem; bool using_shared_shmem = false;
if (size <= gpu->data_shmem.mmap_size) { // Lock mutex before using shared data_shmem buffer if (mtx_lock(&gpu->data_shmem_mutex) != thrd_success) { GGML_ABORT(GGML_VIRTGPU "%s: Failed to lock data_shmem mutex", __func__); } using_shared_shmem = true; shmem = &gpu->data_shmem;
} else if (virtgpu_shmem_create(gpu, size, shmem)) { GGML_ABORT(GGML_VIRTGPU "%s: Couldn't allocate the guest-host shared buffer", __func__); }
memcpy(shmem->mmap_ptr, data, size); apir_encode_virtgpu_shmem_res_id(encoder, shmem->res_id);
apir_encode_size_t(encoder, &offset); apir_encode_size_t(encoder, &size);
REMOTE_CALL(gpu, encoder, decoder, ret);
remote_call_finish(gpu, encoder, decoder);
// Unlock mutex before cleanup if (using_shared_shmem) { mtx_unlock(&gpu->data_shmem_mutex); } else { virtgpu_shmem_destroy(gpu, shmem); }
return;}
void apir_buffer_get_tensor(virtgpu * gpu, apir_buffer_context_t * buffer_context, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_GET_TENSOR);
apir_encode_apir_buffer_host_handle_t(encoder, &buffer_context->host_handle); apir_encode_ggml_tensor(encoder, tensor);
virtgpu_shmem temp_shmem; // Local storage for large buffers virtgpu_shmem * shmem = &temp_shmem; bool using_shared_shmem = false;
if (size <= gpu->data_shmem.mmap_size) { // Lock mutex before using shared data_shmem buffer if (mtx_lock(&gpu->data_shmem_mutex) != thrd_success) { GGML_ABORT(GGML_VIRTGPU "%s: Failed to lock data_shmem mutex", __func__); } using_shared_shmem = true; shmem = &gpu->data_shmem;
} else if (virtgpu_shmem_create(gpu, size, shmem)) { GGML_ABORT(GGML_VIRTGPU "%s: Couldn't allocate the guest-host shared buffer", __func__); }
apir_encode_virtgpu_shmem_res_id(encoder, shmem->res_id); apir_encode_size_t(encoder, &offset); apir_encode_size_t(encoder, &size);
REMOTE_CALL(gpu, encoder, decoder, ret);
memcpy(data, shmem->mmap_ptr, size);
remote_call_finish(gpu, encoder, decoder);
// Unlock mutex before cleanup if (using_shared_shmem) { mtx_unlock(&gpu->data_shmem_mutex); } else { virtgpu_shmem_destroy(gpu, shmem); }}
bool apir_buffer_cpy_tensor(virtgpu * gpu, apir_buffer_context_t * buffer_context, const ggml_tensor * src, const ggml_tensor * dst) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_CPY_TENSOR);
apir_encode_apir_buffer_host_handle_t(encoder, &buffer_context->host_handle); apir_encode_ggml_tensor(encoder, src); apir_encode_ggml_tensor(encoder, dst);
REMOTE_CALL(gpu, encoder, decoder, ret);
bool ret_val; apir_decode_bool_t(decoder, &ret_val);
remote_call_finish(gpu, encoder, decoder);
return ret_val;}
void apir_buffer_clear(virtgpu * gpu, apir_buffer_context_t * buffer_context, uint8_t value) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_CLEAR);
apir_encode_apir_buffer_host_handle_t(encoder, &buffer_context->host_handle); apir_encode_uint8_t(encoder, &value);
REMOTE_CALL(gpu, encoder, decoder, ret);
remote_call_finish(gpu, encoder, decoder);}
void apir_buffer_free_buffer(virtgpu * gpu, apir_buffer_context_t * buffer_context) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_BUFFER_FREE_BUFFER);
apir_encode_apir_buffer_host_handle_t(encoder, &buffer_context->host_handle);
REMOTE_CALL(gpu, encoder, decoder, ret);
remote_call_finish(gpu, encoder, decoder);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192#include "virtgpu-forward-impl.h"#include "virtgpu-shm.h"
int apir_device_get_count(virtgpu * gpu) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_GET_COUNT); REMOTE_CALL(gpu, encoder, decoder, ret);
int32_t dev_count = -1; apir_decode_int32_t(decoder, &dev_count);
remote_call_finish(gpu, encoder, decoder);
return dev_count;}
char * apir_device_get_name(virtgpu * gpu) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_GET_NAME); REMOTE_CALL(gpu, encoder, decoder, ret);
const size_t string_size = apir_decode_array_size_unchecked(decoder); char * string = (char *) apir_decoder_alloc_array(sizeof(char), string_size); if (!string) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: Could not allocate the device name buffer\n", __func__); return NULL; } apir_decode_char_array(decoder, string, string_size);
remote_call_finish(gpu, encoder, decoder);
return string;}
char * apir_device_get_description(virtgpu * gpu) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_GET_DESCRIPTION);
REMOTE_CALL(gpu, encoder, decoder, ret);
const size_t string_size = apir_decode_array_size_unchecked(decoder); char * string = (char *) apir_decoder_alloc_array(sizeof(char), string_size); if (!string) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: Could not allocate the device description buffer\n", __func__);
return NULL; } apir_decode_char_array(decoder, string, string_size);
remote_call_finish(gpu, encoder, decoder);
return string;}
uint32_t apir_device_get_type(virtgpu * gpu) { static uint32_t dev_type = 255; if (dev_type != 255) { return dev_type; }
apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_GET_TYPE);
REMOTE_CALL(gpu, encoder, decoder, ret);
apir_decode_uint32_t(decoder, &dev_type);
remote_call_finish(gpu, encoder, decoder);
return dev_type;}
void apir_device_get_memory(virtgpu * gpu, size_t * free, size_t * total) { static size_t dev_free = 0; static size_t dev_total = 0; apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_GET_MEMORY);
REMOTE_CALL(gpu, encoder, decoder, ret);
apir_decode_size_t(decoder, &dev_free); apir_decode_size_t(decoder, &dev_total);
*free = dev_free; *total = dev_total;
remote_call_finish(gpu, encoder, decoder);
return;}
bool apir_device_supports_op(virtgpu * gpu, const ggml_tensor * op) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_SUPPORTS_OP);
apir_encode_ggml_tensor_inline(encoder, op);
REMOTE_CALL(gpu, encoder, decoder, ret);
bool supports_op; apir_decode_bool_t(decoder, &supports_op);
remote_call_finish(gpu, encoder, decoder);
return supports_op;}
apir_buffer_type_host_handle_t apir_device_get_buffer_type(virtgpu * gpu) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_GET_BUFFER_TYPE);
REMOTE_CALL(gpu, encoder, decoder, ret);
apir_buffer_type_host_handle_t buft_handle; apir_decode_apir_buffer_type_host_handle_t(decoder, &buft_handle);
remote_call_finish(gpu, encoder, decoder);
return buft_handle;}
void apir_device_get_props(virtgpu * gpu, bool * async, bool * host_buffer, bool * buffer_from_host_ptr, bool * events) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_GET_PROPS);
REMOTE_CALL(gpu, encoder, decoder, ret);
apir_decode_bool_t(decoder, async); apir_decode_bool_t(decoder, host_buffer); apir_decode_bool_t(decoder, buffer_from_host_ptr); apir_decode_bool_t(decoder, events);
remote_call_finish(gpu, encoder, decoder);
return;}
apir_buffer_context_t apir_device_buffer_from_ptr(virtgpu * gpu, size_t size, size_t max_tensor_size) { apir_encoder * encoder; apir_decoder * decoder; ApirForwardReturnCode ret;
apir_buffer_context_t buffer_context;
REMOTE_CALL_PREPARE(gpu, encoder, APIR_COMMAND_TYPE_DEVICE_BUFFER_FROM_PTR);
if (virtgpu_shmem_create(gpu, size, &buffer_context.shmem)) { GGML_ABORT(GGML_VIRTGPU "%s: Couldn't allocate %ldb of guest-host shared buffer", __func__, size); }
apir_encode_virtgpu_shmem_res_id(encoder, buffer_context.shmem.res_id);
apir_encode_size_t(encoder, &size); apir_encode_size_t(encoder, &max_tensor_size);
REMOTE_CALL(gpu, encoder, decoder, ret);
apir_decode_apir_buffer_host_handle_t(decoder, &buffer_context.host_handle); buffer_context.buft_host_handle = apir_decode_apir_buffer_type_host_handle(decoder);
remote_call_finish(gpu, encoder, decoder);
return buffer_context;}123456789101112131415161718192021222324252627282930313233343536#pragma once
// clang-format off#include "virtgpu.h"#include "ggml-remoting.h"#include "backend/shared/apir_backend.h"#include "backend/shared/apir_cs_ggml.h"#include "ggml-backend-impl.h"// clang-format on
#define REMOTE_CALL_PREPARE(gpu_dev_name, encoder_name, apir_command_type__) \ int32_t REMOTE_CALL_PREPARE_forward_flag = (int32_t) apir_command_type__; \ const char * REMOTE_CALL_PREPARE_command_name = apir_dispatch_command_name(apir_command_type__); \ do { \ encoder_name = remote_call_prepare(gpu_dev_name, APIR_COMMAND_TYPE_FORWARD, REMOTE_CALL_PREPARE_forward_flag); \ if (!encoder_name) { \ GGML_ABORT(GGML_VIRTGPU "%s: failed to prepare the remote call encoder", __func__); \ } \ } while (0)
#define REMOTE_CALL(gpu_dev_name, encoder_name, decoder_name, ret_name) \ do { \ ret_name = (ApirForwardReturnCode) remote_call(gpu_dev_name, encoder_name, &decoder_name, 0, NULL); \ if (!decoder_name) { \ GGML_ABORT(GGML_VIRTGPU "%s: failed to kick the remote call", __func__); \ } \ if (ret_name < APIR_FORWARD_BASE_INDEX) { \ GGML_ABORT(GGML_VIRTGPU "%s: failed to forward the API call: %s: code %d", __func__, \ apir_forward_error(ret_name), ret_name); \ } \ ret_name = (ApirForwardReturnCode) (ret_name - APIR_FORWARD_BASE_INDEX); \ if (ret_name != 0) { \ GGML_ABORT(GGML_VIRTGPU "backend function '%s' failed (return code: %d)", \ REMOTE_CALL_PREPARE_command_name, ret_name); \ } \ } while (0)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#pragma once
/* device */void apir_device_get_device_count(struct virtgpu * gpu);int apir_device_get_count(struct virtgpu * gpu);char * apir_device_get_name(struct virtgpu * gpu);char * apir_device_get_description(struct virtgpu * gpu);uint32_t apir_device_get_type(struct virtgpu * gpu);void apir_device_get_memory(struct virtgpu * gpu, size_t * free, size_t * total);bool apir_device_supports_op(struct virtgpu * gpu, const ggml_tensor * op);apir_buffer_type_host_handle_t apir_device_get_buffer_type(struct virtgpu * gpu);void apir_device_get_props(struct virtgpu * gpu, bool * async, bool * host_buffer, bool * buffer_from_host_ptr, bool * events);apir_buffer_context_t apir_device_buffer_from_ptr(struct virtgpu * gpu, size_t size, size_t max_tensor_size);
/* buffer-type */char * apir_buffer_type_get_name(struct virtgpu * gpu, apir_buffer_type_host_handle_t host_handle);size_t apir_buffer_type_get_alignment(struct virtgpu * gpu, apir_buffer_type_host_handle_t host_handle);size_t apir_buffer_type_get_max_size(struct virtgpu * gpu, apir_buffer_type_host_handle_t host_handle);/* apir_buffer_type_is_host is deprecated. */apir_buffer_context_t apir_buffer_type_alloc_buffer(struct virtgpu * gpu, apir_buffer_type_host_handle_t host_handle, size_t size);size_t apir_buffer_type_get_alloc_size(struct virtgpu * gpu, apir_buffer_type_host_handle_t host_handle, const ggml_tensor * op);
/* buffer */void * apir_buffer_get_base(struct virtgpu * gpu, apir_buffer_context_t * buffer_context);void apir_buffer_set_tensor(struct virtgpu * gpu, apir_buffer_context_t * buffer_context, ggml_tensor * tensor, const void * data, size_t offset, size_t size);void apir_buffer_get_tensor(struct virtgpu * gpu, apir_buffer_context_t * buffer_context, const ggml_tensor * tensor, void * data, size_t offset, size_t size);bool apir_buffer_cpy_tensor(struct virtgpu * gpu, apir_buffer_context_t * buffer_context, const ggml_tensor * src, const ggml_tensor * dst);void apir_buffer_clear(struct virtgpu * gpu, apir_buffer_context_t * buffer_context, uint8_t value);void apir_buffer_free_buffer(struct virtgpu * gpu, apir_buffer_context_t * buffer_context);
/* backend */ggml_status apir_backend_graph_compute(struct virtgpu * gpu, ggml_cgraph * cgraph);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899#include "virtgpu-shm.h"
#include "virtgpu.h"#include "ggml-remoting.h"
#include <assert.h>
static uint32_t virtgpu_ioctl_resource_create_blob(virtgpu * gpu, uint32_t blob_mem, uint32_t blob_flags, size_t blob_size, uint64_t blob_id, uint32_t * res_id) {#ifdef SIMULATE_BO_SIZE_FIX blob_size = align64(blob_size, 4096);#endif
drm_virtgpu_resource_create_blob args = { .blob_mem = blob_mem, .blob_flags = blob_flags, .bo_handle = 0, .res_handle = 0, .size = blob_size, .pad = 0, .cmd_size = 0, .cmd = 0, .blob_id = blob_id, };
if (virtgpu_ioctl(gpu, DRM_IOCTL_VIRTGPU_RESOURCE_CREATE_BLOB, &args)) { return 0; }
*res_id = args.res_handle; return args.bo_handle;}
static void virtgpu_ioctl_gem_close(virtgpu * gpu, uint32_t gem_handle) { drm_gem_close args = { .handle = gem_handle, .pad = 0, };
const int ret = virtgpu_ioctl(gpu, DRM_IOCTL_GEM_CLOSE, &args); assert(!ret);#ifdef NDEBUG UNUSED(ret);#endif}
static void * virtgpu_ioctl_map(virtgpu * gpu, uint32_t gem_handle, size_t size) { drm_virtgpu_map args = { .offset = 0, .handle = gem_handle, .pad = 0, };
if (virtgpu_ioctl(gpu, DRM_IOCTL_VIRTGPU_MAP, &args)) { return NULL; }
void * ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, gpu->fd, args.offset); if (ptr == MAP_FAILED) { return NULL; }
return ptr;}
void virtgpu_shmem_destroy(virtgpu * gpu, virtgpu_shmem * shmem) { munmap(shmem->mmap_ptr, shmem->mmap_size); virtgpu_ioctl_gem_close(gpu, shmem->gem_handle);}
int virtgpu_shmem_create(virtgpu * gpu, size_t size, virtgpu_shmem * shmem) { size = align64(size, 16384);
uint32_t res_id; uint32_t gem_handle = virtgpu_ioctl_resource_create_blob(gpu, VIRTGPU_BLOB_MEM_HOST3D, VIRTGPU_BLOB_FLAG_USE_MAPPABLE, size, 0, &res_id);
if (!gem_handle) { return 1; }
void * ptr = virtgpu_ioctl_map(gpu, gem_handle, size); if (!ptr) { virtgpu_ioctl_gem_close(gpu, gem_handle); GGML_LOG_ERROR(GGML_VIRTGPU "%s: virtgpu_ioctl_map failed\n", __func__); return 1; }
shmem->res_id = res_id; shmem->mmap_size = size; shmem->mmap_ptr = ptr; shmem->gem_handle = gem_handle;
return 0;}1234567891011121314151617181920212223#pragma once
#include "virtgpu-utils.h"
#include <sys/mman.h>
#include <atomic>#include <cassert>#include <cstddef>#include <cstdint>
struct virtgpu;
struct virtgpu_shmem { uint32_t res_id; size_t mmap_size; void * mmap_ptr;
uint32_t gem_handle;};
int virtgpu_shmem_create(virtgpu * gpu, size_t size, virtgpu_shmem * shmem);void virtgpu_shmem_destroy(virtgpu * gpu, virtgpu_shmem * shmem);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179#include "virtgpu-utils.h"
#include <malloc.h>#include <stdlib.h>
#include <cstring>
#define NODE_ALLOC_ALIGN 64#define NODE_PTR_MASK (~((uintptr_t) NODE_ALLOC_ALIGN - 1))#define NODE_LEVEL_MASK ((uintptr_t) NODE_ALLOC_ALIGN - 1)#define NULL_NODE 0
#define os_malloc_aligned(_size, _align) _aligned_malloc(_size, _align)#define os_free_aligned(_ptr) free(_ptr)#define p_atomic_cmpxchg(v, old, _new) __sync_val_compare_and_swap((v), (old), (_new))
static inline uint64_t util_logbase2_64(uint64_t n) {#if defined(HAVE___BUILTIN_CLZLL) return ((sizeof(uint64_t) * 8 - 1) - __builtin_clzll(n | 1));#else uint64_t pos = 0ull; if (n >= 1ull << 32) { n >>= 32; pos += 32; } if (n >= 1ull << 16) { n >>= 16; pos += 16; } if (n >= 1ull << 8) { n >>= 8; pos += 8; } if (n >= 1ull << 4) { n >>= 4; pos += 4; } if (n >= 1ull << 2) { n >>= 2; pos += 2; } if (n >= 1ull << 1) { pos += 1; } return pos;#endif}
void util_sparse_array_init(util_sparse_array * arr, size_t elem_size, size_t node_size) { memset(arr, 0, sizeof(*arr)); arr->elem_size = elem_size; arr->node_size_log2 = util_logbase2_64(node_size); assert(node_size >= 2 && node_size == (1ull << arr->node_size_log2));}
static inline void * os_malloc_aligned(size_t size, size_t alignment) { void * ptr; alignment = (alignment + sizeof(void *) - 1) & ~(sizeof(void *) - 1); if (posix_memalign(&ptr, alignment, size) != 0) { return NULL; } return ptr;}
static inline void * _util_sparse_array_node_data(uintptr_t handle) { return (void *) (handle & NODE_PTR_MASK);}
static inline unsigned _util_sparse_array_node_level(uintptr_t handle) { return handle & NODE_LEVEL_MASK;}
static inline void _util_sparse_array_node_finish(util_sparse_array * arr, uintptr_t node) { if (_util_sparse_array_node_level(node) > 0) { uintptr_t * children = (uintptr_t *) _util_sparse_array_node_data(node); size_t node_size = 1ull << arr->node_size_log2; for (size_t i = 0; i < node_size; i++) { if (children[i]) { _util_sparse_array_node_finish(arr, children[i]); } } }
os_free_aligned(_util_sparse_array_node_data(node));}
static inline uintptr_t _util_sparse_array_node(void * data, unsigned level) { assert(data != NULL); assert(((uintptr_t) data & NODE_LEVEL_MASK) == 0); assert((level & NODE_PTR_MASK) == 0); return (uintptr_t) data | level;}
inline uintptr_t _util_sparse_array_node_alloc(util_sparse_array * arr, unsigned level) { size_t size; if (level == 0) { size = arr->elem_size << arr->node_size_log2; } else { size = sizeof(uintptr_t) << arr->node_size_log2; }
void * data = os_malloc_aligned(size, NODE_ALLOC_ALIGN); memset(data, 0, size);
return _util_sparse_array_node(data, level);}
static inline uintptr_t _util_sparse_array_set_or_free_node(uintptr_t * node_ptr, uintptr_t cmp_node, uintptr_t node) { uintptr_t prev_node = p_atomic_cmpxchg(node_ptr, cmp_node, node);
if (prev_node != cmp_node) { /* We lost the race. Free this one and return the one that was already * allocated. */ os_free_aligned(_util_sparse_array_node_data(node)); return prev_node; } else { return node; }}
void * util_sparse_array_get(util_sparse_array * arr, uint64_t idx) { const unsigned node_size_log2 = arr->node_size_log2; uintptr_t root = p_atomic_read(&arr->root); if (unlikely(!root)) { unsigned root_level = 0; uint64_t idx_iter = idx >> node_size_log2; while (idx_iter) { idx_iter >>= node_size_log2; root_level++; } uintptr_t new_root = _util_sparse_array_node_alloc(arr, root_level); root = _util_sparse_array_set_or_free_node(&arr->root, NULL_NODE, new_root); }
while (1) { unsigned root_level = _util_sparse_array_node_level(root); uint64_t root_idx = idx >> (root_level * node_size_log2); if (likely(root_idx < (1ull << node_size_log2))) { break; }
/* In this case, we have a root but its level is low enough that the * requested index is out-of-bounds. */ uintptr_t new_root = _util_sparse_array_node_alloc(arr, root_level + 1);
uintptr_t * new_root_children = (uintptr_t *) _util_sparse_array_node_data(new_root); new_root_children[0] = root;
/* We only add one at a time instead of the whole tree because it's * easier to ensure correctness of both the tree building and the * clean-up path. Because we're only adding one node we never have to * worry about trying to free multiple things without freeing the old * things. */ root = _util_sparse_array_set_or_free_node(&arr->root, root, new_root); }
void * node_data = _util_sparse_array_node_data(root); unsigned node_level = _util_sparse_array_node_level(root); while (node_level > 0) { uint64_t child_idx = (idx >> (node_level * node_size_log2)) & ((1ull << node_size_log2) - 1);
uintptr_t * children = (uintptr_t *) node_data; uintptr_t child = p_atomic_read(&children[child_idx]);
if (unlikely(!child)) { child = _util_sparse_array_node_alloc(arr, node_level - 1); child = _util_sparse_array_set_or_free_node(&children[child_idx], NULL_NODE, child); }
node_data = _util_sparse_array_node_data(child); node_level = _util_sparse_array_node_level(child); }
uint64_t elem_idx = idx & ((1ull << node_size_log2) - 1); return (void *) ((char *) node_data + (elem_idx * arr->elem_size));}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586#pragma once
#include <atomic>#include <cassert>#include <cerrno>#include <cstdarg>#include <cstddef>#include <cstdint>#include <cstdio>#include <cstdlib>#include <ctime>
#define unlikely(x) __builtin_expect(!!(x), 0)#define likely(x) __builtin_expect(!!(x), 1)
#ifndef UNUSED# define UNUSED(x) (void) (x)#endif
/** Checks is a value is a power of two. Does not handle zero. */#define IS_POT(v) (((v) & ((v) - 1)) == 0)
/** Checks is a value is a power of two. Zero handled. */#define IS_POT_NONZERO(v) ((v) != 0 && IS_POT(v))
/** Align a value to a power of two */#define ALIGN_POT(x, pot_align) (((x) + (pot_align) - 1) & ~((pot_align) - 1))
#define p_atomic_read(_v) __atomic_load_n((_v), __ATOMIC_ACQUIRE)
static inline bool util_is_power_of_two_nonzero64(uint64_t v) { return IS_POT_NONZERO(v);}
static inline uint64_t align64(uint64_t value, uint64_t alignment) { assert(util_is_power_of_two_nonzero64(alignment)); return ALIGN_POT(value, alignment);}
struct list_head { list_head * prev; list_head * next;};
struct util_sparse_array { size_t elem_size; unsigned node_size_log2;
uintptr_t root;};
void * util_sparse_array_get(util_sparse_array * arr, uint64_t idx);void util_sparse_array_init(util_sparse_array * arr, size_t elem_size, size_t node_size);
inline void os_time_sleep(int64_t usecs) { timespec time; time.tv_sec = usecs / 1000000; time.tv_nsec = (usecs % 1000000) * 1000; while (clock_nanosleep(CLOCK_MONOTONIC, 0, &time, &time) == EINTR) ;}
struct timer_data { long long start; long long total; long long count;};
static inline void start_timer(timer_data * timer) { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); timer->start = (long long) ts.tv_sec * 1000000000LL + ts.tv_nsec;}
// returns the duration in nsstatic inline long long stop_timer(timer_data * timer) { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); long long timer_end = (long long) ts.tv_sec * 1000000000LL + ts.tv_nsec;
long long duration = (timer_end - timer->start); timer->total += duration; timer->count += 1;
return duration;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545#include "virtgpu.h"#include "ggml-remoting.h"
#include <stdio.h>#include <unistd.h>
#include <cassert>#include <cerrno>#include <cstdlib>
static virt_gpu_result_t virtgpu_open_device(virtgpu * gpu, const drmDevicePtr dev);static virt_gpu_result_t virtgpu_open(virtgpu * gpu);
static virt_gpu_result_t virtgpu_init_capset(virtgpu * gpu);static virt_gpu_result_t virtgpu_init_context(virtgpu * gpu);
static int virtgpu_ioctl_context_init(virtgpu * gpu, virgl_renderer_capset capset_id);static int virtgpu_ioctl_get_caps(virtgpu * gpu, virgl_renderer_capset id, uint32_t version, void * capset, size_t capset_size);static uint64_t virtgpu_ioctl_getparam(virtgpu * gpu, uint64_t param);static void virtgpu_init_renderer_info(virtgpu * gpu);
static void log_call_duration(long long call_duration_ns, const char * name);
const uint64_t APIR_HANDSHAKE_MAX_WAIT_MS = 2 * 1000; // 2sconst uint64_t APIR_LOADLIBRARY_MAX_WAIT_MS = 60 * 1000; // 60s
static int virtgpu_handshake(virtgpu * gpu) { apir_encoder * encoder; apir_decoder * decoder;
encoder = remote_call_prepare(gpu, APIR_COMMAND_TYPE_HANDSHAKE, 0); if (!encoder) { GGML_ABORT(GGML_VIRTGPU "%s: failed to prepare the remote call encoder", __func__); return 1; }
/* write handshake props */
uint32_t guest_major = APIR_PROTOCOL_MAJOR; uint32_t guest_minor = APIR_PROTOCOL_MINOR; apir_encode_uint32_t(encoder, &guest_major); apir_encode_uint32_t(encoder, &guest_minor);
/* *** */
uint32_t ret_magic; long long call_duration_ns; ret_magic = remote_call(gpu, encoder, &decoder, APIR_HANDSHAKE_MAX_WAIT_MS, &call_duration_ns); log_call_duration(call_duration_ns, "API Remoting handshake");
if (!decoder) { GGML_ABORT(GGML_VIRTGPU "%s: failed to initiate the communication with the virglrenderer library. " "Most likely, the wrong virglrenderer library was loaded in the hypervisor.", __func__); return 1; }
/* read handshake return values */
uint32_t host_major; uint32_t host_minor;
if (ret_magic != APIR_HANDSHAKE_MAGIC) { GGML_ABORT(GGML_VIRTGPU "%s: handshake with the virglrenderer failed (code=%d | %s)", __func__, ret_magic, apir_backend_initialize_error(ret_magic)); } else { apir_decode_uint32_t(decoder, &host_major); apir_decode_uint32_t(decoder, &host_minor); }
remote_call_finish(gpu, encoder, decoder);
if (ret_magic != APIR_HANDSHAKE_MAGIC) { return 1; }
GGML_LOG_INFO(GGML_VIRTGPU "%s: Guest is running with %u.%u\n", __func__, guest_major, guest_minor); GGML_LOG_INFO(GGML_VIRTGPU "%s: Host is running with %u.%u\n", __func__, host_major, host_minor);
if (guest_major != host_major) { GGML_LOG_ERROR(GGML_VIRTGPU "Host major (%d) and guest major (%d) version differ\n", host_major, guest_major); } else if (guest_minor != host_minor) { GGML_LOG_WARN(GGML_VIRTGPU "Host minor (%d) and guest minor (%d) version differ\n", host_minor, guest_minor); }
return 0;}
static ApirLoadLibraryReturnCode virtgpu_load_library(virtgpu * gpu) { apir_encoder * encoder; apir_decoder * decoder; ApirLoadLibraryReturnCode ret;
encoder = remote_call_prepare(gpu, APIR_COMMAND_TYPE_LOADLIBRARY, 0); if (!encoder) { GGML_ABORT(GGML_VIRTGPU "%s: hypercall error: failed to prepare the API Remoting command encoder", __func__); return APIR_LOAD_LIBRARY_HYPERCALL_INITIALIZATION_ERROR; }
long long call_duration_ns;
ret = (ApirLoadLibraryReturnCode) remote_call(gpu, encoder, &decoder, APIR_LOADLIBRARY_MAX_WAIT_MS, &call_duration_ns); log_call_duration(call_duration_ns, "API Remoting LoadLibrary");
if (!decoder) { GGML_ABORT(GGML_VIRTGPU "%s: hypercall error: failed to trigger the API Remoting hypercall.\n", __func__); return APIR_LOAD_LIBRARY_HYPERCALL_INITIALIZATION_ERROR; }
remote_call_finish(gpu, encoder, decoder);
if (ret == APIR_LOAD_LIBRARY_SUCCESS) { GGML_LOG_INFO(GGML_VIRTGPU "The API Remoting backend was successfully loaded and initialized\n");
return ret; }
// something wrong happened, find out what. if (ret < APIR_LOAD_LIBRARY_INIT_BASE_INDEX) { if (ret == APIR_LOAD_LIBRARY_ENV_VAR_MISSING) { GGML_ABORT(GGML_VIRTGPU "%s: virglrenderer could not open the API Remoting backend library, " "some environment variables are missing. " "Make sure virglrenderer is correctly configured by the hypervisor. (%s)", __func__, apir_load_library_error(ret)); } else if (ret == APIR_LOAD_LIBRARY_CANNOT_OPEN) { GGML_ABORT(GGML_VIRTGPU "%s: virglrenderer could not open the API Remoting backend library. " "Make sure virglrenderer is correctly configured by the hypervisor. (%s)", __func__, apir_load_library_error(ret)); } else if (ret == APIR_LOAD_LIBRARY_ENV_VAR_MISSING) { GGML_ABORT(GGML_VIRTGPU "%s: could not load the backend library, some symbols are missing. " "Make sure virglrenderer is correctly configured by the hypervisor. (%s) ", __func__, apir_load_library_error(ret)); } else { GGML_ABORT(GGML_VIRTGPU "%s: virglrenderer could not load the API Remoting backend library. (%s - code %d)", __func__, apir_load_library_error(ret), ret); } return ret; }
GGML_LOG_INFO(GGML_VIRTGPU "%s: virglrenderer successfully loaded the API Remoting backend library.\n", __func__);
ApirLoadLibraryReturnCode apir_ret = (ApirLoadLibraryReturnCode) (ret - APIR_LOAD_LIBRARY_INIT_BASE_INDEX);
if (apir_ret == APIR_LOAD_LIBRARY_CANNOT_OPEN) { GGML_ABORT(GGML_VIRTGPU "%s: the API Remoting backend library couldn't load the GGML backend library. " "Make sure virglrenderer is correctly configured by the hypervisor. (%s)", __func__, apir_load_library_error(apir_ret)); } else if (apir_ret == APIR_LOAD_LIBRARY_SYMBOL_MISSING) { GGML_ABORT( GGML_VIRTGPU "%s: the API Remoting backend library couldn't load the GGML backend library, some symbols are missing. " "Make sure virglrenderer is correctly configured by the hypervisor. (%s)", __func__, apir_load_library_error(apir_ret)); } else if (apir_ret < APIR_LOAD_LIBRARY_INIT_BASE_INDEX) { GGML_ABORT(GGML_VIRTGPU "%s: the API Remoting backend library couldn't load the GGML backend library: apir code=%d | %s)", __func__, apir_ret, apir_load_library_error(apir_ret)); } else { uint32_t lib_ret = apir_ret - APIR_LOAD_LIBRARY_INIT_BASE_INDEX; GGML_ABORT(GGML_VIRTGPU "%s: the API Remoting backend library failed to initialize its backend library: apir code=%d)", __func__, lib_ret); } return ret;}
virtgpu * create_virtgpu() { virtgpu * gpu = new virtgpu();
gpu->use_apir_capset = getenv("GGML_REMOTING_USE_APIR_CAPSET") != nullptr; util_sparse_array_init(&gpu->shmem_array, sizeof(virtgpu_shmem), 1024);
// Initialize mutex to protect shared data_shmem buffer if (mtx_init(&gpu->data_shmem_mutex, mtx_plain) != thrd_success) { delete gpu; GGML_ABORT(GGML_VIRTGPU "%s: failed to initialize data_shmem mutex", __func__); return NULL; }
if (virtgpu_open(gpu) != APIR_SUCCESS) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: failed to open the virtgpu device\n", __func__); return NULL; }
if (virtgpu_init_capset(gpu) != APIR_SUCCESS) { if (gpu->use_apir_capset) { GGML_ABORT(GGML_VIRTGPU "%s: failed to initialize the virtgpu APIR capset. Make sure that the virglrenderer library " "supports it.", __func__); } else { GGML_ABORT(GGML_VIRTGPU "%s: failed to initialize the virtgpu Venus capset", __func__); } return NULL; }
if (virtgpu_init_context(gpu) != APIR_SUCCESS) { GGML_ABORT(GGML_VIRTGPU "%s: failed to initialize the GPU context", __func__); return NULL; }
if (virtgpu_shmem_create(gpu, SHMEM_REPLY_SIZE, &gpu->reply_shmem)) { GGML_ABORT(GGML_VIRTGPU "%s: failed to create the shared reply memory pages", __func__); return NULL; }
if (virtgpu_shmem_create(gpu, SHMEM_DATA_SIZE, &gpu->data_shmem)) { GGML_ABORT(GGML_VIRTGPU "%s: failed to create the shared data memory pages", __func__); return NULL; }
if (virtgpu_handshake(gpu)) { GGML_ABORT(GGML_VIRTGPU "%s: failed to handshake with the virglrenderer library", __func__); return NULL; }
if (virtgpu_load_library(gpu) != APIR_LOAD_LIBRARY_SUCCESS) { GGML_ABORT(GGML_VIRTGPU "%s: failed to load the backend library", __func__); return NULL; }
return gpu;}
static virt_gpu_result_t virtgpu_open(virtgpu * gpu) { drmDevicePtr devs[8]; int count = drmGetDevices2(0, devs, ARRAY_SIZE(devs)); if (count < 0) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: failed to enumerate DRM devices\n", __func__); return APIR_ERROR_INITIALIZATION_FAILED; }
virt_gpu_result_t result = APIR_ERROR_INITIALIZATION_FAILED; for (int i = 0; i < count; i++) { result = virtgpu_open_device(gpu, devs[i]); if (result == APIR_SUCCESS) { break; } }
drmFreeDevices(devs, count);
return result;}
static virt_gpu_result_t virtgpu_open_device(virtgpu * gpu, const drmDevicePtr dev) { const char * node_path = dev->nodes[DRM_NODE_RENDER];
int fd = open(node_path, O_RDWR | O_CLOEXEC); if (fd < 0) { GGML_ABORT(GGML_VIRTGPU "%s: failed to open %s", __func__, node_path); return APIR_ERROR_INITIALIZATION_FAILED; }
drmVersionPtr version = drmGetVersion(fd); if (!version || strcmp(version->name, "virtio_gpu") || version->version_major != 0) { if (version) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: unknown DRM driver %s version %d\n", __func__, version->name, version->version_major); } else { GGML_LOG_ERROR(GGML_VIRTGPU "%s: failed to get DRM driver version\n", __func__); }
if (version) { drmFreeVersion(version); } close(fd); return APIR_ERROR_INITIALIZATION_FAILED; }
gpu->fd = fd;
drmFreeVersion(version);
GGML_LOG_INFO(GGML_VIRTGPU "using DRM device %s\n", node_path);
return APIR_SUCCESS;}
static virt_gpu_result_t virtgpu_init_context(virtgpu * gpu) { assert(!gpu->capset.version); const int ret = virtgpu_ioctl_context_init(gpu, gpu->capset.id); if (ret) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: failed to initialize context: %s\n", __func__, strerror(errno)); return APIR_ERROR_INITIALIZATION_FAILED; }
return APIR_SUCCESS;}
static virt_gpu_result_t virtgpu_init_capset(virtgpu * gpu) { if (gpu->use_apir_capset) { GGML_LOG_INFO(GGML_VIRTGPU "Using the APIR capset\n"); gpu->capset.id = VIRTGPU_DRM_CAPSET_APIR; } else { GGML_LOG_INFO(GGML_VIRTGPU "Using the Venus capset\n"); gpu->capset.id = VIRTGPU_DRM_CAPSET_VENUS; } gpu->capset.version = 0;
int ret = virtgpu_ioctl_get_caps(gpu, gpu->capset.id, gpu->capset.version, &gpu->capset.data, sizeof(gpu->capset.data));
if (ret) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: failed to get APIR v%d capset: %s\n", __func__, gpu->capset.version, strerror(errno)); return APIR_ERROR_INITIALIZATION_FAILED; }
assert(gpu->capset.data.supports_blob_resources);
return APIR_SUCCESS;}
static int virtgpu_ioctl_context_init(virtgpu * gpu, virgl_renderer_capset capset_id) { drm_virtgpu_context_set_param ctx_set_params[3] = { { .param = VIRTGPU_CONTEXT_PARAM_CAPSET_ID, .value = capset_id, }, { .param = VIRTGPU_CONTEXT_PARAM_NUM_RINGS, .value = 1, }, { .param = VIRTGPU_CONTEXT_PARAM_POLL_RINGS_MASK, .value = 0, /* don't generate drm_events on fence signaling */ }, };
drm_virtgpu_context_init args = { .num_params = ARRAY_SIZE(ctx_set_params), .pad = 0, .ctx_set_params = (uintptr_t) &ctx_set_params, };
return virtgpu_ioctl(gpu, DRM_IOCTL_VIRTGPU_CONTEXT_INIT, &args);}
static int virtgpu_ioctl_get_caps(virtgpu * gpu, virgl_renderer_capset id, uint32_t version, void * capset, size_t capset_size) { drm_virtgpu_get_caps args = { .cap_set_id = id, .cap_set_ver = version, .addr = (uintptr_t) capset, .size = (__u32) capset_size, .pad = 0, };
return virtgpu_ioctl(gpu, DRM_IOCTL_VIRTGPU_GET_CAPS, &args);}
static uint64_t virtgpu_ioctl_getparam(virtgpu * gpu, uint64_t param) { /* val must be zeroed because kernel only writes the lower 32 bits */ uint64_t val = 0; drm_virtgpu_getparam args = { .param = param, .value = (uintptr_t) &val, };
const int ret = virtgpu_ioctl(gpu, DRM_IOCTL_VIRTGPU_GETPARAM, &args); return ret ? 0 : val;}
apir_encoder * remote_call_prepare(virtgpu * gpu, ApirCommandType apir_cmd_type, int32_t cmd_flags) { /* * Prepare the command encoder and its buffer */
thread_local char encoder_buffer[4096];
thread_local apir_encoder enc; enc = { .cur = encoder_buffer, .start = encoder_buffer, .end = encoder_buffer + sizeof(encoder_buffer), .fatal = false, };
/* * Fill the command encoder with the common args: * - cmd_type (int32_t) * - cmd_flags (int32_t) * - reply res id (uint32_t) */
int32_t cmd_type = apir_cmd_type;
// for testing during the hypervisor transition if (!gpu->use_apir_capset) { cmd_type += VENUS_COMMAND_TYPE_LENGTH; } apir_encode_int32_t(&enc, &cmd_type); apir_encode_int32_t(&enc, &cmd_flags);
uint32_t reply_res_id = gpu->reply_shmem.res_id; apir_encode_uint32_t(&enc, &reply_res_id);
return &enc;}
void remote_call_finish(virtgpu * gpu, apir_encoder * enc, apir_decoder * dec) { UNUSED(gpu);
if (!enc) { GGML_ABORT(GGML_VIRTGPU "%s: Invalid (null) encoder", __func__); }
if (!dec) { GGML_ABORT(GGML_VIRTGPU "%s: Invalid (null) decoder", __func__); }
if (apir_encoder_get_fatal(enc)) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: Failed to encode the output parameters.", __func__); }
if (apir_decoder_get_fatal(dec)) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: Failed to decode the input parameters.", __func__); }}
uint32_t remote_call(virtgpu * gpu, apir_encoder * encoder, apir_decoder ** decoder, float max_wait_ms, long long * call_duration_ns) { /* * Prepare the reply notification pointer */
volatile std::atomic_uint * atomic_reply_notif = (volatile std::atomic_uint *) gpu->reply_shmem.mmap_ptr; *atomic_reply_notif = 0;
/* * Trigger the execbuf ioctl */
drm_virtgpu_execbuffer args = { .flags = VIRTGPU_EXECBUF_RING_IDX, .size = (uint32_t) (encoder->cur - encoder->start), .command = (uintptr_t) encoder->start,
.bo_handles = 0, .num_bo_handles = 0,
.fence_fd = 0, .ring_idx = 0, .syncobj_stride = 0, .num_in_syncobjs = 0, .num_out_syncobjs = 0, .in_syncobjs = 0, .out_syncobjs = 0, };
*decoder = NULL;
int ret = drmIoctl(gpu->fd, DRM_IOCTL_VIRTGPU_EXECBUFFER, &args);
if (ret != 0) { GGML_ABORT(GGML_VIRTGPU "%s: the virtgpu EXECBUFFER ioctl failed (%d)", __func__, ret); }
/* * Wait for the response notification */ timer_data wait_host_reply_timer = { 0, 0, 0 };
start_timer(&wait_host_reply_timer);
timespec ts_start, ts_end; clock_gettime(CLOCK_MONOTONIC, &ts_start); long long start_time = (long long) ts_start.tv_sec * 1000000000LL + ts_start.tv_nsec;
bool timedout = false; uint32_t notif_value = 0; while (true) { notif_value = std::atomic_load_explicit(atomic_reply_notif, std::memory_order_acquire);
if (notif_value != 0) { break; }
int64_t base_sleep_us = 15;
os_time_sleep(base_sleep_us);
if (max_wait_ms) { clock_gettime(CLOCK_MONOTONIC, &ts_end); long long end_time = (long long) ts_end.tv_sec * 1000000000LL + ts_end.tv_nsec; float duration_ms = (end_time - start_time) / 1000000;
if (duration_ms > max_wait_ms) { timedout = true; break; } } }
if (call_duration_ns) { *call_duration_ns = stop_timer(&wait_host_reply_timer); }
if (max_wait_ms && timedout) { GGML_LOG_ERROR(GGML_VIRTGPU "%s: timed out waiting for the host answer...\n", __func__); return APIR_FORWARD_TIMEOUT; }
/* * Prepare the decoder */ static apir_decoder response_dec; response_dec.cur = (char *) gpu->reply_shmem.mmap_ptr + sizeof(*atomic_reply_notif); response_dec.end = (char *) gpu->reply_shmem.mmap_ptr + gpu->reply_shmem.mmap_size; *decoder = &response_dec;
// extract the actual return value from the notif flag uint32_t returned_value = notif_value - 1; return returned_value;}
static void log_call_duration(long long call_duration_ns, const char * name) { double call_duration_ms = (double) call_duration_ns / 1e6; // 1 millisecond = 1e6 nanoseconds double call_duration_s = (double) call_duration_ns / 1e9; // 1 second = 1e9 nanoseconds
if (call_duration_s > 1) { GGML_LOG_INFO(GGML_VIRTGPU "waited %.2fs for the %s host reply...\n", call_duration_s, name); } else if (call_duration_ms > 1) { GGML_LOG_INFO(GGML_VIRTGPU "waited %.2fms for the %s host reply...\n", call_duration_ms, name); } else { GGML_LOG_INFO(GGML_VIRTGPU "waited %lldns for the %s host reply...\n", call_duration_ns, name); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115#pragma once
// clang-format off#include "virtgpu-utils.h"#include "virtgpu-shm.h"#include "virtgpu-apir.h"
#include "backend/shared/api_remoting.h"#include "backend/shared/apir_cs.h"
#include <fcntl.h>#include <stdbool.h>#include <stdio.h>#include <sys/stat.h>#include <sys/sysmacros.h>#include <threads.h>#include <xf86drm.h>
#include <cstring>
#define VIRGL_RENDERER_UNSTABLE_APIS 1#include "apir_hw.h"#include <drm/virtgpu_drm.h>#include "venus_hw.h"// clang-format on
#ifndef VIRTGPU_DRM_CAPSET_APIR// Will be defined include/drm/virtgpu_drm.h when// https://gitlab.freedesktop.org/virgl/virglrenderer/-/merge_requests/1590/diffs// is merged# define VIRTGPU_DRM_CAPSET_APIR 10#endif
// Mesa/Virlgrenderer Venus internal. Only necessary during the// Venus->APIR transition in Virglrenderer#define VENUS_COMMAND_TYPE_LENGTH 331
#ifndef VIRTGPU_DRM_CAPSET_VENUS // only available with Linux >= v6.16# define VIRTGPU_DRM_CAPSET_VENUS 4#endif
typedef uint32_t virgl_renderer_capset;
/* from src/virtio/vulkan/vn_renderer_virtgpu.c */#define VIRTGPU_PCI_VENDOR_ID 0x1af4#define VIRTGPU_PCI_DEVICE_ID 0x1050#define VIRTGPU_BLOB_MEM_GUEST_VRAM 0x0004#define VIRTGPU_PARAM_GUEST_VRAM 9
#define SHMEM_DATA_SIZE 0x1830000 // 24MiB#define SHMEM_REPLY_SIZE 0x4000
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
enum virt_gpu_result_t { APIR_SUCCESS = 0, APIR_ERROR_INITIALIZATION_FAILED = -1,};
#define PRINTFLIKE(f, a) __attribute__((format(__printf__, f, a)))
struct virtgpu { bool use_apir_capset;
int fd;
struct { virgl_renderer_capset id; uint32_t version; virgl_renderer_capset_apir data; } capset;
util_sparse_array shmem_array;
/* APIR communication pages */ virtgpu_shmem reply_shmem; virtgpu_shmem data_shmem;
/* Mutex to protect shared data_shmem buffer from concurrent access */ mtx_t data_shmem_mutex;
/* Cached device information to prevent memory leaks and race conditions */ struct { char * description; char * name; int32_t device_count; uint32_t type; size_t memory_free; size_t memory_total; } cached_device_info;
/* Cached buffer type information to prevent memory leaks and race conditions */ struct { apir_buffer_type_host_handle_t host_handle; char * name; size_t alignment; size_t max_size; } cached_buffer_type;};
static inline int virtgpu_ioctl(virtgpu * gpu, unsigned long request, void * args) { return drmIoctl(gpu->fd, request, args);}
virtgpu * create_virtgpu();
apir_encoder * remote_call_prepare(virtgpu * gpu, ApirCommandType apir_cmd_type, int32_t cmd_flags);
uint32_t remote_call(virtgpu * gpu, apir_encoder * enc, apir_decoder ** dec, float max_wait_ms, long long * call_duration_ns);
void remote_call_finish(virtgpu * gpu, apir_encoder * enc, apir_decoder * dec);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236cmake_minimum_required(VERSION 3.19)cmake_policy(SET CMP0114 NEW)cmake_policy(SET CMP0116 NEW)if (POLICY CMP0147) # Parallel build custom build steps cmake_policy(SET CMP0147 NEW)endif()
find_package(Vulkan COMPONENTS glslc REQUIRED)
if (DEFINED ENV{VULKAN_SDK}) list(APPEND CMAKE_PREFIX_PATH "$ENV{VULKAN_SDK}")endif()find_package(SPIRV-Headers CONFIG REQUIRED)
if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") # Parallel build object files add_definitions(/MP)endif()
function(detect_host_compiler) if (CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") find_program(HOST_C_COMPILER NAMES cl gcc clang NO_CMAKE_FIND_ROOT_PATH) find_program(HOST_CXX_COMPILER NAMES cl g++ clang++ NO_CMAKE_FIND_ROOT_PATH) else() find_program(HOST_C_COMPILER NAMES gcc clang NO_CMAKE_FIND_ROOT_PATH) find_program(HOST_CXX_COMPILER NAMES g++ clang++ NO_CMAKE_FIND_ROOT_PATH) endif() set(HOST_C_COMPILER "${HOST_C_COMPILER}" PARENT_SCOPE) set(HOST_CXX_COMPILER "${HOST_CXX_COMPILER}" PARENT_SCOPE)endfunction()
# Function to test shader extension support# Parameters:# EXTENSION_NAME - Name of the extension to test (e.g., "GL_EXT_integer_dot_product")# TEST_SHADER_FILE - Path to the test shader file# RESULT_VARIABLE - Name of the variable to set (ON/OFF) based on test resultfunction(test_shader_extension_support EXTENSION_NAME TEST_SHADER_FILE RESULT_VARIABLE) execute_process( COMMAND ${Vulkan_GLSLC_EXECUTABLE} -o - -fshader-stage=compute --target-env=vulkan1.3 "${TEST_SHADER_FILE}" OUTPUT_VARIABLE glslc_output ERROR_VARIABLE glslc_error )
if (${glslc_error} MATCHES ".*extension not supported: ${EXTENSION_NAME}.*") message(STATUS "${EXTENSION_NAME} not supported by glslc") set(${RESULT_VARIABLE} OFF PARENT_SCOPE) else() message(STATUS "${EXTENSION_NAME} supported by glslc") set(${RESULT_VARIABLE} ON PARENT_SCOPE) add_compile_definitions(${RESULT_VARIABLE})
# Ensure the extension support is forwarded to vulkan-shaders-gen list(APPEND VULKAN_SHADER_GEN_CMAKE_ARGS -D${RESULT_VARIABLE}=ON) set(VULKAN_SHADER_GEN_CMAKE_ARGS "${VULKAN_SHADER_GEN_CMAKE_ARGS}" PARENT_SCOPE) endif()endfunction()
if (Vulkan_FOUND) message(STATUS "Vulkan found")
ggml_add_backend_library(ggml-vulkan ggml-vulkan.cpp ../../include/ggml-vulkan.h )
set(VULKAN_SHADER_GEN_CMAKE_ARGS "")
# Test all shader extensions test_shader_extension_support( "GL_KHR_cooperative_matrix" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/coopmat.comp" "GGML_VULKAN_COOPMAT_GLSLC_SUPPORT" )
test_shader_extension_support( "GL_NV_cooperative_matrix2" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/coopmat2.comp" "GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT" )
test_shader_extension_support( "GL_NV_cooperative_matrix_decode_vector" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/coopmat2_decode_vector.comp" "GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT" )
test_shader_extension_support( "GL_EXT_integer_dot_product" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/integer_dot.comp" "GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT" )
test_shader_extension_support( "GL_EXT_bfloat16" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/bfloat16.comp" "GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT" )
target_link_libraries(ggml-vulkan PRIVATE Vulkan::Vulkan) target_include_directories(ggml-vulkan PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
# Workaround to the "can't dereference invalidated vector iterator" bug in clang-cl debug build # Possibly relevant: https://stackoverflow.com/questions/74748276/visual-studio-no-displays-the-correct-length-of-stdvector if (MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang") add_compile_definitions(_ITERATOR_DEBUG_LEVEL=0) endif()
if (GGML_VULKAN_CHECK_RESULTS) add_compile_definitions(GGML_VULKAN_CHECK_RESULTS) # the result-checking path computes a CPU reference graph via # ggml_graph_compute_with_ctx(), which is defined in ggml-cpu target_link_libraries(ggml-vulkan PRIVATE ggml-cpu) endif()
if (GGML_VULKAN_DEBUG) add_compile_definitions(GGML_VULKAN_DEBUG) endif()
if (GGML_VULKAN_MEMORY_DEBUG) add_compile_definitions(GGML_VULKAN_MEMORY_DEBUG) endif()
if (GGML_VULKAN_SHADER_DEBUG_INFO) add_compile_definitions(GGML_VULKAN_SHADER_DEBUG_INFO) list(APPEND VULKAN_SHADER_GEN_CMAKE_ARGS -DGGML_VULKAN_SHADER_DEBUG_INFO=ON) endif()
if (GGML_VULKAN_VALIDATE) add_compile_definitions(GGML_VULKAN_VALIDATE) endif()
if (GGML_VULKAN_RUN_TESTS) add_compile_definitions(GGML_VULKAN_RUN_TESTS) # the test path also calls ggml_graph_compute_with_ctx() (ggml-cpu) target_link_libraries(ggml-vulkan PRIVATE ggml-cpu) endif()
# Set up toolchain for host compilation whether cross-compiling or not if (CMAKE_CROSSCOMPILING) if (GGML_VULKAN_SHADERS_GEN_TOOLCHAIN) set(HOST_CMAKE_TOOLCHAIN_FILE ${GGML_VULKAN_SHADERS_GEN_TOOLCHAIN}) else() detect_host_compiler() if (NOT HOST_C_COMPILER OR NOT HOST_CXX_COMPILER) message(FATAL_ERROR "Host compiler not found") else() message(STATUS "Host compiler: ${HOST_C_COMPILER} ${HOST_CXX_COMPILER}") endif() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/host-toolchain.cmake.in ${CMAKE_BINARY_DIR}/host-toolchain.cmake @ONLY) set(HOST_CMAKE_TOOLCHAIN_FILE ${CMAKE_BINARY_DIR}/host-toolchain.cmake) endif() else() # For non-cross-compiling, use empty toolchain (use host compiler) set(HOST_CMAKE_TOOLCHAIN_FILE "") endif()
include(ExternalProject)
if (CMAKE_CROSSCOMPILING) list(APPEND VULKAN_SHADER_GEN_CMAKE_ARGS -DCMAKE_TOOLCHAIN_FILE=${HOST_CMAKE_TOOLCHAIN_FILE}) message(STATUS "vulkan-shaders-gen toolchain file: ${HOST_CMAKE_TOOLCHAIN_FILE}") endif()
ExternalProject_Add( vulkan-shaders-gen SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/$<CONFIG> -DCMAKE_INSTALL_BINDIR=. -DCMAKE_BUILD_TYPE=$<CONFIG> ${VULKAN_SHADER_GEN_CMAKE_ARGS}
BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG> BUILD_ALWAYS TRUE
# NOTE: When DESTDIR is set using Makefile generators and # "make install" triggers the build step, vulkan-shaders-gen # would be installed into the DESTDIR prefix, so it is unset # to ensure that does not happen.
INSTALL_COMMAND ${CMAKE_COMMAND} -E env --unset=DESTDIR ${CMAKE_COMMAND} --install . --config $<CONFIG> )
set (_ggml_vk_host_suffix $<IF:$<STREQUAL:${CMAKE_HOST_SYSTEM_NAME},Windows>,.exe,>) set (_ggml_vk_genshaders_dir "${CMAKE_BINARY_DIR}/$<CONFIG>") set (_ggml_vk_genshaders_cmd "${_ggml_vk_genshaders_dir}/vulkan-shaders-gen${_ggml_vk_host_suffix}") set (_ggml_vk_header "${CMAKE_CURRENT_BINARY_DIR}/ggml-vulkan-shaders.hpp") set (_ggml_vk_input_dir "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders") set (_ggml_vk_output_dir "${CMAKE_CURRENT_BINARY_DIR}/vulkan-shaders.spv")
file(GLOB _ggml_vk_shader_files CONFIGURE_DEPENDS "${_ggml_vk_input_dir}/*.comp")
# Because external projects do not provide source-level tracking, # the vulkan-shaders-gen sources need to be explicitly added to # ensure that changes will cascade into shader re-generation.
file(GLOB _ggml_vk_shaders_gen_sources CONFIGURE_DEPENDS "${_ggml_vk_input_dir}/*.cpp" "${_ggml_vk_input_dir}/*.h")
add_custom_command( OUTPUT ${_ggml_vk_header} COMMAND ${_ggml_vk_genshaders_cmd} --output-dir ${_ggml_vk_output_dir} --target-hpp ${_ggml_vk_header} DEPENDS ${_ggml_vk_shaders_gen_sources} vulkan-shaders-gen COMMENT "Generate vulkan shaders header" ) target_sources(ggml-vulkan PRIVATE ${_ggml_vk_header})
foreach (file_full ${_ggml_vk_shader_files}) get_filename_component(file ${file_full} NAME) set (_ggml_vk_target_cpp "${CMAKE_CURRENT_BINARY_DIR}/${file}.cpp")
add_custom_command( OUTPUT ${_ggml_vk_target_cpp} DEPFILE ${_ggml_vk_target_cpp}.d COMMAND ${_ggml_vk_genshaders_cmd} --glslc ${Vulkan_GLSLC_EXECUTABLE} --source ${file_full} --output-dir ${_ggml_vk_output_dir} --target-hpp ${_ggml_vk_header} --target-cpp ${_ggml_vk_target_cpp} DEPENDS ${file_full} ${_ggml_vk_shaders_gen_sources} vulkan-shaders-gen COMMENT "Generate vulkan shaders for ${file}" ) target_sources(ggml-vulkan PRIVATE ${_ggml_vk_target_cpp}) endforeach()
else() message(WARNING "Vulkan not found")endif()123456789101112131415set(CMAKE_BUILD_TYPE Release)set(CMAKE_C_FLAGS -O2)set(CMAKE_CXX_FLAGS -O2)set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER)set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER)set(CMAKE_C_COMPILER "@HOST_C_COMPILER@")set(CMAKE_CXX_COMPILER "@HOST_CXX_COMPILER@")set(CMAKE_RUNTIME_OUTPUT_DIRECTORY @CMAKE_RUNTIME_OUTPUT_DIRECTORY@)
if("@CMAKE_C_COMPILER_ID@" STREQUAL "MSVC") foreach(CONFIG IN ITEMS DEBUG RELEASE MINSIZEREL RELWITHDEBINFO) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) endforeach()endif()1234567891011121314151617181920212223242526272829303132333435cmake_minimum_required(VERSION 3.19)project("vulkan-shaders-gen" C CXX)
find_package (Threads REQUIRED)
if (GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) message(STATUS "Enabling coopmat glslc support")endif()if (GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) message(STATUS "Enabling coopmat2 glslc support")endif()if (GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) message(STATUS "Enabling coopmat2 decode_vector glslc support")endif()if (GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) message(STATUS "Enabling dot glslc support")endif()if (GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) message(STATUS "Enabling bfloat16 glslc support")endif()if (GGML_VULKAN_SHADER_DEBUG_INFO) add_compile_definitions(GGML_VULKAN_SHADER_DEBUG_INFO) message(STATUS "Enabling shader debug info")endif()
set(TARGET vulkan-shaders-gen)add_executable(${TARGET} vulkan-shaders-gen.cpp)install(TARGETS ${TARGET} RUNTIME)target_compile_features(${TARGET} PRIVATE cxx_std_17)target_link_libraries(vulkan-shaders-gen PUBLIC Threads::Threads)12345678910111213141516171819202122232425262728293031323334353637#version 450
#include "types.glsl"#include "generic_binary_head.glsl"
// false for SET, true for ACClayout(constant_id = 1) const bool ACC = true;
layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
void main() { const uint idx = gl_GlobalInvocationID.x; if (idx >= p.ne) { return; }
const uint offset = p.param3; const uint src1_i = idx - offset; const uint i3 = src1_i / p.nb03; const uint rem2 = src1_i - i3 * p.nb03; const uint i2 = rem2 / p.nb02; const uint rem1 = rem2 - i2 * p.nb02; const uint i1 = rem1 / p.nb01; const uint i0 = rem1 % p.nb01;
uint i00, i01, i02, i03;
if (i0 < p.ne10 && i1 < p.ne11 && i2 < p.ne12 && i3 < p.ne13) { if (ACC) { data_d[get_doffset() + idx] = D_TYPE(FLOAT_TYPE(data_a[get_aoffset() + idx]) + FLOAT_TYPE(data_b[get_boffset() + src1_idx(i0, i1, i2, i3)])); } else { data_d[get_doffset() + idx] = D_TYPE(FLOAT_TYPE(data_b[get_boffset() + src1_idx(i0, i1, i2, i3)])); } } else { data_d[get_doffset() + idx] = D_TYPE(FLOAT_TYPE(data_a[get_aoffset() + idx])); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#version 450
#extension GL_EXT_shader_16bit_storage : require#if ADD_RMS#extension GL_KHR_shader_subgroup_arithmetic : enable#extension GL_KHR_shader_subgroup_basic : enable#endif
#include "types.glsl"#include "generic_binary_head.glsl"
const uint num_threads = 256;
layout (binding = 3, std430) buffer PartialBuf {float partial_sums[];};
layout(local_size_x = num_threads, local_size_y = 1, local_size_z = 1) in;
#if ADD_RMS// XXX TODO this could be sized based on number of subgroups, but that't not considered a constantshared FLOAT_TYPE sumsh[num_threads];#endif
void main() { uint idx = get_idx(); uint orig_idx = idx;
// num_threads * num_iter must equal 512, to match the wg_denoms and get_idx calculation const uint num_iter = 2;
FLOAT_TYPE sum_sq = 0;
[[unroll]] for (uint i = 0; i < num_iter; ++i) { if (idx >= p.ne) { continue; } uint i00, i01, i02, i03; get_indices(idx, i00, i01, i02, i03);
FLOAT_TYPE sum = FLOAT_TYPE(data_a[get_aoffset() + src0_idx(i00, i01, i02, i03)]) + FLOAT_TYPE(data_b[get_boffset() + src1_idx(i00, i01, i02, i03)]); sum_sq += sum*sum;
data_d[get_doffset() + dst_idx(i00, i01, i02, i03)] = D_TYPE(sum);
idx += num_threads; }
#if ADD_RMS if (p.param3 != 0) { // reduce the sum within each subgroup, then across subgroups const uint NumSubgroups = num_threads / gl_SubgroupSize; sum_sq = subgroupAdd(sum_sq); if (gl_SubgroupInvocationID == 0) { sumsh[gl_SubgroupID] = sum_sq; } barrier(); [[unroll]] for (uint s = NumSubgroups / 2; s > 0; s >>= 1) { if (gl_SubgroupID < s && gl_SubgroupInvocationID == 0) { sum_sq += sumsh[gl_SubgroupID + s]; sumsh[gl_SubgroupID] = sum_sq; } barrier(); }
if (gl_SubgroupID == 0 && gl_SubgroupInvocationID == 0) { partial_sums[orig_idx / (num_iter * num_threads)] = sum_sq; } }#endif}12345678910111213141516171819202122232425262728#version 450
#extension GL_EXT_shader_16bit_storage : require
#include "types.glsl"#include "generic_binary_head.glsl"
const uint num_threads = 256;
layout(local_size_x = num_threads, local_size_y = 1, local_size_z = 1) in;
void main() { uint idx = get_idx();
const uint num_iter = 2;
[[unroll]] for (uint i = 0; i < num_iter; ++i) { if (idx >= p.ne) { continue; } uint i00, i01, i02, i03; get_indices(idx, i00, i01, i02, i03);
data_d[get_doffset() + dst_idx(i00, i01, i02, i03)] = D_TYPE(FLOAT_TYPE(data_a[get_aoffset() + src0_idx(i00, i01, i02, i03)]) + FLOAT_TYPE(data_b[get_boffset()]));
idx += num_threads; }}123456789101112131415161718192021222324252627282930313233343536373839404142#version 450
#extension GL_EXT_control_flow_attributes : require
#include "types.glsl"
layout (push_constant) uniform parameter{ uint ne0; uint ne1; uint s01; uint s02; uint s11; uint s21;} p;
#define BLOCK_SIZE 512
layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer X {A_TYPE data_a[];};layout (binding = 1) readonly buffer Y {B_TYPE data_b[];};layout (binding = 2) readonly buffer Z {int32_t data_c[];};layout (binding = 3) writeonly buffer D {D_TYPE data_d[];};
void main() { const uint i1 = gl_WorkGroupID.x; const uint i2 = gl_WorkGroupID.y;
const uint i11 = data_c[i1 + i2 * p.s21];
const uint s1 = p.ne0; const uint s2 = p.ne0 * p.ne1;
const uint d0 = i1 * s1 + i2 * s2; const uint a0 = i1 * p.s01 + i2 * p.s02; const uint b0 = i11 * p.s11;
for (uint i0 = gl_LocalInvocationID.x; i0 < p.ne0; i0 += BLOCK_SIZE) { data_d[d0 + i0] = data_a[a0 + i0] + data_b[b0 + i0]; }}1234567891011121314151617181920#version 450
#include "generic_head.glsl"#include "types.glsl"
layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) writeonly buffer D {D_TYPE data_d[];};
void main() { const uint i = gl_GlobalInvocationID.x;
if (i >= p.KX) { return; }
// p.param1 = start, p.param2 = step float value = p.param1 + p.param2 * float(i); data_d[i] = D_TYPE(value);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960#version 450
#include "generic_head.glsl"#include "types.glsl"
#extension GL_EXT_control_flow_attributes : enable
#define FLT_MAX 3.402823466e+38F
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
layout (constant_id = 0) const uint BLOCK_SIZE = 32;
shared FLOAT_TYPE tmpmax[BLOCK_SIZE];shared uint tmp[BLOCK_SIZE];
void main() { const uint row = gl_WorkGroupID.z * 262144 + gl_WorkGroupID.y * 512 + gl_WorkGroupID.x; const uint col = gl_LocalInvocationID.x;
if (row >= p.KY) { return; }
A_TYPE amax = -FLT_MAX; uint acol = col;
if (col < p.KX) { amax = data_a[row*p.KX + col]; }
for (uint i = col + BLOCK_SIZE; i < p.KX; i += BLOCK_SIZE) { A_TYPE val = data_a[row*p.KX + i]; if (val > amax) { amax = val; acol = i; } }
tmp[col] = acol; tmpmax[col] = amax;
barrier(); [[unroll]] for (int s = int(BLOCK_SIZE) / 2; s > 0; s >>= 1) { if (col < s && col + s < p.KX) { if (tmpmax[col] < tmpmax[col + s]) { tmpmax[col] = tmpmax[col + s]; tmp[col] = tmp[col + s]; } } barrier(); }
if (col == 0) { data_d[row] = D_TYPE(tmp[0]); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586#version 450#extension GL_EXT_control_flow_attributes : enable
#include "types.glsl"
layout(constant_id = 0) const int BLOCK_SIZE = 1024;layout(constant_id = 1) const int NCOLS_PADDED_LOG2 = 10;#define ASC 0
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};layout (binding = 2) writeonly buffer D {int data_d[];};
layout (push_constant) uniform parameter { uint ncols; uint ncols_padded; uint ncols_padded_log2; uint nrows; uint order; uint outer_start; uint outer_end; uint inner_start; uint inner_end;} p;
shared ivec2 dst_row[BLOCK_SIZE];
void argsort(bool needs_bounds_check, const uint row) { // bitonic sort const int col = int(gl_LocalInvocationID.x);
const uint row_offset = row * p.ncols;
// initialize indices dst_row[col] = ivec2(col, floatBitsToInt(data_a[row_offset + col])); barrier();
uint num_outer_loop_iters = NCOLS_PADDED_LOG2; [[unroll]] for (uint k = 2, outer_idx = 0; outer_idx < num_outer_loop_iters; k *= 2, outer_idx++) { uint num_inner_loop_iters = outer_idx + 1; [[unroll]] for (uint j = k / 2, inner_idx = 0; inner_idx < num_inner_loop_iters; j /= 2, inner_idx++) { const int ixj = int(col ^ j);
int idx_0 = (col & k) == 0 ? col : ixj; int idx_1 = (col & k) == 0 ? ixj : col;
ivec2 sh_idx_0 = dst_row[idx_0]; ivec2 sh_idx_1 = dst_row[idx_1]; bool idx_0_oob = needs_bounds_check ? sh_idx_0.x >= p.ncols : false; bool idx_1_oob = needs_bounds_check ? sh_idx_1.x >= p.ncols : false;
if ((idx_0_oob || (!idx_1_oob && intBitsToFloat(sh_idx_0.y) > intBitsToFloat(sh_idx_1.y))) && (ixj > col)) { dst_row[idx_0] = sh_idx_1; dst_row[idx_1] = sh_idx_0; }
barrier(); } }
if (col < p.ncols) { if (p.order == ASC) { data_d[row_offset + col] = dst_row[col].x; } else { data_d[row_offset + p.ncols - col - 1] = dst_row[col].x; } }}
void main() { if (p.ncols == BLOCK_SIZE) { uint row = gl_WorkGroupID.y; while (row < p.nrows) { argsort(false, row); row += gl_WorkGroupSize.y * gl_NumWorkGroups.y; } } else { uint row = gl_WorkGroupID.y; while (row < p.nrows) { argsort(true, row); row += gl_WorkGroupSize.y * gl_NumWorkGroups.y; } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114#version 450#extension GL_EXT_control_flow_attributes : enable#extension GL_KHR_memory_scope_semantics : enable#pragma use_vulkan_memory_model
#include "types.glsl"
layout(constant_id = 0) const int BLOCK_SIZE = 1024;layout(constant_id = 1) const int WG_UNROLL_FACTOR = 2;#define ASC 0
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};layout (binding = 1) workgroupcoherent buffer B {ivec2 tmp_idx[];};layout (binding = 2) workgroupcoherent buffer D {int data_d[];};
layout (push_constant) uniform parameter { uint ncols; uint ncols_padded; uint ncols_padded_log2; uint nrows; uint order; uint outer_start; uint outer_end; uint inner_start; uint inner_end;} p;
void argsort(bool needs_bounds_check, const uint row) { // bitonic sort int col = int(gl_GlobalInvocationID.x); col = (col % BLOCK_SIZE) + (col / BLOCK_SIZE) * BLOCK_SIZE * WG_UNROLL_FACTOR;
const uint row_offset = row * p.ncols; uint idx_offset = row * p.ncols_padded;
bool need_barrier = false;
// initialize indices if (p.outer_start == 0 && p.inner_start == 0) { [[unroll]] for (int u = 0; u < WG_UNROLL_FACTOR; ++u) { uint c = u*BLOCK_SIZE + col; if (c < p.ncols_padded) { ivec2 v = ivec2(c, floatBitsToInt(data_a[row_offset + c])); tmp_idx[idx_offset + c] = v; } } need_barrier = true; }
[[unroll]] for (uint outer_idx = p.outer_start, k = (2 << outer_idx); outer_idx < p.outer_end; k *= 2, outer_idx++) { uint inner_end = min(p.inner_end, outer_idx + 1); for (uint j = k >> (p.inner_start + 1), inner_idx = p.inner_start; inner_idx < inner_end; j /= 2, inner_idx++) { if (need_barrier) { controlBarrier(gl_ScopeWorkgroup, gl_ScopeWorkgroup, gl_StorageSemanticsBuffer, gl_SemanticsAcquireRelease); } need_barrier = true; [[unroll]] for (int u = 0; u < WG_UNROLL_FACTOR; ++u) { int c = u*BLOCK_SIZE + col; const int ixj = int(c ^ j);
if (ixj < c) { continue; }
int idx_0 = (c & k) == 0 ? c : ixj; int idx_1 = (c & k) == 0 ? ixj : c;
ivec2 sh_idx_0 = tmp_idx[idx_offset + idx_0]; ivec2 sh_idx_1 = tmp_idx[idx_offset + idx_1]; bool idx_0_oob = needs_bounds_check ? sh_idx_0.x >= p.ncols : false; bool idx_1_oob = needs_bounds_check ? sh_idx_1.x >= p.ncols : false;
if ((idx_0_oob || (!idx_1_oob && intBitsToFloat(sh_idx_0.y) > intBitsToFloat(sh_idx_1.y)))) { tmp_idx[idx_offset + idx_0] = sh_idx_1; tmp_idx[idx_offset + idx_1] = sh_idx_0; } } } }
if (p.outer_end == p.ncols_padded_log2 && p.inner_end >= p.ncols_padded_log2 + 1) { controlBarrier(gl_ScopeWorkgroup, gl_ScopeWorkgroup, gl_StorageSemanticsBuffer, gl_SemanticsAcquireRelease); [[unroll]] for (int u = 0; u < WG_UNROLL_FACTOR; ++u) { uint c = u*BLOCK_SIZE + col; if (c < p.ncols) { if (p.order == ASC) { data_d[row_offset + c] = tmp_idx[idx_offset + c].x; } else { data_d[row_offset + p.ncols - c - 1] = tmp_idx[idx_offset + c].x; } } } }}
void main() { if (p.ncols == p.ncols_padded) { uint row = gl_WorkGroupID.y; while (row < p.nrows) { argsort(false, row); row += gl_WorkGroupSize.y * gl_NumWorkGroups.y; } } else { uint row = gl_WorkGroupID.y; while (row < p.nrows) { argsort(true, row); row += gl_WorkGroupSize.y * gl_NumWorkGroups.y; } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#version 450
#include "types.glsl"
layout (binding = 0) readonly buffer A {A_TYPE data_a[];}; // columns: [K_OC, T_in]layout (binding = 1) writeonly buffer D {D_TYPE data_d[];}; // output: [T_out, OC]
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
layout (push_constant) uniform parameter { uint32_t T_out; uint32_t OC; uint32_t K_OC; uint32_t T_in; uint32_t K; int32_t stride; int32_t p0;} p;
// Load A_TYPE to floatfloat load_col(uint32_t idx) {#if defined(DATA_A_BF16) return bf16_to_fp32(uint32_t(data_a[idx]));#else return float(data_a[idx]);#endif}
// Store float as D_TYPEvoid store_dst(uint32_t idx, float v) {#if defined(DATA_A_BF16) data_d[idx] = D_TYPE(fp32_to_bf16(v));#else data_d[idx] = D_TYPE(v);#endif}
void main() { const uint32_t t_out = gl_GlobalInvocationID.x; const uint32_t oc = gl_GlobalInvocationID.y; if (t_out >= p.T_out || oc >= p.OC) return;
const int32_t t_abs = int32_t(t_out) + p.p0; // absolute position in uncropped signal
// Gather: only the ceil(K/stride) columns that scatter into t_abs, no modulo int32_t t_in_min = (t_abs - int32_t(p.K) + p.stride) / p.stride; if (t_in_min < 0) t_in_min = 0; int32_t t_in_max = t_abs / p.stride; if (t_in_max >= int32_t(p.T_in)) t_in_max = int32_t(p.T_in) - 1;
float val = 0.0; for (int32_t t_in = t_in_min; t_in <= t_in_max; t_in++) { int32_t k = t_abs - t_in * p.stride; // col layout: [K_OC, T_in], column index = oc * K + k uint32_t col_idx = (oc * p.K + uint32_t(k)) + uint32_t(t_in) * p.K_OC; val += load_col(col_idx); }
// dst layout: [T_out, OC], element (t_out, oc) = t_out + oc * T_out store_dst(t_out + oc * p.T_out, val);}1234567891011121314151617181920212223242526272829303132333435363738394041#version 450
#include "types.glsl"#include "generic_binary_head.glsl"
layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
void main() { const uint idx = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x; const int dim = p.param3;
if (idx >= p.ne) { return; }
const uint i3 = idx / (p.ne22*p.ne21*p.ne20); const uint i3_offset = i3 * p.ne22*p.ne21*p.ne20; const uint i2 = (idx - i3_offset) / (p.ne21*p.ne20); const uint i2_offset = i2*p.ne21*p.ne20; const uint i1 = (idx - i3_offset - i2_offset) / p.ne20; const uint i0 = idx - i3_offset - i2_offset - i1*p.ne20;
uint o[4] = {0, 0, 0, 0}; o[dim] = dim == 0 ? p.ne00 : (dim == 1 ? p.ne01 : (dim == 2 ? p.ne02 : p.ne03));
const uint src0_idx = i3*p.nb03 + i2*p.nb02 + i1*p.nb01 + i0*p.nb00; const uint src1_idx = (i3 - o[3])*p.nb13 + (i2 - o[2])*p.nb12 + (i1 - o[1])*p.nb11 + (i0 - o[0])*p.nb10; const uint dst_idx = i3*p.nb23 + i2*p.nb22 + i1*p.nb21 + i0*p.nb20;
const bool is_src0 = i0 < p.ne00 && i1 < p.ne01 && i2 < p.ne02 && i3 < p.ne03;
#ifndef OPTIMIZATION_ERROR_WORKAROUND data_d[get_doffset() + dst_idx] = D_TYPE(is_src0 ? data_a[get_aoffset() + src0_idx] : data_b[get_boffset() + src1_idx]);#else if (is_src0) { data_d[get_doffset() + dst_idx] = data_a[get_aoffset() + src0_idx]; } else { data_d[get_doffset() + dst_idx] = data_b[get_boffset() + src1_idx]; }#endif}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#version 450
#include "types.glsl"#include "generic_unary_head.glsl"
#extension GL_EXT_control_flow_attributes : require
const uint num_threads = 128;
layout(local_size_x = num_threads, local_size_y = 1, local_size_z = 1) in;
void main() { uint idx = get_idx();
// num_threads * num_iter must equal 512, to match the wg_denoms and get_idx calculation const uint num_iter = 4;
// fast path for when all four iterations are in-bounds if (idx + (num_iter-1)*num_threads < p.ne) { [[unroll]] for (uint i = 0; i < num_iter; ++i) {
#if defined(DATA_A_BF16) data_d[get_doffset() + idx] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + idx])));#elif defined(DATA_D_BF16) float f = float(data_a[get_aoffset() + idx]); data_d[get_doffset() + idx] = D_TYPE(fp32_to_bf16(f));#elif !defined(OPTIMIZATION_ERROR_WORKAROUND) data_d[get_doffset() + idx] = D_TYPE(data_a[get_aoffset() + idx]);#else data_d[get_doffset() + idx] = data_a[get_aoffset() + idx];#endif idx += num_threads; } } else { [[unroll]] for (uint i = 0; i < num_iter; ++i) { if (idx >= p.ne) { continue; }
#if defined(DATA_A_BF16) data_d[get_doffset() + idx] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + idx])));#elif defined(DATA_D_BF16) float f = float(data_a[get_aoffset() + idx]); data_d[get_doffset() + idx] = D_TYPE(fp32_to_bf16(f));#elif !defined(OPTIMIZATION_ERROR_WORKAROUND) data_d[get_doffset() + idx] = D_TYPE(data_a[get_aoffset() + idx]);#else data_d[get_doffset() + idx] = data_a[get_aoffset() + idx];#endif idx += num_threads; } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105#version 450
#include "types.glsl"
layout (push_constant) uniform parameter{ uint ne; uint batches; uint channels; uint dst_w; uint dst_h; uint src_w; uint src_h; uint knl_w; uint knl_h; int stride_x; int stride_y; int pad_x; int pad_y; int dilation_x; int dilation_y;} p;
layout (binding = 0) readonly buffer A {A_TYPE knl_data[];};layout (binding = 1) readonly buffer B {B_TYPE src_data[];};layout (binding = 2) writeonly buffer D {D_TYPE dst_data[];};
layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
FLOAT_TYPE conv_2d_dw_whcn(uint idx) { uint i0 = idx / p.dst_w; uint dst_x = idx - i0 * p.dst_w; uint i1 = i0 / p.dst_h; uint dst_y = i0 - i1 * p.dst_h; uint n = i1 / p.channels; uint c = i1 - n * p.channels;
uint src_i = n * p.channels * p.src_h * p.src_w + c * p.src_h * p.src_w; uint knl_i = c * p.knl_h * p.knl_w;
FLOAT_TYPE sum = 0.0; for (uint knl_y = 0; knl_y < p.knl_h; ++knl_y) { uint src_y = dst_y * p.stride_y + knl_y * p.dilation_y - p.pad_y; if (src_y >= p.src_h) { // src_y < 0 will wrap to a large unsigned int continue; } for (uint knl_x = 0; knl_x < p.knl_w; ++knl_x) { uint src_x = dst_x * p.stride_x + knl_x * p.dilation_x - p.pad_x; if (src_x >= p.src_w) { // src_x < 0 will wrap to a large unsigned int continue; } FLOAT_TYPE v = FLOAT_TYPE(src_data[src_i + src_y * p.src_w + src_x]); FLOAT_TYPE k = FLOAT_TYPE(knl_data[knl_i + knl_y * p.knl_w + knl_x]); sum = fma(v, k, sum); } } return sum;}
FLOAT_TYPE conv_2d_dw_cwhn(uint idx) { uint i0 = idx / p.channels; uint c = idx - i0 * p.channels; uint i1 = i0 / p.dst_w; uint dst_x = i0 - i1 * p.dst_w; uint n = i1 / p.dst_h; uint dst_y = i1 - n * p.dst_h;
uint src_i = n * p.channels * p.src_h * p.src_w; uint src_row = p.src_w * p.channels; uint knl_row = p.knl_w * p.channels;
FLOAT_TYPE sum = 0.0; for (uint knl_y = 0; knl_y < p.knl_h; ++knl_y) { uint src_y = dst_y * p.stride_y + knl_y * p.dilation_y - p.pad_y; if (src_y >= p.src_h) { // src_y < 0 will wrap to a large unsigned int continue; } for (uint knl_x = 0; knl_x < p.knl_w; ++knl_x) { uint src_x = dst_x * p.stride_x + knl_x * p.dilation_x - p.pad_x; if (src_x >= p.src_w) { // src_x < 0 will wrap to a large unsigned int continue; } FLOAT_TYPE v = FLOAT_TYPE(src_data[src_i + src_y * src_row + src_x * p.channels + c]); FLOAT_TYPE k = FLOAT_TYPE(knl_data[ knl_y * knl_row + knl_x * p.channels + c]); sum = fma(v, k, sum); } } return sum;}
void main() { uint idx = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x; if (idx >= p.ne) { return; }
FLOAT_TYPE result =#ifdef WHCN conv_2d_dw_whcn(idx);#else conv_2d_dw_cwhn(idx);#endif dst_data[idx] = D_TYPE(result);}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480#version 450
#extension GL_EXT_control_flow_attributes : enable#ifdef COOPMAT2#extension GL_NV_cooperative_matrix2 : enable#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require#extension GL_KHR_memory_scope_semantics : enable#endif
#ifdef COOPMAT#extension GL_KHR_cooperative_matrix : enable#extension GL_KHR_shader_subgroup_basic : enable#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require#extension GL_KHR_memory_scope_semantics : enable#endif
#ifdef USE_COLLECTIVES# extension GL_KHR_shader_subgroup_shuffle : enable#endif
#include "types.glsl"
// shape notation: [dim(N), ..., dim(0)] -- stride(dim(j)) >= stride(dim(i)) if i > jlayout(binding = 0) readonly buffer A { A_TYPE knl_data[];}; // src0 - kernel: [KW, KH, Cin, Cout] for conv_2d, [KW, KH, Cout, Cin] for conv_transposed_2d
layout(binding = 1) readonly buffer B { B_TYPE src_data[];}; // src1 - input: [W, H, Cin, N] -- channel_first format
layout(binding = 2) writeonly buffer D { D_TYPE dst_data[];}; // dst - result: [OW, OH, Cout, N]
layout(push_constant) uniform parameter { // I/O channels, batch size uint32_t Cout; uint32_t Cin; uint32_t N;
// Tensor spatial sizes: input, output uint32_t W; uint32_t H; uint32_t OW; uint32_t OH;
// Strides in elements uint32_t nb01; uint32_t nb02; uint32_t nb03;
uint32_t nb11; uint32_t nb12; uint32_t nb13;
uint32_t nb1; uint32_t nb2; uint32_t nb3;
// fastdiv helper values uint32_t OWmp; uint32_t OWL; uint32_t OWOHmp; uint32_t OWOHL;}
p;
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;// Blocktile sizeslayout(constant_id = 1) const uint BS_K = 128;layout(constant_id = 2) const uint BS_CRS = 16;layout(constant_id = 3) const uint BS_NPQ = 128;// Thread-tile sizeslayout(constant_id = 4) const uint TS_K = 8;layout(constant_id = 5) const uint use_collectives = 1;layout(constant_id = 6) const uint SHMEM_PAD = 4;// Stride, padding, dilationlayout(constant_id = 7) const uint s0 = 1;layout(constant_id = 8) const uint s1 = 1;layout(constant_id = 9) const uint p0 = 0;layout(constant_id = 10) const uint p1 = 0;layout(constant_id = 11) const uint d0 = 1;layout(constant_id = 12) const uint d1 = 1;// Kernel spatial sizeslayout(constant_id = 13) const uint KW = 1;layout(constant_id = 14) const uint KH = 1;// when set, skip bounds checks and address clamps (K/CRS/NPQ are tile-aligned)layout(constant_id = 15) const uint aligned = 0;// stage cm2 result through shmem (Csh) for coalesced stores. cm1 always does this.layout(constant_id = 16) const uint csh_store = 0;
#ifdef COOPMAT// cm1 subgroup tile: each subgroup computes a WM x WN region as a grid of// TM x TN x TK fragments. Requires WM%TM == WN%TN == BS_K%WM == BS_NPQ%WN ==// BS_CRS%TK == 0, and WG_SIZE == (BS_K/WM) * (BS_NPQ/WN) * subgroup_size.layout(constant_id = 17) const uint WM = 32;layout(constant_id = 18) const uint WN = 32;const uint TM = 16;const uint TN = 16;const uint TK = 16;const uint cms_per_row = WM / TM;const uint cms_per_col = WN / TN;const uint warps_M = BS_K / WM;const uint warps_N = BS_NPQ / WN;#endif
// without padding, H_idx/W_idx are in bounds by construction (non-TRANSPOSE only)#ifdef TRANSPOSEconst bool hw_in_bounds = false;#elseconst bool hw_in_bounds = (p0 == 0) && (p1 == 0);#endif
// TRANSPOSE stride alignment is trivially satisfied for stride 1#ifdef TRANSPOSEconst bool stride_in_bounds = (s0 == 1) && (s1 == 1);#elseconst bool stride_in_bounds = true;#endif
uint32_t tid = gl_LocalInvocationID.x;const uint32_t WG_SIZE = gl_WorkGroupSize.x;
uint splitWork(uint work_size, uint block_size) { return (block_size + work_size - 1) / block_size;}
uint32_t K = p.Cout;uint32_t CRS = p.Cin * KH * KW;uint32_t NPQ = p.N * p.OH * p.OW;
uint32_t n_elems_out = K * NPQ;
// Number of blocktiles per inputuint32_t NB_CRS = splitWork(CRS, BS_CRS);
#if defined(COOPMAT2) || defined(COOPMAT)#define SHMEM_TYPE float16_t#else#define SHMEM_TYPE float#endif
const uint32_t Ash_stride = BS_CRS + SHMEM_PAD;const uint32_t Bsh_stride = BS_NPQ + SHMEM_PAD;
const uint32_t Ash_numel = BS_K * BS_CRS;const uint32_t Bsh_numel = BS_CRS * BS_NPQ;
const uint32_t Ash_len = BS_K * Ash_stride;const uint32_t Bsh_len = BS_CRS * Bsh_stride;
shared SHMEM_TYPE Ash[Ash_len]; // K x CRSshared SHMEM_TYPE Bsh[Bsh_len]; // CRS x NPQ
#if defined(COOPMAT2) || defined(COOPMAT)// stage matC through shmem so global stores are row-major (NPQ-contiguous)const uint32_t Csh_stride = BS_NPQ;#ifdef COOPMATconst uint32_t Csh_len = BS_K * Csh_stride;#elseconst uint32_t Csh_len = csh_store != 0 ? BS_K * Csh_stride : 8; // 8 to workaround compiler bug#endifshared SHMEM_TYPE Csh[Csh_len]; // K x NPQ#endif
// Threadtile sizesconst uint32_t TS_NPQ = BS_K * BS_NPQ / WG_SIZE / TS_K;
// Number of threadtiles per blocktileconst uint32_t NT_K = BS_K / TS_K;const uint32_t NT_NPQ = BS_NPQ / TS_NPQ;
/*ComputeKxCRS @ CRSxNPQ = K x NPQK=CoutC=CinR,S=KH,KWP,Q=OH,OW*/
uint32_t B_idx_K = gl_WorkGroupID.x;uint32_t B_idx_NPQ = gl_WorkGroupID.y + gl_WorkGroupID.z * 512;
uint32_t T_y = tid / NT_NPQ;uint32_t T_x = tid % NT_NPQ;
uint32_t Ar = tid / BS_CRS;uint32_t Ac = tid % BS_CRS;const uint32_t ArpWg = WG_SIZE / BS_CRS;
uint32_t Br = tid / BS_NPQ;uint32_t Bc = tid % BS_NPQ;const uint32_t BrpWg = WG_SIZE / BS_NPQ;
// see init_fastdiv_values in ggml-vulkan.cppuint fastdiv(uint n, uint mp, uint L) { uint msbs, lsbs; // msbs = mulhi(n, mp) umulExtended(n, mp, msbs, lsbs); return (msbs + n) >> L;}
#ifdef COOPMAT2#define ACC_TYPE float16_t
ACC_TYPE perElemOpStore(const in uint32_t r, const in uint32_t c, const in ACC_TYPE elem){ uint32_t K_idx = B_idx_K * BS_K + r; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + c; uint32_t N_idx = fastdiv(NPQ_idx, p.OWOHmp, p.OWOHL); // divide by p.OH * p.OW; uint32_t OH_idx = fastdiv(NPQ_idx - N_idx * p.OH * p.OW, p.OWmp, p.OWL); // divide by p.OW; uint32_t OW_idx = NPQ_idx - N_idx * p.OH * p.OW - OH_idx * p.OW; uint32_t dst_idx = OW_idx + OH_idx * p.nb1 + K_idx * p.nb2 + N_idx * p.nb3; if (aligned != 0 || (K_idx < K && NPQ_idx < NPQ)) { dst_data[dst_idx] = D_TYPE(elem); } return elem;}#endif
void main() { if (B_idx_NPQ * BS_NPQ >= NPQ) { return; }
#ifdef COOPMAT2 coopmat<ACC_TYPE, gl_ScopeWorkgroup, BS_K, BS_NPQ, gl_MatrixUseAccumulator> matC; matC = coopmat<ACC_TYPE, gl_ScopeWorkgroup, BS_K, BS_NPQ, gl_MatrixUseAccumulator>(0.0);#elif defined(COOPMAT) coopmat<float16_t, gl_ScopeSubgroup, TM, TN, gl_MatrixUseAccumulator> sums[cms_per_row * cms_per_col]; [[unroll]] for (uint i = 0; i < cms_per_row * cms_per_col; i++) { sums[i] = coopmat<float16_t, gl_ScopeSubgroup, TM, TN, gl_MatrixUseAccumulator>(0.0); } const uint warp_r = gl_SubgroupID / warps_N; const uint warp_c = gl_SubgroupID % warps_N;#else float regC[TS_K][TS_NPQ]; for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { regC[T_ly][T_lx] = 0.0; } }#endif /* Advance block in CRS dim */ [[dont_unroll]] for (uint32_t B_idx_CRS = 0; B_idx_CRS < NB_CRS; B_idx_CRS++) { uint32_t CRS_idx_a; uint32_t Cin_idx_a; uint32_t KH_idx_a; uint32_t KW_idx_a;
#ifdef USE_COLLECTIVES uint32_t cached_CRS_idx; uint32_t cached_Cin_idx; uint32_t cached_KH_idx; uint32_t cached_KW_idx; if (use_collectives == 1) { cached_CRS_idx = B_idx_CRS * BS_CRS + gl_SubgroupInvocationID; cached_Cin_idx = cached_CRS_idx / (KW * KH); uint32_t cached_CRS_remainder = cached_CRS_idx % (KW * KH); cached_KH_idx = cached_CRS_remainder / KW; cached_KW_idx = cached_CRS_remainder % KW;
CRS_idx_a = subgroupShuffle(cached_CRS_idx, Ac); Cin_idx_a = subgroupShuffle(cached_Cin_idx, Ac); KH_idx_a = subgroupShuffle(cached_KH_idx, Ac); KW_idx_a = subgroupShuffle(cached_KW_idx, Ac); } else { CRS_idx_a = B_idx_CRS * BS_CRS + Ac; // Global CRS_idx_a (column index of A) Cin_idx_a = CRS_idx_a / (KW * KH); uint32_t CRS_remainder = CRS_idx_a % (KW * KH); KH_idx_a = CRS_remainder / KW; KW_idx_a = CRS_remainder % KW; }#else CRS_idx_a = B_idx_CRS * BS_CRS + Ac; // Global CRS_idx_a (column index of A) Cin_idx_a = CRS_idx_a / (KW * KH); CRS_remainder = CRS_idx_a % (KW * KH); KH_idx_a = CRS_remainder / KW; KW_idx_a = CRS_remainder % KW;#endif
/* Load kernel to A_block: (BS_K x BS_CRS)*/ UNROLL for (uint32_t r_offset = 0; r_offset < BS_K; r_offset += ArpWg) { uint32_t B_ly = r_offset + Ar; uint32_t B_lx = Ac; uint32_t K_idx = B_idx_K * BS_K + B_ly; /* Global K_idx (row index of A)*/#ifdef TRANSPOSE uint32_t knl_idx = KW_idx_a + KH_idx_a * p.nb01 + K_idx * p.nb02 + Cin_idx_a * p.nb03;#else uint32_t knl_idx = KW_idx_a + KH_idx_a * p.nb01 + Cin_idx_a * p.nb02 + K_idx * p.nb03;#endif if (aligned == 0) { knl_idx = min(knl_idx, K * CRS - 1); } float val = knl_data[knl_idx]; if (aligned == 0 && (K_idx >= K || CRS_idx_a >= CRS)) { val = 0.0; } Ash[B_ly * Ash_stride + B_lx] = SHMEM_TYPE(val); } /* Load input to B_block: (BS_CRS x BS_NPQ) */ UNROLL for (uint32_t r_offset = 0; r_offset < BS_CRS; r_offset += BrpWg) { uint32_t B_ly = r_offset + Br; /* Row index of B block */ uint32_t B_lx = Bc; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + B_lx; /* Global NPQ index (column index of B) */ uint32_t N_idx = fastdiv(NPQ_idx, p.OWOHmp, p.OWOHL); // divide by p.OH * p.OW; uint32_t NPQ_remainder = NPQ_idx - N_idx * p.OH * p.OW; uint32_t OH_idx = fastdiv(NPQ_remainder, p.OWmp, p.OWL); // divide by p.OW; uint32_t OW_idx = NPQ_remainder - OH_idx * p.OW;
uint32_t CRS_idx_b; uint32_t Cin_idx_b; uint32_t KH_idx_b; uint32_t KW_idx_b;#ifdef USE_COLLECTIVES if (use_collectives == 1) { CRS_idx_b = subgroupShuffle(cached_CRS_idx, r_offset + Br); Cin_idx_b = subgroupShuffle(cached_Cin_idx, r_offset + Br); KH_idx_b = subgroupShuffle(cached_KH_idx, r_offset + Br); KW_idx_b = subgroupShuffle(cached_KW_idx, r_offset + Br); } else { CRS_idx_b = B_idx_CRS * BS_CRS + B_ly; /* Global CRS index (row index of B) */ Cin_idx_b = CRS_idx_b / (KW * KH); uint32_t CRS_remainder = CRS_idx_b % (KW * KH); KH_idx_b = CRS_remainder / KW; KW_idx_b = CRS_remainder % KW; }#else CRS_idx_b = B_idx_CRS * BS_CRS + B_ly; /* Global CRS index (row index of B) */ Cin_idx_b = CRS_idx_b / (KW * KH); uint32_t CRS_remainder = CRS_idx_b % (KW * KH); KH_idx_b = CRS_remainder / KW; KW_idx_b = CRS_remainder % KW;#endif
#ifdef TRANSPOSE uint32_t H_idx_x_s1 = OH_idx - KH_idx_b * d1 + p1; uint32_t W_idx_x_s0 = OW_idx - KW_idx_b * d0 + p0; uint32_t H_idx = H_idx_x_s1 / s1; uint32_t W_idx = W_idx_x_s0 / s0;#else uint32_t H_idx = OH_idx * s1 + KH_idx_b * d1 - p1; uint32_t W_idx = OW_idx * s0 + KW_idx_b * d0 - p0;#endif uint32_t src_idx = W_idx + H_idx * p.nb11 + Cin_idx_b * p.nb12 + N_idx * p.nb13; // skip clamp when address can't go OOB if (aligned == 0 || !hw_in_bounds || !stride_in_bounds) { src_idx = min(max(src_idx, 0), p.Cin * p.N * p.W * p.H - 1); } float val = src_data[src_idx]; bool oob = false; if (aligned == 0 && (CRS_idx_b >= CRS || NPQ_idx >= NPQ)) { oob = true; } // also catches lower-bound underflow (idx wraps to 0x80000000+) if (!hw_in_bounds && (H_idx >= p.H || W_idx >= p.W)) { oob = true; }#ifdef TRANSPOSE if (!stride_in_bounds && ((H_idx_x_s1 - H_idx * s1 != 0) || (W_idx_x_s0 - W_idx * s0 != 0))) { oob = true; }#endif if (oob) { val = 0.0; } Bsh[B_ly * Bsh_stride + B_lx] = SHMEM_TYPE(val); } barrier();#ifdef COOPMAT2 coopmat<float16_t, gl_ScopeWorkgroup, BS_K, BS_CRS, gl_MatrixUseA> matA; coopmat<float16_t, gl_ScopeWorkgroup, BS_CRS, BS_NPQ, gl_MatrixUseB> matB;
coopMatLoad(matA, Ash, 0, Ash_stride, gl_CooperativeMatrixLayoutRowMajor); coopMatLoad(matB, Bsh, 0, Bsh_stride, gl_CooperativeMatrixLayoutRowMajor); matC = coopMatMulAdd(matA, matB, matC);#elif defined(COOPMAT) // each subgroup multiplies its grid of fragments per TK-sized CRS chunk [[unroll]] for (uint k_step = 0; k_step < BS_CRS / TK; k_step++) { coopmat<float16_t, gl_ScopeSubgroup, TM, TK, gl_MatrixUseA> cache_a[cms_per_row]; [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { const uint a_off = (warp_r * WM + cm_row * TM) * Ash_stride + k_step * TK; coopMatLoad(cache_a[cm_row], Ash, a_off, Ash_stride, gl_CooperativeMatrixLayoutRowMajor); } [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { coopmat<float16_t, gl_ScopeSubgroup, TK, TN, gl_MatrixUseB> cache_b; const uint b_off = k_step * TK * Bsh_stride + warp_c * WN + cm_col * TN; coopMatLoad(cache_b, Bsh, b_off, Bsh_stride, gl_CooperativeMatrixLayoutRowMajor); [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { sums[cm_col * cms_per_row + cm_row] = coopMatMulAdd(cache_a[cm_row], cache_b, sums[cm_col * cms_per_row + cm_row]); } } }#else if (T_y * TS_K < K) { UNROLL for (uint32_t CRS_lidx = 0; CRS_lidx < BS_CRS; CRS_lidx++) { float regA[TS_K]; float regB[TS_NPQ]; for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { regA[T_ly] = Ash[(T_y * TS_K + T_ly) * Ash_stride + CRS_lidx]; } for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { regB[T_lx] = Bsh[CRS_lidx * Bsh_stride + T_x * TS_NPQ + T_lx]; } for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { regC[T_ly][T_lx] = fma(regA[T_ly], regB[T_lx], regC[T_ly][T_lx]); } } } }#endif barrier(); } /* Save C* */#if defined(COOPMAT2) || defined(COOPMAT) // stage matC into Csh, then write to dst with coalesced NPQ-contiguous stores#ifdef COOPMAT const bool use_staged_store = true;#else const bool use_staged_store = (csh_store != 0);#endif if (use_staged_store) {#ifdef COOPMAT // cm1: each subgroup stores its fragment grid into its Csh slot [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { const uint csh_off = (warp_r * WM + cm_row * TM) * Csh_stride + warp_c * WN + cm_col * TN; coopMatStore(sums[cm_col * cms_per_row + cm_row], Csh, csh_off, Csh_stride, gl_CooperativeMatrixLayoutRowMajor); } }#else coopMatStore(matC, Csh, 0, Csh_stride, gl_CooperativeMatrixLayoutRowMajor);#endif barrier();
// cooperative shmem->global: WG threads spread across BS_NPQ (the // contiguous direction of dst), each iter covers store_rows_per_iter K-rows const uint32_t store_rows_per_iter = WG_SIZE / BS_NPQ; const uint32_t store_iters = BS_K / store_rows_per_iter; const uint32_t k_thread_offset = tid / BS_NPQ; const uint32_t npq_thread = tid % BS_NPQ; [[unroll]] for (uint32_t i = 0; i < store_iters; i++) { uint32_t k_local = i * store_rows_per_iter + k_thread_offset; uint32_t K_idx = B_idx_K * BS_K + k_local; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + npq_thread; uint32_t N_idx = fastdiv(NPQ_idx, p.OWOHmp, p.OWOHL); uint32_t OH_idx = fastdiv(NPQ_idx - N_idx * p.OH * p.OW, p.OWmp, p.OWL); uint32_t OW_idx = NPQ_idx - N_idx * p.OH * p.OW - OH_idx * p.OW; uint32_t dst_idx = OW_idx + OH_idx * p.nb1 + K_idx * p.nb2 + N_idx * p.nb3; if (aligned != 0 || (K_idx < K && NPQ_idx < NPQ)) { dst_data[dst_idx] = D_TYPE(Csh[k_local * Csh_stride + npq_thread]); } } }#ifdef COOPMAT2 else { coopMatPerElementNV(matC, matC, perElemOpStore); }#endif#else if (T_y * TS_K < K) { for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { uint32_t K_idx = B_idx_K * BS_K + T_y * TS_K + T_ly; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + T_x * TS_NPQ + T_lx; uint32_t N_idx = fastdiv(NPQ_idx, p.OWOHmp, p.OWOHL); // divide by p.OH * p.OW; uint32_t OH_idx = fastdiv(NPQ_idx - N_idx * p.OH * p.OW, p.OWmp, p.OWL); // divide by p.OW; uint32_t OW_idx = NPQ_idx - N_idx * p.OH * p.OW - OH_idx * p.OW; uint32_t dst_idx = OW_idx + OH_idx * p.nb1 + K_idx * p.nb2 + N_idx * p.nb3; if (aligned != 0 || (K_idx < K && NPQ_idx < NPQ)) { dst_data[dst_idx] = regC[T_ly][T_lx]; } } } }#endif}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431#version 450
#extension GL_EXT_control_flow_attributes : enable#ifdef COOPMAT2#extension GL_NV_cooperative_matrix2 : enable#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require#extension GL_KHR_memory_scope_semantics : enable#endif
#ifdef COOPMAT#extension GL_KHR_cooperative_matrix : enable#extension GL_KHR_shader_subgroup_basic : enable#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require#extension GL_KHR_memory_scope_semantics : enable#endif
#include "types.glsl"
// shape notation: [dim(N), ..., dim(0)] -- stride(dim(j)) >= stride(dim(i)) if i > jlayout(binding = 0) readonly buffer A { A_TYPE knl_data[];}; // src0 - kernel: [KW, KH, KD, IC*OC]
layout(binding = 1) readonly buffer B { B_TYPE src_data[];}; // src1 - input: [IW, IH, ID, IC*N] -- channel_first format
layout(binding = 2) writeonly buffer D { D_TYPE dst_data[];}; // dst - result: [OW, OH, OD, OC*N]
layout(push_constant) uniform parameter { // I/O channels, batch size uint32_t OC; uint32_t IC; uint32_t N;
// Tensor spatial sizes: input, output uint32_t IW; uint32_t IH; uint32_t ID; uint32_t OW; uint32_t OH; uint32_t OD;
// Strides in elements uint32_t nb01; uint32_t nb02; uint32_t nb03;
uint32_t nb11; uint32_t nb12; uint32_t nb13;
uint32_t nb1; uint32_t nb2; uint32_t nb3;
// fastdiv helper values uint32_t OWmp; uint32_t OWL; uint32_t OWOHmp; uint32_t OWOHL; uint32_t OWOHODmp; uint32_t OWOHODL;}
p;
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;// Blocktile sizeslayout(constant_id = 1) const uint BS_K = 128;layout(constant_id = 2) const uint BS_CRS = 16;layout(constant_id = 3) const uint BS_NPQ = 128;// Thread-tile sizeslayout(constant_id = 4) const uint TS_K = 8;layout(constant_id = 5) const uint SHMEM_PAD = 4;// Stride, padding, dilationlayout(constant_id = 6) const uint s0 = 1;layout(constant_id = 7) const uint s1 = 1;layout(constant_id = 8) const uint s2 = 1;layout(constant_id = 9) const uint p0 = 0;layout(constant_id = 10) const uint p1 = 0;layout(constant_id = 11) const uint p2 = 0;layout(constant_id = 12) const uint d0 = 1;layout(constant_id = 13) const uint d1 = 1;layout(constant_id = 14) const uint d2 = 1;// Kernel spatial sizeslayout(constant_id = 15) const uint KW = 1;layout(constant_id = 16) const uint KH = 1;layout(constant_id = 17) const uint KD = 1;// when set, skip bounds checks and address clamps (K/CRS/NPQ are tile-aligned)layout(constant_id = 18) const uint aligned = 0;// stage cm2 result through shmem (Csh) for coalesced stores. cm1 always does this.layout(constant_id = 19) const uint csh_store = 0;
#ifdef COOPMAT// cm1 subgroup tile: each subgroup computes a WM x WN region as a grid of// TM x TN x TK fragments. Requires WM%TM == WN%TN == BS_K%WM == BS_NPQ%WN ==// BS_CRS%TK == 0, and WG_SIZE == (BS_K/WM) * (BS_NPQ/WN) * subgroup_size.layout(constant_id = 20) const uint WM = 32;layout(constant_id = 21) const uint WN = 32;const uint TM = 16;const uint TN = 16;const uint TK = 16;const uint cms_per_row = WM / TM;const uint cms_per_col = WN / TN;const uint warps_M = BS_K / WM;const uint warps_N = BS_NPQ / WN;#endif
// without padding, ID_idx/IH_idx/IW_idx are in bounds by constructionconst bool dhw_in_bounds = (p0 == 0) && (p1 == 0) && (p2 == 0);
uint32_t tid = gl_LocalInvocationID.x;const uint32_t WG_SIZE = gl_WorkGroupSize.x;
uint splitWork(uint work_size, uint block_size) { return (block_size + work_size - 1) / block_size;}
uint32_t K = p.OC;uint32_t CRS = p.IC * KD * KH * KW;uint32_t NPQ = p.N * p.OD * p.OH * p.OW;
// Number of blocktiles per inputuint32_t NB_CRS = splitWork(CRS, BS_CRS);
#if defined(COOPMAT2) || defined(COOPMAT)#define SHMEM_TYPE float16_t#else#define SHMEM_TYPE float#endif
const uint32_t Ash_stride = BS_CRS + SHMEM_PAD;const uint32_t Bsh_stride = BS_NPQ + SHMEM_PAD;
const uint32_t Ash_len = BS_K * Ash_stride;const uint32_t Bsh_len = BS_CRS * Bsh_stride;
shared SHMEM_TYPE Ash[Ash_len]; // K x CRSshared SHMEM_TYPE Bsh[Bsh_len]; // CRS x NPQ
#if defined(COOPMAT2) || defined(COOPMAT)// stage matC through shmem so global stores are row-major (NPQ-contiguous)const uint32_t Csh_stride = BS_NPQ;#ifdef COOPMATconst uint32_t Csh_len = BS_K * Csh_stride;#elseconst uint32_t Csh_len = csh_store != 0 ? BS_K * Csh_stride : 8; // 8 to workaround compiler bug#endifshared SHMEM_TYPE Csh[Csh_len]; // K x NPQ#endif
// Threadtile sizesconst uint32_t TS_NPQ = BS_K * BS_NPQ / WG_SIZE / TS_K;
// Number of threadtiles per blocktileconst uint32_t NT_NPQ = BS_NPQ / TS_NPQ;
/*ComputeKxCRS @ CRSxNPQ = K x NPQK=OCC=ICD,R,S=KD,KH,KWZ,P,Q=OD,OH,OW*/
uint32_t B_idx_K = gl_WorkGroupID.x;uint32_t B_idx_NPQ = gl_WorkGroupID.y + gl_WorkGroupID.z * 512;
uint32_t T_y = tid / NT_NPQ;uint32_t T_x = tid % NT_NPQ;
uint32_t Ar = tid / BS_CRS;uint32_t Ac = tid % BS_CRS;const uint32_t ArpWg = WG_SIZE / BS_CRS;
uint32_t Br = tid / BS_NPQ;uint32_t Bc = tid % BS_NPQ;const uint32_t BrpWg = WG_SIZE / BS_NPQ;
// see init_fastdiv_values in ggml-vulkan.cppuint fastdiv(uint n, uint mp, uint L) { uint msbs, lsbs; // msbs = mulhi(n, mp) umulExtended(n, mp, msbs, lsbs); return (msbs + n) >> L;}
void split_crs(uint32_t crs_idx, out uint32_t ic, out uint32_t kd, out uint32_t kh, out uint32_t kw) { const uint32_t KHKW = KH * KW; const uint32_t KDKHKW = KD * KHKW; ic = crs_idx / KDKHKW; uint32_t rem = crs_idx - ic * KDKHKW; kd = rem / KHKW; rem = rem - kd * KHKW; kh = rem / KW; kw = rem - kh * KW;}
void split_npq(uint32_t npq_idx, out uint32_t n, out uint32_t od, out uint32_t oh, out uint32_t ow) { const uint32_t OWOH = p.OW * p.OH; n = fastdiv(npq_idx, p.OWOHODmp, p.OWOHODL); uint32_t rem = npq_idx - n * p.OD * OWOH; od = fastdiv(rem, p.OWOHmp, p.OWOHL); rem = rem - od * OWOH; oh = fastdiv(rem, p.OWmp, p.OWL); ow = rem - oh * p.OW;}
#ifdef COOPMAT2#define ACC_TYPE float16_t
ACC_TYPE perElemOpStore(const in uint32_t r, const in uint32_t c, const in ACC_TYPE elem){ uint32_t K_idx = B_idx_K * BS_K + r; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + c; uint32_t N_idx; uint32_t OD_idx; uint32_t OH_idx; uint32_t OW_idx; split_npq(NPQ_idx, N_idx, OD_idx, OH_idx, OW_idx); uint32_t dst_idx = OW_idx + OH_idx * p.nb1 + OD_idx * p.nb2 + (N_idx * p.OC + K_idx) * p.nb3; if (aligned != 0 || (K_idx < K && NPQ_idx < NPQ)) { dst_data[dst_idx] = D_TYPE(elem); } return elem;}#endif
void main() { if (B_idx_NPQ * BS_NPQ >= NPQ) { return; }
#ifdef COOPMAT2 coopmat<ACC_TYPE, gl_ScopeWorkgroup, BS_K, BS_NPQ, gl_MatrixUseAccumulator> matC; matC = coopmat<ACC_TYPE, gl_ScopeWorkgroup, BS_K, BS_NPQ, gl_MatrixUseAccumulator>(0.0);#elif defined(COOPMAT) coopmat<float16_t, gl_ScopeSubgroup, TM, TN, gl_MatrixUseAccumulator> sums[cms_per_row * cms_per_col]; [[unroll]] for (uint i = 0; i < cms_per_row * cms_per_col; i++) { sums[i] = coopmat<float16_t, gl_ScopeSubgroup, TM, TN, gl_MatrixUseAccumulator>(0.0); } const uint warp_r = gl_SubgroupID / warps_N; const uint warp_c = gl_SubgroupID % warps_N;#else float regC[TS_K][TS_NPQ]; for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { regC[T_ly][T_lx] = 0.0; } }#endif /* Advance block in CRS dim */ [[dont_unroll]] for (uint32_t B_idx_CRS = 0; B_idx_CRS < NB_CRS; B_idx_CRS++) { uint32_t CRS_idx_a = B_idx_CRS * BS_CRS + Ac; uint32_t IC_idx_a; uint32_t KD_idx_a; uint32_t KH_idx_a; uint32_t KW_idx_a; split_crs(CRS_idx_a, IC_idx_a, KD_idx_a, KH_idx_a, KW_idx_a);
/* Load kernel to A_block: (BS_K x BS_CRS)*/ UNROLL for (uint32_t r_offset = 0; r_offset < BS_K; r_offset += ArpWg) { uint32_t B_ly = r_offset + Ar; uint32_t B_lx = Ac; uint32_t K_idx = B_idx_K * BS_K + B_ly; /* Global K_idx (row index of A)*/ uint32_t knl_idx = KW_idx_a + KH_idx_a * p.nb01 + KD_idx_a * p.nb02 + (K_idx * p.IC + IC_idx_a) * p.nb03; if (aligned == 0) { knl_idx = min(knl_idx, K * CRS - 1); } float val = knl_data[knl_idx]; if (aligned == 0 && (K_idx >= K || CRS_idx_a >= CRS)) { val = 0.0; } Ash[B_ly * Ash_stride + B_lx] = SHMEM_TYPE(val); } /* Load input to B_block: (BS_CRS x BS_NPQ) */ UNROLL for (uint32_t r_offset = 0; r_offset < BS_CRS; r_offset += BrpWg) { uint32_t B_ly = r_offset + Br; /* Row index of B block */ uint32_t B_lx = Bc; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + B_lx; /* Global NPQ index (column index of B) */ uint32_t N_idx; uint32_t OD_idx; uint32_t OH_idx; uint32_t OW_idx; split_npq(NPQ_idx, N_idx, OD_idx, OH_idx, OW_idx);
uint32_t CRS_idx_b = B_idx_CRS * BS_CRS + B_ly; uint32_t IC_idx_b; uint32_t KD_idx_b; uint32_t KH_idx_b; uint32_t KW_idx_b; split_crs(CRS_idx_b, IC_idx_b, KD_idx_b, KH_idx_b, KW_idx_b);
uint32_t ID_idx = OD_idx * s2 + KD_idx_b * d2 - p2; uint32_t IH_idx = OH_idx * s1 + KH_idx_b * d1 - p1; uint32_t IW_idx = OW_idx * s0 + KW_idx_b * d0 - p0;
uint32_t src_idx = IW_idx + IH_idx * p.nb11 + ID_idx * p.nb12 + (N_idx * p.IC + IC_idx_b) * p.nb13; // skip clamp when address can't go OOB if (aligned == 0 || !dhw_in_bounds) { src_idx = min(src_idx, p.IC * p.N * p.IW * p.IH * p.ID - 1); } float val = src_data[src_idx]; bool oob = false; if (aligned == 0 && (CRS_idx_b >= CRS || NPQ_idx >= NPQ)) { oob = true; } // also catches lower-bound underflow (idx wraps to 0x80000000+) if (!dhw_in_bounds && (ID_idx >= p.ID || IH_idx >= p.IH || IW_idx >= p.IW)) { oob = true; } if (oob) { val = 0.0; } Bsh[B_ly * Bsh_stride + B_lx] = SHMEM_TYPE(val); } barrier();#ifdef COOPMAT2 coopmat<float16_t, gl_ScopeWorkgroup, BS_K, BS_CRS, gl_MatrixUseA> matA; coopmat<float16_t, gl_ScopeWorkgroup, BS_CRS, BS_NPQ, gl_MatrixUseB> matB;
coopMatLoad(matA, Ash, 0, Ash_stride, gl_CooperativeMatrixLayoutRowMajor); coopMatLoad(matB, Bsh, 0, Bsh_stride, gl_CooperativeMatrixLayoutRowMajor); matC = coopMatMulAdd(matA, matB, matC);#elif defined(COOPMAT) // each subgroup multiplies its grid of fragments per TK-sized CRS chunk [[unroll]] for (uint k_step = 0; k_step < BS_CRS / TK; k_step++) { coopmat<float16_t, gl_ScopeSubgroup, TM, TK, gl_MatrixUseA> cache_a[cms_per_row]; [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { const uint a_off = (warp_r * WM + cm_row * TM) * Ash_stride + k_step * TK; coopMatLoad(cache_a[cm_row], Ash, a_off, Ash_stride, gl_CooperativeMatrixLayoutRowMajor); } [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { coopmat<float16_t, gl_ScopeSubgroup, TK, TN, gl_MatrixUseB> cache_b; const uint b_off = k_step * TK * Bsh_stride + warp_c * WN + cm_col * TN; coopMatLoad(cache_b, Bsh, b_off, Bsh_stride, gl_CooperativeMatrixLayoutRowMajor); [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { sums[cm_col * cms_per_row + cm_row] = coopMatMulAdd(cache_a[cm_row], cache_b, sums[cm_col * cms_per_row + cm_row]); } } }#else if (T_y * TS_K < K) { UNROLL for (uint32_t CRS_lidx = 0; CRS_lidx < BS_CRS; CRS_lidx++) { float regA[TS_K]; float regB[TS_NPQ]; for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { regA[T_ly] = Ash[(T_y * TS_K + T_ly) * Ash_stride + CRS_lidx]; } for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { regB[T_lx] = Bsh[CRS_lidx * Bsh_stride + T_x * TS_NPQ + T_lx]; } for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { regC[T_ly][T_lx] = fma(regA[T_ly], regB[T_lx], regC[T_ly][T_lx]); } } } }#endif barrier(); } /* Save C* */#if defined(COOPMAT2) || defined(COOPMAT) // stage matC into Csh, then write to dst with coalesced NPQ-contiguous stores#ifdef COOPMAT const bool use_staged_store = true;#else const bool use_staged_store = (csh_store != 0);#endif if (use_staged_store) {#ifdef COOPMAT // cm1: each subgroup stores its fragment grid into its Csh slot [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { const uint csh_off = (warp_r * WM + cm_row * TM) * Csh_stride + warp_c * WN + cm_col * TN; coopMatStore(sums[cm_col * cms_per_row + cm_row], Csh, csh_off, Csh_stride, gl_CooperativeMatrixLayoutRowMajor); } }#else coopMatStore(matC, Csh, 0, Csh_stride, gl_CooperativeMatrixLayoutRowMajor);#endif barrier();
// cooperative shmem->global: WG threads spread across BS_NPQ (the // contiguous direction of dst), each iter covers store_rows_per_iter K-rows const uint32_t store_rows_per_iter = WG_SIZE / BS_NPQ; const uint32_t store_iters = BS_K / store_rows_per_iter; const uint32_t k_thread_offset = tid / BS_NPQ; const uint32_t npq_thread = tid % BS_NPQ; [[unroll]] for (uint32_t i = 0; i < store_iters; i++) { uint32_t k_local = i * store_rows_per_iter + k_thread_offset; uint32_t K_idx = B_idx_K * BS_K + k_local; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + npq_thread; uint32_t N_idx; uint32_t OD_idx; uint32_t OH_idx; uint32_t OW_idx; split_npq(NPQ_idx, N_idx, OD_idx, OH_idx, OW_idx); uint32_t dst_idx = OW_idx + OH_idx * p.nb1 + OD_idx * p.nb2 + (N_idx * p.OC + K_idx) * p.nb3; if (aligned != 0 || (K_idx < K && NPQ_idx < NPQ)) { dst_data[dst_idx] = D_TYPE(Csh[k_local * Csh_stride + npq_thread]); } } }#ifdef COOPMAT2 else { coopMatPerElementNV(matC, matC, perElemOpStore); }#endif#else if (T_y * TS_K < K) { for (uint32_t T_ly = 0; T_ly < TS_K; T_ly++) { for (uint32_t T_lx = 0; T_lx < TS_NPQ; T_lx++) { uint32_t K_idx = B_idx_K * BS_K + T_y * TS_K + T_ly; uint32_t NPQ_idx = B_idx_NPQ * BS_NPQ + T_x * TS_NPQ + T_lx; uint32_t N_idx; uint32_t OD_idx; uint32_t OH_idx; uint32_t OW_idx; split_npq(NPQ_idx, N_idx, OD_idx, OH_idx, OW_idx); uint32_t dst_idx = OW_idx + OH_idx * p.nb1 + OD_idx * p.nb2 + (N_idx * p.OC + K_idx) * p.nb3; if (aligned != 0 || (K_idx < K && NPQ_idx < NPQ)) { dst_data[dst_idx] = D_TYPE(regC[T_ly][T_lx]); } } } }#endif}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798#version 450
#include "types.glsl"
layout (binding = 0) readonly buffer A {A_TYPE data_a[];}; // src0 - kernel: [K, Cout, Cin]layout (binding = 1) readonly buffer B {B_TYPE data_b[];}; // src1 - input: [L, Cin]layout (binding = 2) writeonly buffer D {D_TYPE data_d[];}; // dst - result [KL, Cout]
layout(local_size_x = 128 , local_size_y = 1, local_size_z = 1) in;
layout (push_constant) uniform parameter { uint32_t Cout; uint32_t Cin; uint32_t K; uint32_t L; uint32_t KL;
uint32_t nb01; uint32_t nb02; uint32_t nb11; uint32_t nb1;
int32_t s0;} p;
uint32_t Cout_idx = gl_WorkGroupID.x;const uint32_t bs = gl_WorkGroupSize.x;uint32_t tid = gl_LocalInvocationID.x;// Code is more straightforward if we assume it is bs*s0+K instead of (bs-1)*s0+K.uint32_t tmp_len = bs*p.s0+p.K;shared D_TYPE tmp[4096];
uint splitWork(uint workSize){ return (bs + workSize -1) / bs;}
void main(){ for(uint32_t i = 0; i < splitWork(tmp_len); i++){ uint32_t idx = i*bs+tid; if(idx < tmp_len){ tmp[idx] = 0.0; } }
uint32_t L_blocks = splitWork(p.L); for(uint32_t L_block_id = 0; L_block_id < L_blocks; L_block_id++){ if(L_block_id > 0){ barrier(); // Shift values in tmp to the current processing window for(int i = 0; i < splitWork(tmp_len); i++){ uint32_t idx = i*bs+tid; if(idx >= bs*p.s0 && idx < tmp_len){ tmp[idx-bs*p.s0] = tmp[idx]; tmp[idx] = 0.0; }else if(idx >= p.K && idx < bs*p.s0){ tmp[idx] = 0.0; } } } barrier();
// Save contributions of the block to tmp uint32_t L_idx = L_block_id*bs + tid; for(uint32_t K_idx = 0; K_idx < p.K; K_idx++){ D_TYPE dp = 0.0; for(uint32_t Cin_idx = 0; Cin_idx < p.Cin; Cin_idx++){ A_TYPE elemKrn = data_a[K_idx + Cout_idx * p.nb01 + Cin_idx * p.nb02]; if(L_idx < p.L){ B_TYPE elemInp = data_b[L_idx + Cin_idx*p.nb11]; dp = fma(elemKrn, elemInp, dp); } } tmp[tid*p.s0 + K_idx] += dp; barrier(); }
// Save the computed values except the last block that can have different size uint32_t KLb_idx = L_block_id*bs*p.s0; if(L_block_id < L_blocks-1){ for(uint32_t s0_idx = 0; s0_idx < p.s0; s0_idx++){ uint32_t sh_idx = p.s0*tid+s0_idx; uint32_t KL_idx = KLb_idx+sh_idx; if(KL_idx < p.KL){ data_d[KL_idx + Cout_idx*p.nb1] = tmp[sh_idx]; } } } }
for(uint32_t i = 0; i < splitWork(tmp_len); i++){ uint32_t idx = i*bs+tid; uint32_t KL_idx = (L_blocks-1)*bs*p.s0+idx; if(KL_idx < p.KL){ data_d[KL_idx + Cout_idx*p.nb1] = tmp[idx]; } }}12345678910111213141516171819202122232425#version 450
#include "types.glsl"#include "generic_unary_head.glsl"
layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
void main() { const uint idx = get_idx();
if (idx >= p.ne) { return; }
#if defined(DATA_A_BF16) data_d[get_doffset() + dst_idx(idx)] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + src0_idx(idx)])));#elif defined(DATA_D_BF16) float f = float(data_a[get_aoffset() + src0_idx(idx)]); data_d[get_doffset() + dst_idx(idx)] = D_TYPE(fp32_to_bf16(f));#elif !defined(OPTIMIZATION_ERROR_WORKAROUND) data_d[get_doffset() + dst_idx(idx)] = D_TYPE(data_a[get_aoffset() + src0_idx(idx)]);#else data_d[get_doffset() + dst_idx(idx)] = data_a[get_aoffset() + src0_idx(idx)];#endif}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#version 450
#include "types.glsl"#include "generic_unary_head.glsl"#include "dequant_funcs.glsl"
#if defined(DATA_A_IQ4_NL) || defined(DATA_A_MXFP4) || defined(DATA_A_NVFP4)// 16 invocations needed for init_iq_shmemlayout(local_size_x = 16, local_size_y = 1, local_size_z = 1) in;#elselayout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;#endif
void main() {#ifdef NEEDS_INIT_IQ_SHMEM init_iq_shmem(gl_WorkGroupSize); if (gl_LocalInvocationIndex.x != 0) { return; }#endif
const uint idx = gl_WorkGroupID.z * 262144 + gl_WorkGroupID.y * 512 + gl_WorkGroupID.x * QUANT_K;
if (idx >= p.ne) { return; }
uint dst_idx = get_doffset() + dst_idx(idx); uint src_idx = src0_idx_quant(idx, QUANT_K);
const uint a_offset = 0; const uint ib = src_idx; const vec2 dm = get_dm(ib, a_offset);
[[unroll]] for (int j = 0; j < QUANT_K; j += 4) { vec4 v = dequantize4(ib, j / QUANT_R, a_offset); v = v * dm.x + vec4(dm.y);
#if QUANT_R == 2 data_d[dst_idx + j/2 + 0] = v[0]; data_d[dst_idx + j/2 + QUANT_K/2 + 0] = v[1]; data_d[dst_idx + j/2 + 1] = v[2]; data_d[dst_idx + j/2 + QUANT_K/2 + 1] = v[3];#else data_d[dst_idx + j + 0] = v[0]; data_d[dst_idx + j + 1] = v[1]; data_d[dst_idx + j + 2] = v[2]; data_d[dst_idx + j + 3] = v[3];#endif }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320#version 450
#include "types.glsl"
#if defined(SET_ROWS) && QUANT_K == 1layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;const uint BLOCK_SIZE = 512;#elselayout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;const uint BLOCK_SIZE = 32;#endif
layout (binding = 0) readonly buffer S {float data_s[];};
#if defined(SET_ROWS)#include "generic_binary_head.glsl"layout (binding = 1) readonly buffer C {B_TYPE data_i[];};layout (binding = 2) writeonly buffer Q {A_TYPE data_q[];};
#if B_SIZE == 64#define DATA_I_SWIZZLE .x#else#define DATA_I_SWIZZLE#endif
#else#include "generic_unary_head.glsl"layout (binding = 1) writeonly buffer Q {A_TYPE data_q[];};#endif
#if defined(DATA_A_Q4_0)void quantize(uint dst_idx, uint src_idx){ float amax = 0.0; float vmax = 0.0;
[[unroll]] for (int j = 0; j < QUANT_K_Q4_0; ++j) { const float v = data_s[src_idx + j]; if (amax < abs(v)) { amax = abs(v); vmax = v; } }
const float d = vmax / -8; const float id = (d != 0.0) ? 1.0/d : 0.0;
data_q[dst_idx].d = float16_t(d);
[[unroll]] for (int j = 0; j < QUANT_K_Q4_0/2; ++j) { const float x0 = data_s[src_idx + 0 + j]*id; const float x1 = data_s[src_idx + QUANT_K_Q4_0/2 + j]*id;
const uint xi0 = min(15, int(x0 + 8.5)); const uint xi1 = min(15, int(x1 + 8.5));
data_q[dst_idx].qs[j] = uint8_t(xi0 | (xi1 << 4)); }}#endif
#if defined(DATA_A_Q4_1)void quantize(uint dst_idx, uint src_idx){ float vmin = 1.0/0.0; float vmax = -vmin;
[[unroll]] for (int j = 0; j < QUANT_K_Q4_1; ++j) { const float v = data_s[src_idx + j];
if (v < vmin) vmin = v; if (v > vmax) vmax = v; }
const float d = (vmax - vmin) / ((1 << 4) - 1); const float id = (d != 0.0) ? 1.0/d : 0.0;
data_q[dst_idx].d = float16_t(d); data_q[dst_idx].m = float16_t(vmin);
[[unroll]] for (int j = 0; j < QUANT_K_Q4_1/2; ++j) { const float x0 = (data_s[src_idx + 0 + j] - vmin)*id; const float x1 = (data_s[src_idx + QUANT_K_Q4_1/2 + j] - vmin)*id;
const uint xi0 = min(15, int(x0 + 0.5)); const uint xi1 = min(15, int(x1 + 0.5));
data_q[dst_idx].qs[j] = uint8_t(xi0 | (xi1 << 4)); }}#endif
#if defined(DATA_A_Q5_0)void quantize(uint dst_idx, uint src_idx){ float amax = 0.0; float vmax = 0.0;
[[unroll]] for (int j = 0; j < QUANT_K_Q5_0; ++j) { const float v = data_s[src_idx + j]; if (amax < abs(v)) { amax = abs(v); vmax = v; } }
const float d = vmax / -16; const float id = (d != 0.0) ? 1.0/d : 0.0;
data_q[dst_idx].d = float16_t(d);
uint32_t qh = 0; [[unroll]] for (int j = 0; j < QUANT_K_Q5_0/2; ++j) { const float x0 = data_s[src_idx + 0 + j]*id; const float x1 = data_s[src_idx + QUANT_K_Q5_0/2 + j]*id;
const uint xi0 = min(31, int(x0 + 16.5)); const uint xi1 = min(31, int(x1 + 16.5));
data_q[dst_idx].qs[j] = uint8_t((xi0 & 0xf) | ((xi1 & 0xf) << 4)); qh |= ((xi0 & 0x10u) >> 4) << (j + 0); qh |= ((xi1 & 0x10u) >> 4) << (j + QUANT_K_Q5_0/2); } data_q[dst_idx].qh[0] = uint16_t(qh & 0xFFFF); data_q[dst_idx].qh[1] = uint16_t(qh >> 16);}#endif
#if defined(DATA_A_Q5_1)void quantize(uint dst_idx, uint src_idx){ float min = data_s[src_idx + 0]; float max = min;
[[unroll]] for (int j = 1; j < QUANT_K_Q5_1; ++j) { const float v = data_s[src_idx + j]; min = v < min ? v : min; max = v > max ? v : max; }
const float d = (max - min) / 31; const float id = (d != 0) ? 1.0/d : 0.0;
data_q[dst_idx].d = float16_t(d); data_q[dst_idx].m = float16_t(min);
uint32_t qh = 0; [[unroll]] for (int j = 0; j < QUANT_K_Q5_1/2; ++j) { const float x0 = (data_s[src_idx + 0 + j] - min)*id; const float x1 = (data_s[src_idx + QUANT_K_Q5_1/2 + j] - min)*id;
const uint xi0 = uint(x0 + 0.5); const uint xi1 = uint(x1 + 0.5);
data_q[dst_idx].qs[j] = uint8_t((xi0 & 0xf) | ((xi1 & 0xf) << 4)); qh |= ((xi0 & 0x10u) >> 4) << (j + 0); qh |= ((xi1 & 0x10u) >> 4) << (j + QUANT_K_Q5_1/2); } data_q[dst_idx].qh = qh;}#endif
#if defined(DATA_A_Q8_0)void quantize(uint dst_idx, uint src_idx){ float amax = 0.0; // absolute max
[[unroll]] for (int j = 0; j < QUANT_K_Q8_0; j++) { const float v = data_s[src_idx + j]; amax = max(amax, abs(v)); }
const float d = amax / ((1 << 7) - 1); const float id = (d != 0.0) ? 1.0/d : 0.0;
data_q[dst_idx].d = float16_t(d);
[[unroll]] for (int j = 0; j < QUANT_K_Q8_0; ++j) { const float x0 = data_s[src_idx + j]*id;
data_q[dst_idx].qs[j] = int8_t(round(x0)); }}#endif
#if defined(DATA_A_Q1_0)void quantize(uint dst_idx, uint src_idx){ float sum_abs = 0.0;
[[unroll]] for (int j = 0; j < QUANT_K_Q1_0; j++) { sum_abs += abs(data_s[src_idx + j]); }
const float d = sum_abs / QUANT_K_Q1_0;
data_q[dst_idx].d = float16_t(d);
[[unroll]] for (int j = 0; j < QUANT_K_Q1_0 / 8; ++j) { data_q[dst_idx].qs[j] = uint8_t(0); }
[[unroll]] for (int j = 0; j < QUANT_K_Q1_0; ++j) { if (data_s[src_idx + j] >= 0.0) { data_q[dst_idx].qs[j / 8] |= uint8_t(1 << (j % 8)); } }}#endif
#if defined(DATA_A_IQ4_NL)uint best_index(float x) { if (x <= kvalues_iq4nl[0]) return 0; if (x >= kvalues_iq4nl[15]) return 15; int ml = 0, mu = 15; while (mu-ml > 1) { int mav = (ml+mu)/2; if (x < kvalues_iq4nl[mav]) mu = mav; else ml = mav; } return x - kvalues_iq4nl[mu-1] < kvalues_iq4nl[mu] - x ? mu-1 : mu;}
void quantize(uint dst_idx, uint src_idx){ float amax = 0.0; float vmax = 0.0;
[[unroll]] for (int j = 0; j < QUANT_K_IQ4_NL; ++j) { const float v = data_s[src_idx + j]; if (amax < abs(v)) { amax = abs(v); vmax = v; } }
float d = vmax / kvalues_iq4nl[0]; const float id = (d != 0.0) ? 1.0/d : 0.0;
float sumqx = 0, sumq2 = 0; [[unroll]] for (int j = 0; j < QUANT_K_IQ4_NL/2; ++j) { const float x0 = data_s[src_idx + 0 + j]*id; const float x1 = data_s[src_idx + QUANT_K_IQ4_NL/2 + j]*id; const uint xi0 = best_index(x0); const uint xi1 = best_index(x1); data_q[dst_idx].qs[j] = uint8_t(xi0 | (xi1 << 4)); const float v0 = kvalues_iq4nl[xi0]; const float v1 = kvalues_iq4nl[xi1]; const float w0 = data_s[src_idx + 0 + j]*data_s[src_idx + 0 + j]; const float w1 = data_s[src_idx + QUANT_K_IQ4_NL/2 + j]*data_s[src_idx + QUANT_K_IQ4_NL/2 + j]; sumqx += w0*v0*data_s[src_idx + j] + w1*v1*data_s[src_idx + QUANT_K_IQ4_NL/2 + j]; sumq2 += w0*v0*v0 + w1*v1*v1; }
data_q[dst_idx].d = float16_t(sumq2 > 0 ? sumqx/sumq2 : d);
}#endif
#if defined(DATA_A_F32) || defined(DATA_A_F16)void quantize(uint dst_idx, uint src_idx){ data_q[dst_idx] = A_TYPE(data_s[src_idx]);}#endif
#if defined(DATA_A_BF16)void quantize(uint dst_idx, uint src_idx){ data_q[dst_idx] = A_TYPE(fp32_to_bf16(data_s[src_idx]));}#endif
#if defined(SET_ROWS)
void main() {#ifdef NEEDS_INIT_IQ_SHMEM init_iq_shmem(gl_WorkGroupSize);#endif
const uint idx = ((gl_WorkGroupID.z * 262144 + gl_WorkGroupID.y * 512 + gl_WorkGroupID.x) * BLOCK_SIZE + gl_LocalInvocationID.x) * QUANT_K;
if (idx >= p.ne) { return; }
uint i00, i01, i02, i03; get_indices(idx, i00, i01, i02, i03);
uint i12 = fastmod(i03, p.ne12); uint i11 = fastmod(i02, p.ne11); uint i10 = i01;
uint i1 = data_i[src1_idx(i10, i11, i12, 0) + get_boffset()] DATA_I_SWIZZLE;
uint src0_idx = src0_idx(i00, i01, i02, i03) + get_aoffset(); uint dst_idx = dst_idx(i00 / QUANT_K, i1, i02, i03) + get_doffset();
quantize(dst_idx, src0_idx);}
#else
void main() {#ifdef NEEDS_INIT_IQ_SHMEM init_iq_shmem(gl_WorkGroupSize);#endif
const uint idx = (gl_WorkGroupID.z * 262144 + gl_WorkGroupID.y * 512 + gl_WorkGroupID.x * 32 + gl_LocalInvocationID.x) * QUANT_K;
if (idx >= p.ne) { return; }
uint dst_idx = dst_idx_quant(idx, QUANT_K); uint src_idx = get_aoffset() + src0_idx(idx);
quantize(dst_idx, src_idx);}
#endif12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#version 450
#include "types.glsl"#include "generic_unary_head.glsl"
// workgroup does 32x32 tile, but uses 32x8 threads#define TILE_DIM 32layout(local_size_x = 32, local_size_y = 8, local_size_z = 1) in;
shared uint sh[TILE_DIM][TILE_DIM + 1];
void iter(uvec3 wg_id) { const uint tile_col = wg_id.x; const uint tile_row = wg_id.y;
const uint tid_col = gl_LocalInvocationID.x; const uint tid_row = gl_LocalInvocationID.y;
const uint i2 = wg_id.z % p.ne12; const uint i3 = wg_id.z / p.ne12; const uint i02 = i2; const uint i03 = i3;
// The workgroup does TILE_DIM x TILE_DIM, but swaps the LSBs of the // src coords to make memory accesses contiguous, dst has tid.x in i0, // src has tid.x in i01
[[unroll]] for (uint y = 0; y < 4; ++y) { const uint i00 = tile_col * TILE_DIM + tid_row + 8 * y; const uint i01 = tile_row * TILE_DIM + tid_col; if (i00 < p.ne00 && i01 < p.ne01 && i02 < p.ne02 && i03 < p.ne03) { const uint src_idx = i00 * p.nb00 + i01 * p.nb01 + i02 * p.nb02 + i03 * p.nb03; sh[tid_row + 8 * y][tid_col] = uint(data_a[get_aoffset() + src_idx]); } }
barrier();
[[unroll]] for (uint y = 0; y < 4; ++y) { const uint i0 = tile_col * TILE_DIM + tid_col; const uint i1 = tile_row * TILE_DIM + tid_row + 8 * y; if (i0 < p.ne10 && i1 < p.ne11 && i2 < p.ne12 && i3 < p.ne13) { const uint dst_idx = i0 * p.nb10 + i1 * p.nb11 + i2 * p.nb12 + i3 * p.nb13; // load transposed data_d[get_doffset() + dst_idx] = D_TYPE(sh[tid_col][tid_row + 8 * y]); } }}
#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
void main() { uint z = gl_WorkGroupID.z; uint y = gl_WorkGroupID.y; bool need_barrier = false; for (uint z = gl_WorkGroupID.z; z < p.ne12 * p.ne13; z += gl_NumWorkGroups.z) { for (uint y = gl_WorkGroupID.y; y < CEIL_DIV(p.ne11, TILE_DIM); y += gl_NumWorkGroups.y) { for (uint x = gl_WorkGroupID.x; x < CEIL_DIV(p.ne10, TILE_DIM); x += gl_NumWorkGroups.x) { if (need_barrier) { barrier(); } need_barrier = true; iter(uvec3(x, y, z)); } } }}12345678910111213141516171819202122232425262728293031#version 450
#extension GL_EXT_control_flow_attributes : enable
#include "types.glsl"#include "generic_head.glsl"
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer X {A_TYPE data_a[];};layout (binding = 1) readonly buffer Y {B_TYPE data_b[];};layout (binding = 2) buffer D {D_TYPE data_d[];};
const uint CHUNK_SIZE = 512;
void main() { const uint base = gl_WorkGroupID.x * CHUNK_SIZE; const uint col = gl_LocalInvocationID.x;
uint count = 0; [[unroll]] for (uint i = 0; i < CHUNK_SIZE; i += gl_WorkGroupSize.x) { const uint idx = base + i + col; if (idx >= p.KX) { break; } count += uint(data_a[idx] == data_b[idx]); }
atomicAdd(data_d[0], D_TYPE(count));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#version 450
#extension GL_EXT_control_flow_attributes : enable
#include "types.glsl"
layout (push_constant) uniform parameter{ uint32_t ne00; uint32_t ne01; uint32_t nb00; uint32_t nb01; uint32_t a_offset;} p;
#define BLOCK_SIZE 256
layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {uint data_a[];};layout (binding = 1) writeonly buffer D {uint data_d[];};
shared uint vals[BLOCK_SIZE];
void main() { const uint expert_id = gl_WorkGroupID.x; const uint num_elements = p.ne00 * p.ne01; const uint tid = gl_LocalInvocationID.x;
uint count = 0; for (uint idx = tid; idx < num_elements; idx += BLOCK_SIZE) { const uint i01 = idx / p.ne00; const uint i00 = idx % p.ne00; const uint a = data_a[p.a_offset + i01 * p.nb01 + i00 * p.nb00];
count += uint(a == expert_id); }
vals[tid] = count; barrier(); [[unroll]] for (uint s = BLOCK_SIZE / 2; s > 0; s >>= 1) { if (tid < s) { vals[tid] += vals[tid + s]; } barrier(); }
if (tid == 0) { data_d[expert_id] = vals[0]; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283#version 450
#include "types.glsl"#include "sum_rows.glsl"
#extension GL_EXT_control_flow_attributes : enable#extension GL_KHR_shader_subgroup_arithmetic : enable#extension GL_KHR_shader_subgroup_basic : enable
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
layout (constant_id = 0) const uint BLOCK_SIZE = 128;layout (constant_id = 1) const uint SUBGROUP_SIZE = 32;layout (constant_id = 2) const uint ELEM_PER_THREAD = 4;
#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
shared FLOAT_TYPE partial[BLOCK_SIZE / SUBGROUP_SIZE];shared FLOAT_TYPE last_sum;
void main() { const uint row = gl_WorkGroupID.z * 262144 + gl_WorkGroupID.y * 512 + gl_WorkGroupID.x; const uint tid = gl_LocalInvocationID.x;
const uint i03 = fastdiv(row, p.ne0_12mp, p.ne0_12L); const uint i03_offset = i03 * p.ne01*p.ne02; const uint i02 = fastdiv(row - i03_offset, p.ne0_1mp, p.ne0_1L); const uint i01 = row - i03_offset - i02*p.ne01;
const uint src_idx = get_aoffset() + i01 * p.nb01 + i02 * p.nb02 + i03 * p.nb03; const uint dst_idx = get_doffset() + i01 * p.nb11 + i02 * p.nb12 + i03 * p.nb13;
uint subgroup_id = tid / SUBGROUP_SIZE;
if (tid == 0) { last_sum = 0; }
uint col = tid * ELEM_PER_THREAD; uint num_iter = CEIL_DIV(p.n_cols, BLOCK_SIZE * ELEM_PER_THREAD); for (int i = 0; i < num_iter; ++i) { FLOAT_TYPE v[ELEM_PER_THREAD]; FLOAT_TYPE thread_sum = 0; [[unroll]] for (uint j = 0; j < ELEM_PER_THREAD; ++j) { if (col + j < p.n_cols) { thread_sum += FLOAT_TYPE(data_a[src_idx + col + j]); } v[j] = thread_sum; }
thread_sum = subgroupExclusiveAdd(thread_sum); [[unroll]] for (uint j = 0; j < ELEM_PER_THREAD; ++j) { v[j] += thread_sum; } // Store the largest partial sum for each subgroup, then add the partials for all // lower subgroups and the final partial sum from the previous iteration. if (gl_SubgroupInvocationID == SUBGROUP_SIZE - 1) { partial[subgroup_id] = v[ELEM_PER_THREAD - 1]; } barrier(); for (int s = 0; s < subgroup_id; ++s) { [[unroll]] for (uint j = 0; j < ELEM_PER_THREAD; ++j) { v[j] += partial[s]; } } [[unroll]] for (uint j = 0; j < ELEM_PER_THREAD; ++j) { v[j] += last_sum; } barrier(); if (tid == BLOCK_SIZE - 1) { last_sum = v[ELEM_PER_THREAD - 1]; } [[unroll]] for (uint j = 0; j < ELEM_PER_THREAD; ++j) { if (col + j < p.n_cols) { data_d[dst_idx + col + j] = D_TYPE(v[j]); } } col += BLOCK_SIZE * ELEM_PER_THREAD; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960#version 450
#include "types.glsl"#include "sum_rows.glsl"
#extension GL_EXT_control_flow_attributes : enable#extension GL_KHR_shader_subgroup_arithmetic : enable#extension GL_KHR_shader_subgroup_basic : enable
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};layout (binding = 2) writeonly buffer T {D_TYPE data_t[];};
layout (constant_id = 0) const uint BLOCK_SIZE = 128;layout (constant_id = 1) const uint SUBGROUP_SIZE = 32;
#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
shared FLOAT_TYPE partial[BLOCK_SIZE / SUBGROUP_SIZE];
void main() { const uint row = gl_WorkGroupID.y; const uint tid = gl_LocalInvocationID.x; const uint col = gl_GlobalInvocationID.x;
const uint i03 = fastdiv(row, p.ne0_12mp, p.ne0_12L); const uint i03_offset = i03 * p.ne01*p.ne02; const uint i02 = fastdiv(row - i03_offset, p.ne0_1mp, p.ne0_1L); const uint i01 = row - i03_offset - i02*p.ne01;
const uint src_idx = get_aoffset() + i01 * p.nb01 + i02 * p.nb02 + i03 * p.nb03; const uint dst_idx = get_doffset() + i01 * p.nb11 + i02 * p.nb12 + i03 * p.nb13;
uint subgroup_id = tid / SUBGROUP_SIZE;
FLOAT_TYPE v = 0; if (col < p.n_cols) { v = FLOAT_TYPE(data_a[src_idx + col]); } v = subgroupInclusiveAdd(v);
// Store the largest partial sum for each subgroup, then add the partials for all // lower subgroups and the final partial sum from the previous iteration. if (gl_SubgroupInvocationID == SUBGROUP_SIZE - 1) { partial[subgroup_id] = v; } barrier(); for (int j = 0; j < subgroup_id; ++j) { v += partial[j]; } barrier(); if (tid == BLOCK_SIZE - 1) { data_t[gl_WorkGroupID.x + gl_NumWorkGroups.x * row] = v; } if (col < p.n_cols) { data_d[dst_idx + col] = D_TYPE(v); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566#version 450
#include "types.glsl"#include "sum_rows.glsl"
#extension GL_EXT_control_flow_attributes : enable#extension GL_KHR_shader_subgroup_arithmetic : enable#extension GL_KHR_shader_subgroup_basic : enable
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};layout (binding = 1) buffer D {D_TYPE data_d[];};layout (binding = 2) readonly buffer T {D_TYPE data_t[];};
layout (constant_id = 0) const uint BLOCK_SIZE = 128;layout (constant_id = 1) const uint SUBGROUP_SIZE = 32;
#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
shared FLOAT_TYPE temp[BLOCK_SIZE / SUBGROUP_SIZE];
void main() { const uint row = gl_WorkGroupID.y; const uint tid = gl_LocalInvocationID.x;
const uint i03 = fastdiv(row, p.ne0_12mp, p.ne0_12L); const uint i03_offset = i03 * p.ne01*p.ne02; const uint i02 = fastdiv(row - i03_offset, p.ne0_1mp, p.ne0_1L); const uint i01 = row - i03_offset - i02*p.ne01;
const uint src_idx = get_aoffset() + i01 * p.nb01 + i02 * p.nb02 + i03 * p.nb03; const uint dst_idx = get_doffset() + i01 * p.nb11 + i02 * p.nb12 + i03 * p.nb13;
const uint col = gl_GlobalInvocationID.x;
float v = 0; // prefetch value we're adding to if (col < p.n_cols) { v = data_d[dst_idx + col]; }
// compute the sum of all previous blocks uint c = tid; float sum = 0; while (c < gl_WorkGroupID.x) { sum += data_t[c + gl_NumWorkGroups.x * row]; c += BLOCK_SIZE; }
sum = subgroupAdd(sum); if (gl_SubgroupInvocationID == 0) { temp[gl_SubgroupID] = sum; } barrier(); sum = 0; [[unroll]] for (uint s = 0; s < BLOCK_SIZE / SUBGROUP_SIZE; ++s) { sum += temp[s]; }
// Add the sum to what the first pass computed if (col < p.n_cols) { data_d[dst_idx + col] = v + sum; }}
1234567891011121314151617181920#version 450
#include "dequant_head.glsl"
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {float data_a[];};layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
void main() { const uint i = gl_GlobalInvocationID.x * 16;
if (i >= p.nel) { return; }
[[unroll]] for (uint l = 0; l < 16; l++) { data_b[i + l] = D_TYPE(data_a[i + l]); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692#if !defined(DATA_A_F32) && !defined(DATA_A_F16)#extension GL_EXT_shader_explicit_arithmetic_types_int8 : require#endif
#include "types.glsl"
#if defined(DATA_A_F32)FLOAT_TYPE dequantize1(uint ib, uint iqs, uint a_offset) { return data_a[a_offset + ib];}vec2 dequantize(uint ib, uint iqs, uint a_offset) { return vec2(data_a[a_offset + ib], data_a[a_offset + ib + 1]);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { return vec4(data_a[a_offset + ib ], data_a[a_offset + ib + 1], data_a[a_offset + ib + 2], data_a[a_offset + ib + 3]);}vec4 dequantize4_2aligned(uint ib, uint iqs, uint a_offset) { return vec4(data_a[a_offset + ib ], data_a[a_offset + ib + 1], data_a[a_offset + ib + 2], data_a[a_offset + ib + 3]);}
#endif
#if defined(DATA_A_F16)FLOAT_TYPE dequantize1(uint ib, uint iqs, uint a_offset) { return data_a[a_offset + ib];}vec2 dequantize(uint ib, uint iqs, uint a_offset) { return vec2(data_a[a_offset + ib], data_a[a_offset + ib + 1]);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { return vec4(data_a[a_offset + ib ], data_a[a_offset + ib + 1], data_a[a_offset + ib + 2], data_a[a_offset + ib + 3]);}vec4 dequantize4_2aligned(uint ib, uint iqs, uint a_offset) { const vec2 a = data_a_packed32[(a_offset + ib)/2]; const vec2 b = data_a_packed32[(a_offset + ib)/2 + 1]; return vec4(a, b);}#endif
#if defined(DATA_A_BF16)FLOAT_TYPE dequantize1(uint ib, uint iqs, uint a_offset) { return bf16_to_fp32(data_a[a_offset + ib]);}vec2 dequantize(uint ib, uint iqs, uint a_offset) { return vec2(bf16_to_fp32(data_a[a_offset + ib]), bf16_to_fp32(data_a[a_offset + ib + 1]));}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { return vec4(bf16_to_fp32(data_a[a_offset + ib ]), bf16_to_fp32(data_a[a_offset + ib + 1]), bf16_to_fp32(data_a[a_offset + ib + 2]), bf16_to_fp32(data_a[a_offset + ib + 3]));}vec4 dequantize4_2aligned(uint ib, uint iqs, uint a_offset) { const uint a = data_a_packed32[(a_offset + ib)/2]; const uint b = data_a_packed32[(a_offset + ib)/2 + 1]; return vec4(uintBitsToFloat((a & 0x0000ffff) << 16), uintBitsToFloat( a & 0xffff0000), uintBitsToFloat((b & 0x0000ffff) << 16), uintBitsToFloat( b & 0xffff0000));}#endif
#if defined(DATA_A_Q4_0)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint vui = uint(data_a[a_offset + ib].qs[iqs]); return (vec2(vui & 0xF, vui >> 4) - 8.0f);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint vui = uint(data_a_packed16[a_offset + ib].qs[iqs/2]); return (vec4(vui & 0xF, (vui >> 4) & 0xF, (vui >> 8) & 0xF, vui >> 12) - 8.0f);}#endif
#if defined(DATA_A_Q4_1)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint vui = uint(data_a[a_offset + ib].qs[iqs]); return vec2(vui & 0xF, vui >> 4);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint vui = uint(data_a_packed16[a_offset + ib].qs[iqs/2]); return vec4(vui & 0xF, (vui >> 4) & 0xF, (vui >> 8) & 0xF, vui >> 12);}#endif
#if defined(DATA_A_Q5_0)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint uint_qh = uint(data_a[a_offset + ib].qh[1]) << 16 | data_a[a_offset + ib].qh[0]; const ivec2 qh = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10); const uint vui = uint(data_a[a_offset + ib].qs[iqs]); return (vec2((vui & 0xF) | qh.x, (vui >> 4) | qh.y) - 16.0f);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint uint_qh = uint(data_a_packed16[a_offset + ib].qh[1]) << 16 | data_a_packed16[a_offset + ib].qh[0]; const ivec2 qh0 = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10); const ivec2 qh1 = ivec2(((uint_qh >> (iqs + 1)) << 4) & 0x10, (uint_qh >> (iqs + 13)) & 0x10); const uint vui = uint(data_a_packed16[a_offset + ib].qs[iqs/2]); return (vec4((vui & 0xF) | qh0.x, ((vui >> 4) & 0xF) | qh0.y, ((vui >> 8) & 0xF) | qh1.x, (vui >> 12) | qh1.y) - 16.0f);}#endif
#if defined(DATA_A_Q5_1)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint uint_qh = data_a[a_offset + ib].qh; const ivec2 qh = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10); const uint vui = uint(data_a[a_offset + ib].qs[iqs]); return vec2((vui & 0xF) | qh.x, (vui >> 4) | qh.y);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint uint_qh = data_a_packed16[a_offset + ib].qh; const ivec2 qh0 = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10); const ivec2 qh1 = ivec2(((uint_qh >> (iqs + 1)) << 4) & 0x10, (uint_qh >> (iqs + 13)) & 0x10); const uint vui = uint(data_a_packed16[a_offset + ib].qs[iqs/2]); return vec4((vui & 0xF) | qh0.x, ((vui >> 4) & 0xF) | qh0.y, ((vui >> 8) & 0xF) | qh1.x, (vui >> 12) | qh1.y);}#endif
#if defined(DATA_A_Q8_0)vec2 dequantize(uint ib, uint iqs, uint a_offset) { return vec2(int(data_a[a_offset + ib].qs[iqs]), int(data_a[a_offset + ib].qs[iqs + 1]));}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const i8vec2 v0 = unpack8(int32_t(data_a_packed16[a_offset + ib].qs[iqs/2])).xy; // vec4 used due to #12147 const i8vec2 v1 = unpack8(int32_t(data_a_packed16[a_offset + ib].qs[iqs/2 + 1])).xy; return vec4(v0.x, v0.y, v1.x, v1.y);}#endif
#if defined(DATA_A_Q1_0)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint bits = uint(data_a[a_offset + ib].qs[iqs / 8u]) >> (iqs % 8u); return vec2( (bits & 1u) != 0u ? 1.0f : -1.0f, (bits & 2u) != 0u ? 1.0f : -1.0f);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint bits = uint(data_a[a_offset + ib].qs[iqs / 8u]) >> (iqs % 8u); return vec4( (bits & 1u) != 0u ? 1.0f : -1.0f, (bits & 2u) != 0u ? 1.0f : -1.0f, (bits & 4u) != 0u ? 1.0f : -1.0f, (bits & 8u) != 0u ? 1.0f : -1.0f);}#endif
#if defined(DATA_A_IQ1_S)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint ib8 = iqs / 8; const int i8 = int(iqs % 8); const uint qh = data_a[a_offset + ib].qh[ib32]; const uint qs = data_a[a_offset + ib].qs[ib8]; const float dl = float(2 * bitfieldExtract(qh, 12, 3) + 1); const float delta = ((qh & 0x8000) != 0) ? -IQ1S_DELTA : IQ1S_DELTA; const uint idxhi = bitfieldExtract(qh, 3 * int(ib8 & 3), 3); const int16_t grid = int16_t(iq1s_grid[qs | (idxhi << 8)]); // Signed bitfield extract. const ivec2 gvec = ivec2( bitfieldExtract(grid, 2 * (i8), 2), bitfieldExtract(grid, 2 * (i8 + 1), 2) ); return dl * (vec2(gvec) + delta);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint ib8 = iqs / 8; const int i8 = int(iqs % 8); const uint qh = data_a[a_offset + ib].qh[ib32]; const uint qs = data_a[a_offset + ib].qs[ib8]; const float dl = 2 * bitfieldExtract(qh, 12, 3) + 1; const float delta = ((qh & 0x8000) != 0) ? -IQ1S_DELTA : IQ1S_DELTA; const int16_t grid = int16_t(iq1s_grid[qs | (bitfieldExtract(qh, 3 * int(ib8 & 3), 3) << 8)]); // Signed bitfield extract. const ivec4 gvec = ivec4( bitfieldExtract(grid, 2 * (i8), 2), bitfieldExtract(grid, 2 * (i8 + 1), 2), bitfieldExtract(grid, 2 * (i8 + 2), 2), bitfieldExtract(grid, 2 * (i8 + 3), 2) ); return dl * (vec4(gvec) + delta);}#endif
#if defined(DATA_A_IQ1_M)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint ib8 = iqs / 8; const uint ib16 = iqs / 16; const int i8 = int(iqs % 8); const uint sc = data_a[a_offset + ib].scales[iqs / 64]; const uint qs = data_a[a_offset + ib].qs[ib8]; const uint qh = data_a[a_offset + ib].qh[ib16] >> (4 * (ib8 & 1)); const float dl = 2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1; const float delta = ((qh & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA; const int16_t grid = int16_t(iq1s_grid[qs | ((qh & 7) << 8)]); // Signed bitfield extract. const ivec2 gvec = ivec2( bitfieldExtract(grid, 2 * (i8), 2), bitfieldExtract(grid, 2 * (i8 + 1), 2) ); return dl * (vec2(gvec) + delta);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint ib8 = iqs / 8; const uint ib16 = iqs / 16; const int i8 = int(iqs % 8); const uint sc = data_a[a_offset + ib].scales[iqs / 64]; const uint qs = data_a[a_offset + ib].qs[ib8]; const uint qh = data_a[a_offset + ib].qh[ib16] >> (4 * (ib8 & 1)); const float dl = 2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1; const float delta = ((qh & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA; const int16_t grid = int16_t(iq1s_grid[qs | ((qh & 7) << 8)]); // Signed bitfield extract. const ivec4 gvec = ivec4( bitfieldExtract(grid, 2 * (i8), 2), bitfieldExtract(grid, 2 * (i8 + 1), 2), bitfieldExtract(grid, 2 * (i8 + 2), 2), bitfieldExtract(grid, 2 * (i8 + 3), 2) ); return dl * (vec4(gvec) + delta);}#endif
#if defined(DATA_A_IQ2_XXS)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint ib8 = (iqs / 8) % 4; const uint qs = data_a[a_offset + ib].qs[8 * ib32 + ib8]; // Scales are stored as packed 7+7+7+7+4 bits (4 sign tuples and 1 int4 scale) const uint signs = pack32(u16vec2(data_a_packed16[a_offset + ib].qs[4 * ib32 + 2], data_a_packed16[a_offset + ib].qs[4 * ib32 + 3])); const float db = 0.25 * (0.5 + (signs >> 28)); const uint sign7 = bitfieldExtract(signs, 7 * int(ib8), 7); // Add parity bit const uint sign8 = sign7 | (bitCount(sign7) << 7); const uint sign = sign8 >> (iqs % 8); const u8vec4 grid = unpack8(iq2xxs_grid[qs][(iqs % 8) / 4] >> (8 * (iqs % 4))); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; return db * vec2( grid.x * (sign0 ? -1.0 : 1.0), grid.y * (sign1 ? -1.0 : 1.0) );}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint ib8 = (iqs / 8) % 4; const uint qs = data_a[a_offset + ib].qs[8 * ib32 + ib8]; // Scales are stored as packed 7+7+7+7+4 bits (4 sign tuples and 1 int4 scale) const uint signs = pack32(u16vec2(data_a_packed16[a_offset + ib].qs[4 * ib32 + 2], data_a_packed16[a_offset + ib].qs[4 * ib32 + 3])); const float db = 0.25 * (0.5 + (signs >> 28)); const uint sign7 = bitfieldExtract(signs, 7 * int(ib8), 7); // Add parity bit const uint sign8 = sign7 | (bitCount(sign7) << 7); const uint sign = sign8 >> (iqs % 8); const u8vec4 grid = unpack8(iq2xxs_grid[qs][(iqs % 8) / 4] >> (8 * (iqs % 4))); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; bool sign2 = (sign & 4) != 0; bool sign3 = (sign & 8) != 0; return db * vec4( grid.x * (sign0 ? -1.0 : 1.0), grid.y * (sign1 ? -1.0 : 1.0), grid.z * (sign2 ? -1.0 : 1.0), grid.w * (sign3 ? -1.0 : 1.0) );}#endif
#if defined(DATA_A_IQ2_XS)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint scale = (data_a[a_offset + ib].scales[iqs / 32] >> (4 * ((iqs / 16) & 1))) & 0xf; const uint qs = data_a[a_offset + ib].qs[iqs / 8]; const float db = 0.25 * (0.5 + scale); const uint sign7 = qs >> 9; // Add parity bit const uint sign8 = sign7 | (bitCount(sign7) << 7); const uint sign = sign8 >> (iqs % 8); const u8vec4 grid = unpack8(iq2xs_grid[qs & 511][(iqs % 8) / 4] >> (8 * (iqs % 4))); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; return db * vec2( grid.x * (sign0 ? -1.0 : 1.0), grid.y * (sign1 ? -1.0 : 1.0) );}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint scale = (data_a[a_offset + ib].scales[iqs / 32] >> (4 * ((iqs / 16) & 1))) & 0xf; const uint qs = data_a[a_offset + ib].qs[iqs / 8]; const float db = 0.25 * (0.5 + scale); const uint sign7 = qs >> 9; // Add parity bit const uint sign8 = sign7 | (bitCount(sign7) << 7); const uint sign = sign8 >> (iqs % 8); const u8vec4 grid = unpack8(iq2xs_grid[qs & 511][(iqs % 8) / 4] >> (8 * (iqs % 4))); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; bool sign2 = (sign & 4) != 0; bool sign3 = (sign & 8) != 0; return db * vec4( grid.x * (sign0 ? -1.0 : 1.0), grid.y * (sign1 ? -1.0 : 1.0), grid.z * (sign2 ? -1.0 : 1.0), grid.w * (sign3 ? -1.0 : 1.0) );}#endif
#if defined(DATA_A_IQ2_S)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint ib8 = iqs / 8;
const uint scale = (data_a[a_offset + ib].scales[ib32] >> (4 * ((iqs / 16) & 1))) & 0xf; const uint qs = data_a[a_offset + ib].qs[ib8]; const uint qh = data_a[a_offset + ib].qh[ib32]; const uint qhshift = 2 * (ib8 % 4); const uint sign = data_a[a_offset + ib].qs[QUANT_K / 8 + ib8] >> (iqs % 8);
const float db = 0.25 * (0.5 + scale); const u8vec4 grid = unpack8(iq2s_grid[qs | ((qh << (8 - qhshift)) & 0x300)][(iqs % 8) / 4]); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; return db * vec2( grid[iqs % 4] * (sign0 ? -1.0 : 1.0), grid[(iqs % 4) + 1] * (sign1 ? -1.0 : 1.0) );}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint ib8 = iqs / 8;
const uint scale = (data_a[a_offset + ib].scales[ib32] >> (4 * ((iqs / 16) & 1))) & 0xf; const uint qs = data_a[a_offset + ib].qs[ib8]; const uint qh = data_a[a_offset + ib].qh[ib32]; const uint qhshift = 2 * (ib8 % 4); const uint sign = data_a[a_offset + ib].qs[QUANT_K / 8 + ib8] >> (iqs % 8);
const float db = 0.25 * (0.5 + scale); const u8vec4 grid = unpack8(iq2s_grid[qs | ((qh << (8 - qhshift)) & 0x300)][(iqs % 8) / 4]); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; bool sign2 = (sign & 4) != 0; bool sign3 = (sign & 8) != 0; return db * vec4( grid.x * (sign0 ? -1.0 : 1.0), grid.y * (sign1 ? -1.0 : 1.0), grid.z * (sign2 ? -1.0 : 1.0), grid.w * (sign3 ? -1.0 : 1.0) );}#endif
#if defined(DATA_A_IQ3_XXS)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint ib4 = iqs / 4; const uint ib32 = iqs / 32; const uint is = QUANT_K / 4 + 4 * ib32; const uint qs = data_a[a_offset + ib].qs[ib4]; // Scales are stored as packed 7+7+7+7+4 bits (4 sign tuples and 1 int4 scale) const uint signs = pack32(u16vec2(data_a_packed16[a_offset + ib].qs[is / 2], data_a_packed16[a_offset + ib].qs[is / 2 + 1])); const float db = 0.5 * (0.5 + (signs >> 28)); const uint sign7 = bitfieldExtract(signs, 7 * (int(ib4 / 2) % 4), 7); // Add parity bit const uint sign8 = sign7 | (bitCount(sign7) << 7); const uint sign = sign8 >> (iqs % 8); const u8vec4 grid = unpack8(iq3xxs_grid[qs] >> (8 * (iqs % 4))); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; return db * vec2( grid.x * (sign0 ? -1.0 : 1.0), grid.y * (sign1 ? -1.0 : 1.0) );}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint ib4 = iqs / 4; const uint ib32 = iqs / 32; const uint is = QUANT_K / 4 + 4 * ib32; const uint qs = data_a[a_offset + ib].qs[ib4]; const uint signs = pack32(u16vec2(data_a_packed16[a_offset + ib].qs[is / 2], data_a_packed16[a_offset + ib].qs[is / 2 + 1])); const float db = 0.5 * (0.5 + (signs >> 28)); const uint sign7 = bitfieldExtract(signs, 7 * (int(ib4 / 2) % 4), 7); // Add parity bit const uint sign8 = sign7 | (bitCount(sign7) << 7); const uint sign = sign8 >> (iqs % 8); const u8vec4 grid = unpack8(iq3xxs_grid[qs]); bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; bool sign2 = (sign & 4) != 0; bool sign3 = (sign & 8) != 0; return db * vec4( grid.x * (sign0 ? -1.0 : 1.0), grid.y * (sign1 ? -1.0 : 1.0), grid.z * (sign2 ? -1.0 : 1.0), grid.w * (sign3 ? -1.0 : 1.0) );}#endif
#if defined(DATA_A_IQ3_S)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint qs = data_a[a_offset + ib].qs[iqs / 4]; const uint qh = data_a[a_offset + ib].qh[iqs / 32]; const uint sign = data_a[a_offset + ib].signs[iqs / 8] >> (iqs % 8); const uint scale = data_a[a_offset + ib].scales[iqs / 64]; bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; const float db = 1 + 2 * ((scale >> (4 * ((iqs / 32) & 1))) & 0xf); const uint32_t grid = iq3s_grid[qs | ((qh << (8 - ((iqs / 4) % 8))) & 256)] >> (8 * (iqs % 4)); return db * vec2( int(grid & 0xFF) * (sign0 ? -1.0 : 1.0), int((grid >> 8) & 0xFF) * (sign1 ? -1.0 : 1.0) );}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint ib4 = iqs / 4; const uint ib32 = iqs / 32; const uint qs = data_a[a_offset + ib].qs[ib4]; const uint qh = data_a[a_offset + ib].qh[ib32]; const uint sign = data_a[a_offset + ib].signs[iqs / 8] >> (iqs % 8); const uint scale = data_a[a_offset + ib].scales[ib32 / 2]; bool sign0 = (sign & 1) != 0; bool sign1 = (sign & 2) != 0; bool sign2 = (sign & 4) != 0; bool sign3 = (sign & 8) != 0; const float db = 1 + 2 * ((scale >> (4 * (ib32 & 1))) & 0xf); const uint32_t grid = iq3s_grid[qs | ((qh << (8 - ib4 % 8)) & 256)] >> (8 * (iqs % 4)); return db * vec4( int(grid & 0xFF) * (sign0 ? -1.0 : 1.0), int((grid >> 8) & 0xFF) * (sign1 ? -1.0 : 1.0), int((grid >> 16) & 0xFF) * (sign2 ? -1.0 : 1.0), int((grid >> 24) & 0xFF) * (sign3 ? -1.0 : 1.0) );}#endif
#if defined(DATA_A_IQ4_XS)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint iq = 16 * ib32 + (iqs % 16);
const uint sl = (data_a[a_offset + ib].scales_l[ib32/2] >> (4 * (ib32 & 1))) & 0xF; const uint sh = (data_a[a_offset + ib].scales_h >> (2 * ib32)) & 3; const uint qshift = (iqs & 16) >> 2; u8vec2 qs = u8vec2(data_a[a_offset + ib].qs[iq], data_a[a_offset + ib].qs[iq + 1]); qs = (qs >> qshift) & uint8_t(0xF);
const float dl = float(int(sl | (sh << 4)) - 32); return dl * vec2(kvalues_iq4nl[qs.x], kvalues_iq4nl[qs.y]);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint ib32 = iqs / 32; const uint iq = 16 * ib32 + (iqs % 16);
const uint sl = (data_a[a_offset + ib].scales_l[ib32/2] >> (4 * (ib32 & 1))) & 0xF; const uint sh = (data_a[a_offset + ib].scales_h >> (2 * ib32)) & 3; const uint qshift = (iqs & 16) >> 2; const u8vec4 qs = unpack8((data_a_packed32[a_offset + ib].qs[iq/4] >> qshift) & 0x0F0F0F0F);
const float dl = float(int(sl | (sh << 4)) - 32); return dl * vec4( kvalues_iq4nl[qs.x], kvalues_iq4nl[qs.y], kvalues_iq4nl[qs.z], kvalues_iq4nl[qs.w]);}#endif
#if defined(DATA_A_IQ4_NL)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint vui = uint(data_a[a_offset + ib].qs[iqs]); return vec2(kvalues_iq4nl[vui & 0xF], kvalues_iq4nl[vui >> 4]);}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const uint vui = uint(data_a_packed16[a_offset + ib].qs[iqs/2]); return vec4(kvalues_iq4nl[vui & 0xF], kvalues_iq4nl[(vui >> 4) & 0xF], kvalues_iq4nl[(vui >> 8) & 0xF], kvalues_iq4nl[vui >> 12]);}#endif
#if defined(DATA_A_MXFP4)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint vui = uint(data_a[a_offset + ib].qs[iqs]); return vec2(kvalues_mxfp4[vui & 0xF], kvalues_mxfp4[vui >> 4]) * 0.5;}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { vec2 v0 = dequantize(ib, iqs, a_offset); vec2 v1 = dequantize(ib, iqs + 1, a_offset); return vec4(v0.x, v0.y, v1.x, v1.y);}#endif
#if defined(DATA_A_NVFP4)vec2 dequantize(uint ib, uint iqs, uint a_offset) { const uint sub = iqs >> 4; const float d = ue4m3_to_fp32(data_a[a_offset + ib].d[sub]); const uint j = iqs & 7; const uint shift = (iqs & 8) >> 1; // 0 or 4 const uint vui0 = uint(data_a[a_offset + ib].qs[sub * 8u + j]); const uint vui1 = uint(data_a[a_offset + ib].qs[sub * 8u + j + 1]); const uint qs0 = (vui0 >> shift) & 0xF; const uint qs1 = (vui1 >> shift) & 0xF; return vec2(float(kvalues_mxfp4[qs0]), float(kvalues_mxfp4[qs1])) * d * 0.5;}vec4 dequantize4(uint ib, uint iqs, uint a_offset) { const vec2 v0 = dequantize(ib, iqs, a_offset); const vec2 v1 = dequantize(ib, iqs + 2u, a_offset); return vec4(v0.x, v0.y, v1.x, v1.y);}#endif
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)vec2 get_dm(uint ib, uint a_offset) { return vec2(0, 0);}#endif
#if defined(DATA_A_IQ1_M)vec2 get_dm(uint ib, uint a_offset) { const uint16_t[4] scales = data_a[a_offset + ib].scales; const u16vec4 s = u16vec4(scales[0], scales[1], scales[2], scales[3]) >> 12; const float d = float(unpackHalf2x16(s.x | (s.y << 4) | (s.z << 8) | (s.w << 12)).x); return vec2(d, 0);}#endif
#if defined(DATA_A_Q4_0) || defined(DATA_A_Q5_0) || defined(DATA_A_Q8_0) || defined(DATA_A_IQ1_S) || defined(DATA_A_IQ2_XXS) || defined(DATA_A_IQ2_XS) || defined(DATA_A_IQ2_S) || defined(DATA_A_IQ3_XXS) || defined(DATA_A_IQ3_S) || defined(DATA_A_IQ4_XS) || defined(DATA_A_IQ4_NL)vec2 get_dm(uint ib, uint a_offset) { return vec2(float(data_a[a_offset + ib].d), 0);}#endif
#if defined(DATA_A_Q1_0)vec2 get_dm(uint ib, uint a_offset) { const float d = float(data_a[a_offset + ib].d); return vec2(d, 0);}#endif
#if defined(DATA_A_MXFP4)vec2 get_dm(uint ib, uint a_offset) { return vec2(e8m0_to_fp32(data_a[a_offset + ib].e), 0);}#endif
#if defined(DATA_A_NVFP4)vec2 get_dm(uint ib, uint a_offset) { return vec2(1.0, 0.0);}#endif
#if defined(DATA_A_Q4_1) || defined(DATA_A_Q5_1)vec2 get_dm(uint ib, uint a_offset) { const vec2 dm = vec2(data_a_packed32[a_offset + ib].dm); return dm;}#endif
#if defined(DATA_A_Q2_K)vec2 dequantize(uint ib, uint iqs, uint a_offset) { iqs /= 2; const uint qsi = (iqs / 64) * 32 + (iqs % 16) * 2; // 0,2,4..30 const uint scalesi = iqs / 8; // 0..15 const uint qsshift = ((iqs % 64) / 16) * 2; // 0,2,4,6
const uvec2 qs = uvec2(data_a[a_offset + ib].qs[qsi], data_a[a_offset + ib].qs[qsi + 1]); const uint scales = data_a[a_offset + ib].scales[scalesi]; const vec2 dm = vec2(data_a[a_offset + ib].dm);
return dm.x * float(scales & 0xF) * vec2((qs >> qsshift) & 3) - dm.y * float(scales >> 4);}vec2 get_dm(uint ib, uint a_offset) { return vec2(1, 0);}#endif
#if defined(DATA_A_Q3_K)vec2 dequantize(uint ib, uint iqs, uint a_offset) { iqs /= 2; const uint n = iqs / 64; // 0,1 const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..62 const uint hmi = (iqs % 16) * 2; // 0,2,4..30 const uint j = (iqs % 64) / 4; // 0..3 const uint is = iqs / 8; // 0..15 const uint halfsplit = ((iqs % 64) / 16); // 0,1,2,3 const uint qsshift = halfsplit * 2; // 0,2,4,6 const uint m = 1 << (4 * n + halfsplit); // 1,2,4,8,16,32,64,128
const int8_t us = int8_t(((data_a[a_offset + ib].scales[is % 8] >> (4 * int(is / 8))) & 0xF) | (((data_a[a_offset + ib].scales[8 + (is % 4)] >> (2 * int(is / 4))) & 3) << 4)); const float dl = float(data_a[a_offset + ib].d) * float(us - 32);
return vec2(dl * float(int8_t((data_a[a_offset + ib].qs[qsi ] >> qsshift) & 3) - (((data_a[a_offset + ib].hmask[hmi ] & m) != 0) ? 0 : 4)), dl * float(int8_t((data_a[a_offset + ib].qs[qsi + 1] >> qsshift) & 3) - (((data_a[a_offset + ib].hmask[hmi + 1] & m) != 0) ? 0 : 4)));}vec2 get_dm(uint ib, uint a_offset) { return vec2(1, 0);}#endif
#if defined(DATA_A_Q4_K)vec2 dequantize(uint ib, uint iqs, uint a_offset) { iqs /= 2; const uint n = iqs / 32; // 0,1,2,3 const uint b = (iqs % 32) / 16; // 0,1 const uint is = 2 * n + b; // 0..7 const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..126
const vec2 loadd = vec2(data_a[a_offset + ib].dm);
const uint scidx0 = (is < 4) ? is : (is + 4); const uint scidx1 = (is < 4) ? is : (is - 4); const uint scidxmask1 = (is < 4) ? 0x30 : 0xC0; const uint scidxshift1 = (is < 4) ? 0 : 2; const uint mbidx0 = is + 4; const uint mbidx1 = (is < 4) ? is + 4 : is; const uint mbidxmask0 = (is < 4) ? 0xF : 0xF0; const uint mbidxshift0 = (is < 4) ? 0 : 4; const uint mbidxmask1 = (is < 4) ? 0x30 : 0xC0; const uint mbidxshift1 = (is < 4) ? 0 : 2;
const uint8_t sc = uint8_t((data_a[a_offset + ib].scales[scidx0] & 0xF) | ((data_a[a_offset + ib].scales[scidx1] & scidxmask1) >> scidxshift1)); const uint8_t mbyte = uint8_t((data_a[a_offset + ib].scales[mbidx0] & mbidxmask0) >> mbidxshift0 | ((data_a[a_offset + ib].scales[mbidx1] & mbidxmask1) >> mbidxshift1));
const float d = loadd.x * sc; const float m = -loadd.y * mbyte;
return vec2(fma(d, float((data_a[a_offset + ib].qs[qsi ] >> (b * 4)) & 0xF), m), fma(d, float((data_a[a_offset + ib].qs[qsi + 1] >> (b * 4)) & 0xF), m));}vec2 get_dm(uint ib, uint a_offset) { return vec2(1, 0);}#endif
#if defined(DATA_A_Q5_K)vec2 dequantize(uint ib, uint iqs, uint a_offset) { iqs /= 2; const uint n = iqs / 32; // 0,1,2,3 const uint b = (iqs % 32) / 16; // 0,1 const uint is = 2 * n + b; // 0..7 const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..126 const uint qhi = (iqs % 16) * 2; // 0,2,4..30
const uint8_t hm = uint8_t(1 << (iqs / 16));
const vec2 loadd = vec2(data_a[a_offset + ib].dm);
const uint scidx0 = (is < 4) ? is : (is + 4); const uint scidx1 = (is < 4) ? is : (is - 4); const uint scidxmask1 = (is < 4) ? 0x30 : 0xC0; const uint scidxshift1 = (is < 4) ? 0 : 2; const uint mbidx0 = is + 4; const uint mbidx1 = (is < 4) ? is + 4 : is; const uint mbidxmask0 = (is < 4) ? 0xF : 0xF0; const uint mbidxshift0 = (is < 4) ? 0 : 4; const uint mbidxmask1 = (is < 4) ? 0x30 : 0xC0; const uint mbidxshift1 = (is < 4) ? 0 : 2;
const uint8_t sc = uint8_t((data_a[a_offset + ib].scales[scidx0] & 0xF) | ((data_a[a_offset + ib].scales[scidx1] & scidxmask1) >> scidxshift1)); const uint8_t mbyte = uint8_t(((data_a[a_offset + ib].scales[mbidx0] & mbidxmask0) >> mbidxshift0) | ((data_a[a_offset + ib].scales[mbidx1] & mbidxmask1) >> mbidxshift1));
const float d = loadd.x * sc; const float m = -loadd.y * mbyte;
return vec2(fma(d, float((data_a[a_offset + ib].qs[qsi ] >> (b * 4)) & 0xF) + float((data_a[a_offset + ib].qh[qhi ] & hm) != 0 ? 16 : 0), m), fma(d, float((data_a[a_offset + ib].qs[qsi + 1] >> (b * 4)) & 0xF) + float((data_a[a_offset + ib].qh[qhi + 1] & hm) != 0 ? 16 : 0), m));}vec2 get_dm(uint ib, uint a_offset) { return vec2(1, 0);}#endif
#if defined(DATA_A_Q6_K)vec2 dequantize(uint ib, uint iqs, uint a_offset) { iqs /= 2; const uint n = iqs / 64; // 0,1 const uint b = (iqs % 64) / 32; // 0,1 const uint is_b = (iqs % 16) / 8; // 0,1 const uint qhshift = ((iqs % 64) / 16) * 2; // 0,2,4,6 const uint is = 8 * n + qhshift + is_b; // 0..15 const uint qsi = n * 64 + (iqs % 32) * 2; // 0,2,4..126 const uint qhi = n * 32 + (iqs % 16) * 2; // 0,2,4..62
const float dscale = float(data_a[a_offset + ib].d) * float(data_a[a_offset + ib].scales[is]);
return vec2(dscale * float(int8_t(((data_a[a_offset + ib].ql[qsi ] >> (b * 4)) & 0xF) | (((data_a[a_offset + ib].qh[qhi ] >> qhshift) & 3) << 4)) - 32), dscale * float(int8_t(((data_a[a_offset + ib].ql[qsi + 1] >> (b * 4)) & 0xF) | (((data_a[a_offset + ib].qh[qhi + 1] >> qhshift) & 3) << 4)) - 32));}vec2 get_dm(uint ib, uint a_offset) { return vec2(1, 0);}#endif12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
// Each format defines a scalar dequantFunc<T> plus a V=4 dequantFunc<T>_v// passed as the optional vector decoder to coopMatLoadTensorNV via// GL_NV_cooperative_matrix_decode_vector. When the driver doesn't support// the extension, ggml-vulkan.cpp strips it from the compiled SPIR-V.#ifdef GL_NV_cooperative_matrix_decode_vector#extension GL_NV_cooperative_matrix_decode_vector : enable#endif
#include "types.glsl"
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufF32 { vec4 block;};
float16_t dequantFuncF32(const in decodeBufF32 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const vec4 v = bl.block; const uint idx = coordInBlock[1]; const f16vec4 vf16 = f16vec4(v); return vf16[idx];}
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ1_0 { block_q1_0 block;};
float16_t dequantFuncQ1_0(const in decodeBufQ1_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint bit = (uint(bl.block.qs[(idx & 0x78) >> 3]) >> (idx & 0x7)) & 1u; return bit != 0u ? d : -d;}
f16vec4 dequantFuncQ1_0_v(const in decodeBufQ1_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const float16_t md = -d; const uint idx = coordInBlock[1]; const uint qs_nib = uint(bl.block.qs[idx >> 3]) >> (idx & 0x4u); return f16vec4( (qs_nib & 1u) != 0u ? d : md, (qs_nib & 2u) != 0u ? d : md, (qs_nib & 4u) != 0u ? d : md, (qs_nib & 8u) != 0u ? d : md);}
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ4_0 { block_q4_0_packed16 block;};
float16_t dequantFuncQ4_0(const in decodeBufQ4_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint shift = (idx & 0x10) >> 2; uint32_t qs = uint32_t(bl.block.qs[(idx & 0xE) >> 1]); qs >>= shift; qs &= 0x0F0F; qs = unpack8(qs)[idx & 1]; float16_t ret = (float16_t(qs) - float16_t(8)) * d; return ret;}
f16vec4 dequantFuncQ4_0_v(const in decodeBufQ4_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint shift = (idx & 0x10) >> 2; // 0 or 4 const uint qs_i = (idx & 0xE) >> 1; // even, in {0,2,4,6} const uint qsw = uint32_t(bl.block.qs[qs_i ]) | (uint32_t(bl.block.qs[qs_i + 1u]) << 16); // shift in {0,4}: per-byte mask 0x0F isolates the wanted nibble in each byte. const uint q4 = (qsw >> shift) & 0x0F0F0F0Fu; const u8vec4 q = unpack8(q4); return f16vec4((vec4(q) - vec4(8.0)) * vec4(float(d)));}
layout(buffer_reference, std430, buffer_reference_align = 4) buffer decodeBufQ4_1 { block_q4_1 block;};
layout(buffer_reference, std430, buffer_reference_align = 4) buffer decodeBufQ4_1_packed32 { block_q4_1_packed32 block;};
float16_t dequantFuncQ4_1(const in decodeBufQ4_1 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const float16_t m = bl.block.m; const uint idx = coordInBlock[1]; const uint iqs = idx & 0xF; const uint shift = (idx & 0x10) >> 2; uint32_t qs = bl.block.qs[iqs]; qs >>= shift; qs &= 0xF; float16_t ret = float16_t(qs) * d + m; return ret;}
f16vec4 dequantFuncQ4_1_v(const in decodeBufQ4_1 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ4_1_packed32 bl32 = decodeBufQ4_1_packed32(bl); const float16_t d = bl.block.d; const float16_t m = bl.block.m; const uint idx = coordInBlock[1]; const uint shift = (idx & 0x10) >> 2; // 0 or 4 const uint qs_w = (idx & 0xC) >> 2; // iqs / 4 in [0,4) const uint qsw = uint32_t(bl32.block.qs[qs_w]); const u8vec4 q = unpack8((qsw >> shift) & 0x0F0F0F0Fu); return f16vec4(vec4(q) * vec4(float(d)) + vec4(float(m)));}
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ5_0 { block_q5_0 block;};
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ5_0_packed16 { block_q5_0_packed16 block;};
float16_t dequantFuncQ5_0(const in decodeBufQ5_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint iqs = idx & 0xF;
const uint uint_qh = uint(bl.block.qh[1]) << 16 | bl.block.qh[0]; const uint qh = ((uint_qh >> idx) << 4) & 0x10;
const uint shift = (idx & 0x10) >> 2; uint32_t qs = bl.block.qs[iqs]; qs >>= shift; qs &= 0xF;
float16_t ret = (float16_t(qs | qh) - float16_t(16)) * d; return ret;}
f16vec4 dequantFuncQ5_0_v(const in decodeBufQ5_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ5_0_packed16 bl16 = decodeBufQ5_0_packed16(bl); const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint shift = (idx & 0x10) >> 2; // 0 or 4 const uint qs_i = (idx & 0xC) >> 1; // packed16 word index, in {0,2,4,6} const uint qsw = uint32_t(bl16.block.qs[qs_i ]) | (uint32_t(bl16.block.qs[qs_i + 1u]) << 16); const u8vec4 ql = unpack8((qsw >> shift) & 0x0F0F0F0Fu);
const uint uint_qh = uint(bl16.block.qh[1]) << 16 | uint(bl16.block.qh[0]); const uint qh_pack = uint_qh >> idx; // bits 0..3 = element idx..idx+3 high bits const uvec4 qh_high = (uvec4(qh_pack, qh_pack >> 1u, qh_pack >> 2u, qh_pack >> 3u) & uvec4(0x01u)) << 4u;
return f16vec4((vec4(ql) + vec4(qh_high) - vec4(16.0)) * vec4(float(d)));}
layout(buffer_reference, std430, buffer_reference_align = 8) buffer decodeBufQ5_1 { block_q5_1 block;};
layout(buffer_reference, std430, buffer_reference_align = 8) buffer decodeBufQ5_1_packed32 { block_q5_1_packed32 block;};
float16_t dequantFuncQ5_1(const in decodeBufQ5_1 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const float16_t m = bl.block.m; const uint idx = coordInBlock[1]; const uint iqs = idx & 0xF;
const uint uint_qh = bl.block.qh; const uint qh = ((uint_qh >> idx) << 4) & 0x10;
const uint shift = (idx & 0x10) >> 2; uint32_t qs = bl.block.qs[iqs]; qs >>= shift; qs &= 0xF;
float16_t ret = float16_t(qs | qh) * d + m; return ret;}
f16vec4 dequantFuncQ5_1_v(const in decodeBufQ5_1 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ5_1_packed32 bl32 = decodeBufQ5_1_packed32(bl); const float16_t d = bl.block.d; const float16_t m = bl.block.m; const uint idx = coordInBlock[1]; const uint shift = (idx & 0x10) >> 2; // 0 or 4 const uint qs_w = (idx & 0xC) >> 2; // iqs / 4 in [0,4) const uint qsw = uint32_t(bl32.block.qs[qs_w]); const u8vec4 ql = unpack8((qsw >> shift) & 0x0F0F0F0Fu);
const uint qh_pack = bl.block.qh >> idx; // bits 0..3 = element idx..idx+3 high bits const uvec4 qh_high = (uvec4(qh_pack, qh_pack >> 1u, qh_pack >> 2u, qh_pack >> 3u) & uvec4(0x01u)) << 4u;
return f16vec4((vec4(ql) + vec4(qh_high)) * vec4(float(d)) + vec4(float(m)));}
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ8_0 { block_q8_0_packed16 block;};
float16_t dequantFuncQ8_0(const in decodeBufQ8_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint iqs = idx;
// Load 16b and select the byte for this element int32_t qs = unpack8(bl.block.qs[(iqs & 0x1E) >> 1])[iqs & 1]; float16_t ret = float16_t(qs) * d; return ret;}
f16vec4 dequantFuncQ8_0_v(const in decodeBufQ8_0 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint base = idx >> 1u; const uint w = uint(uint16_t(bl.block.qs[base])) | (uint(uint16_t(bl.block.qs[base + 1u])) << 16u); const i8vec4 qi = unpack8(int32_t(w)); return f16vec4(vec4(qi) * vec4(float(d)));}
layout(buffer_reference, std430, buffer_reference_align = 4) buffer decodeBufQ2_K { block_q2_K block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ2_K_packed16 { block_q2_K_packed16 block;};
layout(buffer_reference, std430, buffer_reference_align = 4) buffer decodeBufQ2_K_packed32 { block_q2_K_packed32 block;};
float16_t dequantFuncQ2_K(const in decodeBufQ2_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ2_K_packed16 bl16 = decodeBufQ2_K_packed16(bl); const f16vec2 dm = bl.block.dm; const uint idx = coordInBlock[1];
const uint scalesi = (idx & 0xF0) >> 4; // 0..15 const uint qsshift = (idx & 0x60) >> 4; // 0,2,4,6
uint qs = uint32_t(bl16.block.qs[((idx & 0x80) >> 3) + ((idx & 0x1E) >> 1)]); qs = (qs >> qsshift) & 0x0303; qs = unpack8(qs)[idx & 1];
const uint scales = bl.block.scales[scalesi]; float16_t ret = dm.x * float16_t(scales & 0xF) * float16_t(qs) - dm.y * float16_t(scales >> 4); return ret;}
f16vec4 dequantFuncQ2_K_v(const in decodeBufQ2_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ2_K_packed32 bl32 = decodeBufQ2_K_packed32(bl); const f16vec2 dm = bl.block.dm; const uint idx = coordInBlock[1];
const uint scalesi = idx >> 4; // 0..15 const uint qsshift = (idx & 0x60) >> 4; // 0,2,4,6
// qs_i (packed16) = ((idx & 0x80) >> 3) + ((idx & 0x1E) >> 1) is even for idx % 4 == 0, // so qs_w (packed32) = qs_i / 2 = ((idx & 0x80) >> 4) + ((idx & 0x1Cu) >> 2). const uint qs_w = ((idx & 0x80) >> 4) + ((idx & 0x1Cu) >> 2); const uint qsw = uint32_t(bl32.block.qs[qs_w]); const uint qs4 = (qsw >> qsshift) & 0x03030303u; const u8vec4 qi = unpack8(qs4);
const uint scales = bl.block.scales[scalesi]; const float16_t d_sub = dm.x * float16_t(scales & 0xF); const float16_t m_sub = dm.y * float16_t(scales >> 4); return f16vec4(vec4(qi) * vec4(float(d_sub)) - vec4(float(m_sub)));}
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ3_K { block_q3_K block;};
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ3_K_packed16 { block_q3_K_packed16 block;};
float16_t dequantFuncQ3_K(const in decodeBufQ3_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const uint idx = coordInBlock[1]; const uint iqs = idx;
const uint n = iqs / 128; // 0,1 const uint qsi = n * 32 + (iqs % 32); // 0..63 const uint hmi = (iqs % 32); // 0..31 const uint j = (iqs % 128) / 8; // 0..15 const uint is = iqs / 16; // 0..15 const uint halfsplit = ((iqs % 128) / 32); // 0,1,2,3 const uint qsshift = halfsplit * 2; // 0,2,4,6 const uint m = 1 << (4 * n + halfsplit); // 1,2,4,8,16,32,64,128
uint32_t scaleidx0 = (is < 8) ? is : (is-8); uint32_t scaleidx0shift = (is < 8) ? 0 : 4; uint32_t scaleidx1 = is + 8 - (is/4)*4; uint32_t scaleidx1shift = (is/4)*2;
const int8_t us = int8_t(((bl.block.scales[scaleidx0] >> scaleidx0shift) & 0xF) | (((bl.block.scales[scaleidx1] >> scaleidx1shift) & 3) << 4));
const float16_t dl = bl.block.d * float16_t(us - 32);
float16_t ret = dl * float16_t(int8_t((bl.block.qs[qsi ] >> qsshift) & 3) - (((bl.block.hmask[hmi ] & m) != 0) ? 0 : 4));
return ret;}
f16vec4 dequantFuncQ3_K_v(const in decodeBufQ3_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ3_K_packed16 bl16 = decodeBufQ3_K_packed16(bl); const uint idx = coordInBlock[1];
const uint n = idx >> 7; // 0,1 const uint is = idx >> 4; // 0..15 const uint halfsplit = (idx & 0x60) >> 5; // 0,1,2,3 const uint qsshift = halfsplit << 1; // 0,2,4,6 const uint hbit = (n << 2) + halfsplit; // 0..7 (bit position in hmask byte)
uint32_t scaleidx0 = (is < 8) ? is : (is - 8); uint32_t scaleidx0shift = (is < 8) ? 0u : 4u; uint32_t scaleidx1 = is + 8 - (is / 4) * 4; uint32_t scaleidx1shift = (is / 4) * 2;
const int8_t us = int8_t( ((bl.block.scales[scaleidx0] >> scaleidx0shift) & 0xF) | (((bl.block.scales[scaleidx1] >> scaleidx1shift) & 3) << 4)); const float16_t dl = bl.block.d * float16_t(int(us) - 32);
// For idx % 4 == 0: (idx & 0x1F) == (idx & 0x1C) is a multiple of 4. const uint qsi = (n << 5) + (idx & 0x1Cu); const uint hmi = (idx & 0x1Cu);
// Two adjacent uint16 packed16 reads, combined into a uint32 in registers. // After this: byte j of qsw / hmw holds the data for element idx+j. const uint qsw = uint32_t(bl16.block.qs[qsi >> 1]) | (uint32_t(bl16.block.qs[(qsi >> 1) + 1u]) << 16); const uint hmw = uint32_t(bl16.block.hmask[hmi >> 1]) | (uint32_t(bl16.block.hmask[(hmi >> 1) + 1u]) << 16);
// qsshift in {0,2,4,6} and hbit in {0..7}: per-byte masks isolate the wanted bits // with no inter-byte leakage. const uint ql4 = (qsw >> qsshift) & 0x03030303u; const uint qh4 = (hmw >> hbit) & 0x01010101u;
const ivec4 q = ivec4(unpack8(ql4 | (qh4 << 2))) - ivec4(4); return f16vec4(vec4(q) * vec4(float(dl)));}
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ4_K { block_q4_K block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ4_K_packed16 { block_q4_K_packed16 block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ4_K_packed32 { block_q4_K_packed32 block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ4_K_packed128 { block_q4_K_packed128 block;};
#if defined(IS_MUL_MM2)
// For Q4_K and Q5_K in the mat-mul shader, we decode a tile's worth of scales// into shared memory and then process the whole tile using those scales.// There is a fetch function that loads into private variables and then a store// function that stores into shared memory.// Q4_K and Q5_K have the same encoding of scales, so everything is shared except// the part that fetches from the structure (which has a different block layout).#if defined(DATA_A_Q4_K) || defined(DATA_A_Q5_K)const uint shAscales_stride = (BM + 2);// 1 scale per 32 elements -> 8 scales per block, per rowshared vec2 shAscales[8 * shAscales_stride];uvec4 row_v;#endif
#if defined(DATA_A_Q4_K)layout (binding = 0) readonly buffer A_Q4_K_128 {block_q4_K_packed128 data_a_q4_k_packed128[];};
void fetch_scalesQ4_K(uint ir_BM, uint pos_a, uint stride_a, uint block_k, uint tid, bool in_bounds){ uint tids_per_row = BLOCK_SIZE / BM; uint is_per_tid = 8 / tids_per_row; uint is_start = is_per_tid * (tid % tids_per_row); uint tid_row = tid / tids_per_row;
uint row = ir_BM + tid_row; uint block_index = pos_a + row * stride_a + (block_k / QUANT_K); if (in_bounds || row < p.M) { row_v = data_a_q4_k_packed128[block_index].q4k[0]; }}#endif#if defined(DATA_A_Q5_K)layout (binding = 0) readonly buffer A_Q5_K_128 {block_q5_K_packed128 data_a_q5_k_packed128[];};
void fetch_scalesQ5_K(uint ir_BM, uint pos_a, uint stride_a, uint block_k, uint tid, bool in_bounds){ uint tids_per_row = BLOCK_SIZE / BM; uint is_per_tid = 8 / tids_per_row; uint is_start = is_per_tid * (tid % tids_per_row); uint tid_row = tid / tids_per_row;
uint row = ir_BM + tid_row; uint block_index = pos_a + row * stride_a + (block_k / QUANT_K); if (in_bounds || row < p.M) { row_v = data_a_q5_k_packed128[block_index].q5k[0]; }}#endif
#if defined(DATA_A_Q4_K) || defined(DATA_A_Q5_K)void store_scalesQ4_K(uint tid){ barrier();
uint tids_per_row = BLOCK_SIZE / BM; uint is_per_tid = 8 / tids_per_row; uint is_start = is_per_tid * (tid % tids_per_row); uint tid_row = tid / tids_per_row;
[[unroll]] for (uint idx = 0; idx < is_per_tid; ++idx) { uint is = idx + is_start; uvec4 v = row_v; const vec2 loadd = vec2(unpackFloat2x16(v.x));
uint32_t sc; uint32_t mbyte;
uint32_t scale0 = v.y; uint32_t scale4 = v.z; uint32_t scale8 = v.w;
uint32_t sc_lo = scale0; uint32_t mb_lo = scale4; uint32_t sc_hi = (scale8 & 0x0F0F0F0F) | ((scale0 & 0xC0C0C0C0) >> 2); uint32_t mb_hi = ((scale8 & 0xF0F0F0F0) >> 4) | ((scale4 & 0xC0C0C0C0) >> 2);
sc = is < 4 ? sc_lo : sc_hi; mbyte = is < 4 ? mb_lo : mb_hi; sc = sc >> (8 * (is & 3)); mbyte = mbyte >> (8 * (is & 3)); sc &= 0x3F; mbyte &= 0x3F;
const float d = loadd.x * float(sc); const float m = loadd.y * float(mbyte); shAscales[is * shAscales_stride + tid_row] = vec2(d,m); }
barrier();}#endif
#endif
float16_t dequantFuncQ4_K(const in decodeBufQ4_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ4_K_packed16 bl16 = decodeBufQ4_K_packed16(bl); decodeBufQ4_K_packed128 bl128 = decodeBufQ4_K_packed128(bl); const uint idx = coordInBlock[1];
const uint b = (idx & 0x20) >> 5; // 0,1 const uint is = (idx & 0xE0) >> 5; // 0..7
#if defined(IS_MUL_MM2) && defined(DATA_A_Q4_K) vec2 v = shAscales[is * shAscales_stride + (blockCoords[0] % BM)]; float d = v.x; float m = v.y;#else uvec4 v = bl128.block.q4k[0]; const vec2 loadd = vec2(unpackFloat2x16(v.x));
uint32_t sc; uint32_t mbyte;
uint32_t scale0 = v.y; uint32_t scale4 = v.z; uint32_t scale8 = v.w;
uint32_t sc_lo = scale0; uint32_t mb_lo = scale4; uint32_t sc_hi = (scale8 & 0x0F0F0F0F) | ((scale0 & 0xC0C0C0C0) >> 2); uint32_t mb_hi = ((scale8 & 0xF0F0F0F0) >> 4) | ((scale4 & 0xC0C0C0C0) >> 2);
sc = is < 4 ? sc_lo : sc_hi; mbyte = is < 4 ? mb_lo : mb_hi; sc = sc >> (8 * (is & 3)); mbyte = mbyte >> (8 * (is & 3)); sc &= 0x3F; mbyte &= 0x3F;
const float d = loadd.x * float(sc); const float m = loadd.y * float(mbyte);#endif
uint qs = uint32_t(bl16.block.qs[((idx & 0xC0) >> 2) + ((idx & 0x1E) >> 1)]); qs = (qs >> (b * 4 + 8 * (idx & 1))) & 0xF;
float ret = d * float(qs) - m;
return float16_t(ret);}
f16vec4 dequantFuncQ4_K_v(const in decodeBufQ4_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ4_K_packed32 bl32 = decodeBufQ4_K_packed32(bl); decodeBufQ4_K_packed128 bl128 = decodeBufQ4_K_packed128(bl); const uint idx = coordInBlock[1];
const uint is = idx >> 5; // 0..7
#if defined(IS_MUL_MM2) && defined(DATA_A_Q4_K) vec2 v = shAscales[is * shAscales_stride + (blockCoords[0] % BM)]; float d = v.x; float m = v.y;#else uvec4 v = bl128.block.q4k[0]; const vec2 loadd = vec2(unpackFloat2x16(v.x));
uint32_t sc; uint32_t mbyte;
uint32_t scale0 = v.y; uint32_t scale4 = v.z; uint32_t scale8 = v.w;
uint32_t sc_lo = scale0; uint32_t mb_lo = scale4; uint32_t sc_hi = (scale8 & 0x0F0F0F0F) | ((scale0 & 0xC0C0C0C0) >> 2); uint32_t mb_hi = ((scale8 & 0xF0F0F0F0) >> 4) | ((scale4 & 0xC0C0C0C0) >> 2);
sc = is < 4 ? sc_lo : sc_hi; mbyte = is < 4 ? mb_lo : mb_hi; sc = sc >> (8 * (is & 3)); mbyte = mbyte >> (8 * (is & 3)); sc &= 0x3F; mbyte &= 0x3F;
const float d = loadd.x * float(sc); const float m = loadd.y * float(mbyte);#endif
// idx in [0,256); vector decode uses idx a multiple of 4. packed32 word index: // (qs_i >> 1) == (idx >> 6) * 8 + ((idx & 0x1E) >> 2). sh is 0 or 4 only, so a // single (w >> sh) & 0x0F0F0F0F isolates all four nibbles without inter-byte leakage. const uint sh = (idx & 0x20u) >> 3u; const uint w = uint32_t(bl32.block.qs[(idx >> 6) * 8u + ((idx & 0x1Eu) >> 2)]); const u8vec4 q = unpack8((w >> sh) & 0x0F0F0F0Fu);
return f16vec4(vec4(d) * vec4(q) - vec4(m));}
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ5_K { block_q5_K block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ5_K_packed16 { block_q5_K_packed16 block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ5_K_packed128 { block_q5_K_packed128 block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ5_K_packed32 { block_q5_K_packed32 block;};
float16_t dequantFuncQ5_K(const in decodeBufQ5_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ5_K_packed16 bl16 = decodeBufQ5_K_packed16(bl); decodeBufQ5_K_packed128 bl128 = decodeBufQ5_K_packed128(bl); const uint idx = coordInBlock[1];
const uint b = (idx & 0x20) >> 5; // 0,1 const uint is = (idx & 0xE0) >> 5; // 0..7
#if defined(IS_MUL_MM2) && defined(DATA_A_Q5_K) vec2 v = shAscales[is * shAscales_stride + (blockCoords[0] % BM)]; float d = v.x; float m = v.y;#else uvec4 v = bl128.block.q5k[0];
const f16vec2 loadd = unpackFloat2x16(v.x);
uint32_t sc; uint32_t mbyte;
uint32_t scale0 = v.y; uint32_t scale4 = v.z; uint32_t scale8 = v.w;
uint32_t sc_lo = scale0; uint32_t mb_lo = scale4; uint32_t sc_hi = (scale8 & 0x0F0F0F0F) | ((scale0 & 0xC0C0C0C0) >> 2); uint32_t mb_hi = ((scale8 & 0xF0F0F0F0) >> 4) | ((scale4 & 0xC0C0C0C0) >> 2);
sc = is < 4 ? sc_lo : sc_hi; mbyte = is < 4 ? mb_lo : mb_hi; sc = sc >> (8 * (is & 3)); mbyte = mbyte >> (8 * (is & 3)); sc &= 0x3F; mbyte &= 0x3F;
const float16_t d = loadd.x * float16_t(sc); const float16_t m = loadd.y * float16_t(mbyte);#endif
uint qh = uint32_t(bl16.block.qh[(idx & 0x1E) >> 1]); qh = ((qh >> is) & 0x101) << 4;
uint qs = uint32_t(bl16.block.qs[((idx & 0xC0) >> 2) + ((idx & 0x1E) >> 1)]); qs = (qs >> (b * 4)) & 0x0F0F; qs = unpack8(qs | qh)[idx & 1];
float ret = d * float(qs) - m;
return float16_t(ret);}
f16vec4 dequantFuncQ5_K_v(const in decodeBufQ5_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ5_K_packed32 bl32 = decodeBufQ5_K_packed32(bl); decodeBufQ5_K_packed128 bl128 = decodeBufQ5_K_packed128(bl); const uint idx = coordInBlock[1]; const uint is = idx >> 5;
#if defined(IS_MUL_MM2) && defined(DATA_A_Q5_K) vec2 v = shAscales[is * shAscales_stride + (blockCoords[0] % BM)]; float d = v.x; float m = v.y;#else uvec4 v = bl128.block.q5k[0];
const f16vec2 loadd = unpackFloat2x16(v.x);
uint32_t sc; uint32_t mbyte;
uint32_t scale0 = v.y; uint32_t scale4 = v.z; uint32_t scale8 = v.w;
uint32_t sc_lo = scale0; uint32_t mb_lo = scale4; uint32_t sc_hi = (scale8 & 0x0F0F0F0F) | ((scale0 & 0xC0C0C0C0) >> 2); uint32_t mb_hi = ((scale8 & 0xF0F0F0F0) >> 4) | ((scale4 & 0xC0C0C0C0) >> 2);
sc = is < 4 ? sc_lo : sc_hi; mbyte = is < 4 ? mb_lo : mb_hi; sc = sc >> (8 * (is & 3)); mbyte = mbyte >> (8 * (is & 3)); sc &= 0x3F; mbyte &= 0x3F;
const float16_t d = loadd.x * float16_t(sc); const float16_t m = loadd.y * float16_t(mbyte);#endif
// sh is 0 or 4; mask 0x0F0F0F0F covers the four nibbles regardless (no inter-byte leakage). const uint sh = (idx & 0x20u) >> 3u; const uint qs_w = (idx >> 6) * 8u + ((idx & 0x1Eu) >> 2); const uint qh_w = (idx & 0x1Eu) >> 2;
const uint ql4 = (uint32_t(bl32.block.qs[qs_w]) >> sh) & 0x0F0F0F0Fu; // qh stores bit `is` per element across 4 consecutive bytes; one shift+mask handles all 4. const uint qh4 = ((uint32_t(bl32.block.qh[qh_w]) >> is) & 0x01010101u) << 4u;
const u8vec4 qi = unpack8(ql4 | qh4); return f16vec4(vec4(qi) * vec4(d) - vec4(m));}
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufQ6_K { block_q6_K block;};
layout(buffer_reference, std430, buffer_reference_align = 16) buffer decodeBufQ6_K_packed16 { block_q6_K_packed16 block;};
float16_t dequantFuncQ6_K(const in decodeBufQ6_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ6_K_packed16 bl16 = decodeBufQ6_K_packed16(bl); const uint idx = coordInBlock[1];
const uint b = (idx & 0x40) >> 6; // 0,1 const uint qhshift = (idx & 0x60) >> 4; // 0,2,4,6 const uint is = (idx & 0xF0) >> 4; // 0..15
const float16_t dscale = bl.block.d * float16_t(bl.block.scales[is]);
uint ql = uint32_t(bl16.block.ql[((idx & 0x80) >> 2) + ((idx & 0x3E) >> 1)]); ql = (ql >> (b * 4)) & 0x0F0F;
uint qh = uint32_t(bl16.block.qh[((idx & 0x80) >> 3) + ((idx & 0x1E) >> 1)]); qh = ((qh >> qhshift) & 0x0303) << 4;
int q = unpack8(ql | qh)[idx & 1];
float16_t ret = dscale * float16_t(q - 32);
return ret;}
f16vec4 dequantFuncQ6_K_v(const in decodeBufQ6_K bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufQ6_K_packed16 bl16 = decodeBufQ6_K_packed16(bl); const uint idx = coordInBlock[1];
const uint b = (idx & 0x40) >> 6; const uint qhshift = (idx & 0x60) >> 4; // 0,2,4,6 const uint is = idx >> 4; const uint sh = b * 4; // 0 or 4
const float16_t dscale = bl.block.d * float16_t(bl.block.scales[is]);
const uint ql_i = ((idx & 0x80) >> 2) + ((idx & 0x3E) >> 1); const uint qh_i = ((idx & 0x80) >> 3) + ((idx & 0x1E) >> 1);
// Two adjacent uint16 packed16 reads, combined into a uint32 in registers. // After this: byte j of qlw / qhw holds the data for element idx+j. const uint qlw = uint32_t(bl16.block.ql[ql_i ]) | (uint32_t(bl16.block.ql[ql_i + 1]) << 16); const uint qhw = uint32_t(bl16.block.qh[qh_i ]) | (uint32_t(bl16.block.qh[qh_i + 1]) << 16);
// sh in {0,4} and qhshift in {0,2,4,6}: per-byte masks 0x0F / 0x03 keep only the // wanted bits with no inter-byte leakage; place qh's 2 bits at nibble high position. const uint ql4 = (qlw >> sh) & 0x0F0F0F0Fu; const uint qh4 = ((qhw >> qhshift) & 0x03030303u) << 4u;
const ivec4 qi = ivec4(unpack8(ql4 | qh4)); return f16vec4((vec4(qi) - vec4(32.0f)) * vec4(float(dscale)));}
#if defined(DATA_A_IQ1_S)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ1_S { block_iq1_s block;};
float16_t dequantFuncIQ1_S(const in decodeBufIQ1_S bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1];
const uint ib32 = (idx & 0xE0) >> 5; const uint ib8 = (idx & 0xF8) >> 3;
const uint qh = bl.block.qh[ib32]; const uint qs = bl.block.qs[ib8]; const float dl = d * float(2 * bitfieldExtract(qh, 12, 3) + 1); const float delta = ((qh & 0x8000) != 0) ? -IQ1S_DELTA : IQ1S_DELTA; const uint grid = iq1s_grid[qs | (bitfieldExtract(qh, 3 * int(ib8 & 3), 3) << 8)];
float16_t ret = float16_t(dl) * (float16_t(bitfieldExtract(int(grid), 2 * int(idx % 8), 2)) + float16_t(delta)); return ret;}
f16vec4 dequantFuncIQ1_S_v(const in decodeBufIQ1_S bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1];
const uint ib32 = idx >> 5; const uint ib8 = idx >> 3; const int i8b = int(idx & 4); // 0 or 4
const uint qh = bl.block.qh[ib32]; const uint qs = bl.block.qs[ib8]; const float dl = float(d) * float(2 * bitfieldExtract(qh, 12, 3) + 1); const float delta = ((qh & 0x8000u) != 0u) ? -IQ1S_DELTA : IQ1S_DELTA; const uint grid = iq1s_grid[qs | (bitfieldExtract(qh, 3 * int(ib8 & 3), 3) << 8)];
const ivec4 q = ivec4( bitfieldExtract(int(grid), 2 * (i8b + 0), 2), bitfieldExtract(int(grid), 2 * (i8b + 1), 2), bitfieldExtract(int(grid), 2 * (i8b + 2), 2), bitfieldExtract(int(grid), 2 * (i8b + 3), 2)); return f16vec4((vec4(q) + vec4(delta)) * dl);}#endif
#if defined(DATA_A_IQ1_M)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ1_M { block_iq1_m block;};
layout(buffer_reference, std430, buffer_reference_align = 8) buffer decodeBufIQ1_M_packed64 { block_iq1_m_packed64 block;};
float16_t dequantFuncIQ1_M(const in decodeBufIQ1_M bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ1_M_packed64 bl64 = decodeBufIQ1_M_packed64(bl); const uint idx = coordInBlock[1];
uvec2 scales = unpack32(bl64.block.scales); const float16_t d = uint16BitsToHalf(uint16_t(((scales.x & 0xF000) >> 12) | ((scales.x & 0xF0000000) >> 24) | ((scales.y & 0xF000) >> 4) | ((scales.y & 0xF0000000) >> 16)));
const uint ib8 = (idx & 0xF8) >> 3; const uint ib16 = (idx & 0xF0) >> 4; const int i8 = int(idx % 8); const uint sc = bl.block.scales[ib8 / 8]; const uint qs = bl.block.qs[ib8]; const uint qh = bl.block.qh[ib16] >> (4 * (ib8 & 1)); const float dl = 2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1; const float delta = ((qh & 8) != 0) ? -IQ1S_DELTA : IQ1S_DELTA; const uint grid = iq1s_grid[qs | ((qh & 7) << 8)];
float16_t ret = d * float16_t(dl) * (float16_t(bitfieldExtract(int(grid), 2 * i8, 2)) + float16_t(delta)); return ret;}
f16vec4 dequantFuncIQ1_M_v(const in decodeBufIQ1_M bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ1_M_packed64 bl64 = decodeBufIQ1_M_packed64(bl); const uint idx = coordInBlock[1];
uvec2 scales = unpack32(bl64.block.scales); const float16_t d = uint16BitsToHalf(uint16_t(((scales.x & 0xF000) >> 12) | ((scales.x & 0xF0000000) >> 24) | ((scales.y & 0xF000) >> 4) | ((scales.y & 0xF0000000) >> 16)));
const uint ib8 = idx >> 3; const uint ib16 = idx >> 4; const int i8b = int(idx & 4); // 0 or 4 -- i8 base for the V=4 group
const uint sc = bl.block.scales[ib8 / 8]; const uint qs = bl.block.qs[ib8]; const uint qh = bl.block.qh[ib16] >> (4 * (ib8 & 1)); const float dl = 2.0 * float(bitfieldExtract(sc, 3 * int(ib16 & 3), 3)) + 1.0; const float delta = ((qh & 8u) != 0u) ? -IQ1S_DELTA : IQ1S_DELTA; const uint grid = iq1s_grid[qs | ((qh & 7u) << 8)];
const ivec4 q = ivec4( bitfieldExtract(int(grid), 2 * (i8b + 0), 2), bitfieldExtract(int(grid), 2 * (i8b + 1), 2), bitfieldExtract(int(grid), 2 * (i8b + 2), 2), bitfieldExtract(int(grid), 2 * (i8b + 3), 2)); return f16vec4((vec4(q) + vec4(delta)) * (float(d) * dl));}#endif
#if defined(DATA_A_IQ2_XXS)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ2_XXS { block_iq2_xxs block;};
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ2_XXS_packed16 { block_iq2_xxs_packed16 block;};
float16_t dequantFuncIQ2_XXS(const in decodeBufIQ2_XXS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ2_XXS_packed16 bl16 = decodeBufIQ2_XXS_packed16(bl); const float16_t d = bl.block.d; const uint idx = coordInBlock[1];
const uint ib32 = (idx & 0xE0) >> 5; // 0..7 const uint ib8 = (idx & 0x18) >> 3; // 0..3 const uint iqs = 8 * ib32 + ib8;
const uint qs = bl.block.qs[iqs]; const uint signscale = pack32(u16vec2(bl16.block.qs[4*ib32+2], bl16.block.qs[4*ib32+3]));
const float dscale = float(bl.block.d) * 0.25 * (0.5 + float(signscale >> 28)); uint sign = bitfieldExtract(signscale, 7 * int(ib8), 7); sign |= bitCount(sign) << 7;
uint g2 = iq2xxs_grid[qs][(idx & 4) >> 2]; g2 >>= (idx & 2) * 8; const vec2 g = vec2(unpack8(g2));
vec2 ret = dscale * g * ((sign & (1 << (idx & 7))) != 0 ? -1.0hf : 1.0hf); return float16_t(ret[idx & 1]);}
f16vec4 dequantFuncIQ2_XXS_v(const in decodeBufIQ2_XXS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ2_XXS_packed16 bl16 = decodeBufIQ2_XXS_packed16(bl); const uint idx = coordInBlock[1];
const uint ib32 = idx >> 5; const uint ib8 = (idx & 0x18) >> 3; const uint iqs = 8 * ib32 + ib8;
const uint qs = bl.block.qs[iqs]; const uint signscale = pack32(u16vec2(bl16.block.qs[4*ib32+2], bl16.block.qs[4*ib32+3])); const float dscale = float(bl.block.d) * 0.25 * (0.5 + float(signscale >> 28));
uint sign = bitfieldExtract(signscale, 7 * int(ib8), 7); sign |= bitCount(sign) << 7; const uint sb = sign >> (idx & 7u);
const uint g2 = iq2xxs_grid[qs][(idx & 4) >> 2]; const u8vec4 g = unpack8(g2);
return f16vec4( dscale * float(g.x) * ((sb & 1u) != 0u ? -1.0 : 1.0), dscale * float(g.y) * ((sb & 2u) != 0u ? -1.0 : 1.0), dscale * float(g.z) * ((sb & 4u) != 0u ? -1.0 : 1.0), dscale * float(g.w) * ((sb & 8u) != 0u ? -1.0 : 1.0));}#endif
#if defined(DATA_A_IQ2_XS)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ2_XS { block_iq2_xs block;};
float16_t dequantFuncIQ2_XS(const in decodeBufIQ2_XS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1];
const uint is = (idx & 0xE0) >> 5; // 0..8 const uint sshift = (idx & 0x10) >> 2; // 0,4 const uint iqs = (idx & 0xF8) >> 3; // 0..63
const uint16_t qs = bl.block.qs[iqs]; const float dscale = float(bl.block.d) * 0.25 * (0.5 + float((bl.block.scales[is] >> sshift) & 0xF));
uint sign = uint(qs >> 9); sign |= bitCount(sign) << 7; uint g2 = iq2xs_grid[qs & 0x1FF][(idx & 4) >> 2]; g2 >>= (idx & 2) * 8; const vec2 g = vec2(unpack8(g2));
vec2 ret = dscale * g * ((sign & (1 << (idx & 7))) != 0 ? -1.0hf : 1.0hf); return float16_t(ret[idx & 1]);}
f16vec4 dequantFuncIQ2_XS_v(const in decodeBufIQ2_XS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const uint idx = coordInBlock[1];
const uint is = idx >> 5; const uint sshift = (idx & 0x10) >> 2; const uint iqs = idx >> 3;
const uint16_t qs = bl.block.qs[iqs]; const float dscale = float(bl.block.d) * 0.25 * (0.5 + float((bl.block.scales[is] >> sshift) & 0xF));
uint sign = uint(qs >> 9); sign |= bitCount(sign) << 7; const uint sb = sign >> (idx & 7u);
const uint g2 = iq2xs_grid[qs & 0x1FF][(idx & 4) >> 2]; const u8vec4 g = unpack8(g2);
return f16vec4( dscale * float(g.x) * ((sb & 1u) != 0u ? -1.0 : 1.0), dscale * float(g.y) * ((sb & 2u) != 0u ? -1.0 : 1.0), dscale * float(g.z) * ((sb & 4u) != 0u ? -1.0 : 1.0), dscale * float(g.w) * ((sb & 8u) != 0u ? -1.0 : 1.0));}#endif
#if defined(DATA_A_IQ2_S)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ2_S { block_iq2_s block;};
float16_t dequantFuncIQ2_S(const in decodeBufIQ2_S bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ uint idx = coordInBlock[1];
const uint ib32 = (idx & 0xE0) >> 5; // 0..7 const uint ib8 = (idx & 0xF8) >> 3; // 0..31 const uint qhshift = 2 * (ib8 % 4);
const uint scale = (bl.block.scales[ib32] >> ((idx & 0x10) >> 2)) & 0xf; const uint qs = bl.block.qs[ib8]; const uint qh = bl.block.qh[ib32]; const uint sign = bl.block.qs[QUANT_K / 8 + ib8] >> (idx & 0x6);
const float d = float(bl.block.d); const float db = d * 0.25 * (0.5 + scale); const ivec2 sign01 = 1 - (2 & ivec2(sign << 1, sign)); uint g2 = iq2s_grid[qs | ((qh << (8 - qhshift)) & 0x300)][(idx & 4) >> 2]; g2 >>= (idx & 2) * 8; const vec2 v = db * vec2(sign01) * vec2(unpack8(g2)); return float16_t(v[idx & 1]);}
f16vec4 dequantFuncIQ2_S_v(const in decodeBufIQ2_S bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const uint idx = coordInBlock[1];
const uint ib32 = idx >> 5; const uint ib8 = idx >> 3; const uint qhshift = 2 * (ib8 % 4);
const uint scale = (bl.block.scales[ib32] >> ((idx & 0x10) >> 2)) & 0xf; const uint qs = bl.block.qs[ib8]; const uint qh = bl.block.qh[ib32]; const uint sb = uint(bl.block.qs[QUANT_K / 8 + ib8]) >> (idx & 0x6u);
const float d = float(bl.block.d); const float db = d * 0.25 * (0.5 + scale);
const uint g2 = iq2s_grid[qs | ((qh << (8 - qhshift)) & 0x300)][(idx & 4) >> 2]; const u8vec4 g = unpack8(g2);
return f16vec4( db * float(g.x) * ((sb & 1u) != 0u ? -1.0 : 1.0), db * float(g.y) * ((sb & 2u) != 0u ? -1.0 : 1.0), db * float(g.z) * ((sb & 4u) != 0u ? -1.0 : 1.0), db * float(g.w) * ((sb & 8u) != 0u ? -1.0 : 1.0));}#endif
#if defined(DATA_A_IQ3_XXS)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ3_XXS { block_iq3_xxs block;};
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ3_XXS_packed16 { block_iq3_xxs_packed16 block;};
float16_t dequantFuncIQ3_XXS(const in decodeBufIQ3_XXS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ3_XXS_packed16 bl16 = decodeBufIQ3_XXS_packed16(bl); uint idx = coordInBlock[1];
const uint iqs = (idx & 0xFC) >> 2; // 0..63 const uint is = QUANT_K / 4 + ((idx & 0xE0) >> 3);// 8 values
const float d = float(bl.block.d); const uint qs = bl.block.qs[iqs]; const uint signs = pack32(u16vec2( bl16.block.qs[is/2+0], bl16.block.qs[is/2+1] )); const float db = d * 0.5 * (0.5 + (signs >> 28)); const uint32_t sign7 = bitfieldExtract(signs, 7 * (int(iqs / 2) % 4), 7); const uint sign = (sign7 | (bitCount(sign7) << 7)) >> (idx & 0x6); const ivec2 sign01 = ivec2(1 - (2 & ivec2(sign << 1, sign))); const uint grid = iq3xxs_grid[qs] >> (16 * ((idx & 2) >> 1)); const vec2 v = db * vec2(sign01) * vec2(unpack8(grid).xy); return float16_t(v[idx & 1]);}
f16vec4 dequantFuncIQ3_XXS_v(const in decodeBufIQ3_XXS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ3_XXS_packed16 bl16 = decodeBufIQ3_XXS_packed16(bl); const uint idx = coordInBlock[1];
const uint iqs = idx >> 2; const uint is = QUANT_K / 4 + ((idx & 0xE0) >> 3);
const float d = float(bl.block.d); const uint qs = bl.block.qs[iqs]; const uint signs = pack32(u16vec2(bl16.block.qs[is/2+0], bl16.block.qs[is/2+1])); const float db = d * 0.5 * (0.5 + (signs >> 28));
const uint sign7 = bitfieldExtract(signs, 7 * (int(iqs / 2) % 4), 7); const uint sb = (sign7 | (bitCount(sign7) << 7)) >> (idx & 0x6u);
const uint grid = iq3xxs_grid[qs]; const u8vec4 g = unpack8(grid);
return f16vec4( db * float(g.x) * ((sb & 1u) != 0u ? -1.0 : 1.0), db * float(g.y) * ((sb & 2u) != 0u ? -1.0 : 1.0), db * float(g.z) * ((sb & 4u) != 0u ? -1.0 : 1.0), db * float(g.w) * ((sb & 8u) != 0u ? -1.0 : 1.0));}#endif
#if defined(DATA_A_IQ3_S)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ3_S { block_iq3_s block;};
float16_t dequantFuncIQ3_S(const in decodeBufIQ3_S bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ uint idx = coordInBlock[1];
const uint iqs = (idx & 0xFC) >> 2; // 0..63 const uint iqh = (idx & 0xE0) >> 5;
const float d = float(bl.block.d); const uint qs = bl.block.qs[iqs]; const uint qh = bl.block.qh[iqh]; const int8_t sign = int8_t(bl.block.signs[iqs / 2] >> (idx & 0x6)); const uint scale = bl.block.scales[iqs / 16]; const ivec2 sign01 = ivec2(1 - (2 & ivec2(sign << 1, sign))); const float db = d * (1 + 2 * ((scale >> (4 * (iqh & 1))) & 0xf)); const uint32_t grid = iq3s_grid[qs | ((qh << (8 - (iqs % 8))) & 256)] >> ((idx & 2) << 3); const vec2 v = db * vec2(sign01) * vec2(unpack8(grid).xy);
return float16_t(v[idx & 1]);}
f16vec4 dequantFuncIQ3_S_v(const in decodeBufIQ3_S bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const uint idx = coordInBlock[1];
const uint iqs = idx >> 2; const uint iqh = idx >> 5;
const float d = float(bl.block.d); const uint qs = bl.block.qs[iqs]; const uint qh = bl.block.qh[iqh]; const uint sb = uint(bl.block.signs[iqs / 2]) >> (idx & 0x6u); const uint scale = bl.block.scales[iqs / 16]; const float db = d * (1 + 2 * ((scale >> (4 * (iqh & 1))) & 0xf));
const uint grid = iq3s_grid[qs | ((qh << (8 - (iqs % 8))) & 256)]; const u8vec4 g = unpack8(grid);
return f16vec4( db * float(g.x) * ((sb & 1u) != 0u ? -1.0 : 1.0), db * float(g.y) * ((sb & 2u) != 0u ? -1.0 : 1.0), db * float(g.z) * ((sb & 4u) != 0u ? -1.0 : 1.0), db * float(g.w) * ((sb & 8u) != 0u ? -1.0 : 1.0));}#endif
#if defined(DATA_A_IQ4_XS)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ4_XS { block_iq4_xs block;};
layout(buffer_reference, std430, buffer_reference_align = 4) buffer decodeBufIQ4_XS_packed32 { block_iq4_xs_packed32 block;};
float16_t dequantFuncIQ4_XS(const in decodeBufIQ4_XS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1];
const uint ib32 = (idx & 0xE0) >> 5; // 0..7
const uint sl = (bl.block.scales_l[ib32/2] >> (4 * (ib32 & 1))) & 0xF; const uint sh = ((bl.block.scales_h) >> (2 * ib32)) & 3; const uint qshift = (idx & 16) >> 2; const uint q = (bl.block.qs[16 * ib32 + (idx % 16)] >> qshift) & 0xF;
float16_t ret = d * float16_t(int(sl | (sh << 4)) - 32) * float16_t(kvalues_iq4nl[q]); return ret;}
f16vec4 dequantFuncIQ4_XS_v(const in decodeBufIQ4_XS bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ4_XS_packed32 bl32 = decodeBufIQ4_XS_packed32(bl); const float16_t d = bl.block.d; const uint idx = coordInBlock[1];
const uint ib32 = idx >> 5; // 0..7 const uint sl = (bl32.block.scales_l >> (4 * ib32)) & 0xF; const uint sh = (uint(bl32.block.scales_h) >> (2 * ib32)) & 0x3; const uint qshift = (idx & 0x10) >> 2; // {0, 4} const uint qs_w = 4 * ib32 + ((idx & 0xC) >> 2); // iqs / 4, in [0,32)
const float16_t dl = d * float16_t(int(sl | (sh << 4)) - 32);
const uint qsw = bl32.block.qs[qs_w]; const u8vec4 qv = unpack8((qsw >> qshift) & 0x0F0F0F0Fu); const vec4 ret = vec4( float(kvalues_iq4nl[qv.x]), float(kvalues_iq4nl[qv.y]), float(kvalues_iq4nl[qv.z]), float(kvalues_iq4nl[qv.w])) * float(dl); return f16vec4(ret);}#endif
#if defined(DATA_A_IQ4_NL)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ4_NL { block_iq4_nl block;};
layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufIQ4_NL_packed16 { block_iq4_nl_packed16 block;};
float16_t dequantFuncIQ4_NL(const in decodeBufIQ4_NL bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint iqs = idx & 0xF; const uint shift = (idx & 0x10) >> 2; uint32_t qs = bl.block.qs[iqs]; qs >>= shift; qs &= 0xF; float16_t ret = float16_t(kvalues_iq4nl[qs]) * d; return ret;}
f16vec4 dequantFuncIQ4_NL_v(const in decodeBufIQ4_NL bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufIQ4_NL_packed16 bl16 = decodeBufIQ4_NL_packed16(bl); const float16_t d = bl.block.d; const uint idx = coordInBlock[1]; const uint shift = (idx & 0x10) >> 2; // 0 or 4 const uint qs_i = (idx & 0xC) >> 1; // packed16 word index, in {0,2,4,6} const uint qsw = uint32_t(bl16.block.qs[qs_i ]) | (uint32_t(bl16.block.qs[qs_i + 1u]) << 16); // shift in {0,4}: per-byte mask 0x0F isolates the wanted nibble in each byte. const u8vec4 q = unpack8((qsw >> shift) & 0x0F0F0F0Fu); return f16vec4( float(d) * float(kvalues_iq4nl[q.x]), float(d) * float(kvalues_iq4nl[q.y]), float(d) * float(kvalues_iq4nl[q.z]), float(d) * float(kvalues_iq4nl[q.w]));}#endif
#if defined(DATA_A_MXFP4)layout(buffer_reference, std430, buffer_reference_align = 2) buffer decodeBufMXFP4 { block_mxfp4 block;};
float16_t dequantFuncMXFP4(const in decodeBufMXFP4 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float d = e8m0_to_fp32(bl.block.e); const uint idx = coordInBlock[1]; const uint iqs = idx & 0xF; const uint shift = (idx & 0x10) >> 2; uint32_t qs = bl.block.qs[iqs]; qs >>= shift; qs &= 0xF; float16_t ret = float16_t(kvalues_mxfp4[qs] * d * 0.5); return ret;}
f16vec4 dequantFuncMXFP4_v(const in decodeBufMXFP4 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const float d = e8m0_to_fp32(bl.block.e); const uint idx = coordInBlock[1]; const uint iqs = idx & 0xF; const uint shift = (idx & 0x10) >> 2; uvec4 qv = uvec4( uint(bl.block.qs[iqs]), uint(bl.block.qs[iqs + 1u]), uint(bl.block.qs[iqs + 2u]), uint(bl.block.qs[iqs + 3u])); qv = (qv >> shift) & 0xFu; const vec4 ret = vec4( float(kvalues_mxfp4[qv.x]), float(kvalues_mxfp4[qv.y]), float(kvalues_mxfp4[qv.z]), float(kvalues_mxfp4[qv.w])) * d * 0.5f; return f16vec4(ret);}#endif
#if defined(DATA_A_NVFP4)layout(buffer_reference, std430, buffer_reference_align = 4) buffer decodeBufNVFP4 { block_nvfp4 block;};
layout(buffer_reference, std430, buffer_reference_align = 4) buffer decodeBufNVFP4_packed32 { block_nvfp4_packed32 block;};
float16_t dequantFuncNVFP4(const in decodeBufNVFP4 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ const uint idx = coordInBlock[1]; const uint sub = (idx & 0x30) >> 4; const uint iqs = ((idx & 0x30) >> 1) + (idx & 0x7); const uint shift = (idx & 0x8) >> 1; const float d = ue4m3_to_fp32(bl.block.d[sub]); uint qs = uint(bl.block.qs[iqs]); qs = (qs >> shift) & 0xF; return float16_t(kvalues_mxfp4[qs] * d * 0.5);}
f16vec4 dequantFuncNVFP4_v(const in decodeBufNVFP4 bl, const in uint blockCoords[2], const in uint coordInBlock[2]){ decodeBufNVFP4_packed32 bl32 = decodeBufNVFP4_packed32(bl); const uint idx = coordInBlock[1]; const uint sub = idx >> 4; const uint qs_w = ((idx & 0x30) >> 3) + ((idx & 0x4u) >> 2); // iqs / 4, in [0,8) const uint shift = (idx & 0x8) >> 1; const float d = ue4m3_to_fp32(bl.block.d[sub]);
const uint qsw = uint32_t(bl32.block.qs[qs_w]); const u8vec4 qv = unpack8((qsw >> shift) & 0x0F0F0F0Fu); const vec4 ret = vec4( float(kvalues_mxfp4[qv.x]), float(kvalues_mxfp4[qv.y]), float(kvalues_mxfp4[qv.z]), float(kvalues_mxfp4[qv.w])) * d * 0.5f; return f16vec4(ret);}#endif
#if defined(DATA_A_Q1_0)#define dequantFuncA dequantFuncQ1_0#define dequantFuncA_v dequantFuncQ1_0_v#elif defined(DATA_A_Q4_0)#define dequantFuncA dequantFuncQ4_0#define dequantFuncA_v dequantFuncQ4_0_v#elif defined(DATA_A_Q4_1)#define dequantFuncA dequantFuncQ4_1#define dequantFuncA_v dequantFuncQ4_1_v#elif defined(DATA_A_Q5_0)#define dequantFuncA dequantFuncQ5_0#define dequantFuncA_v dequantFuncQ5_0_v#elif defined(DATA_A_Q5_1)#define dequantFuncA dequantFuncQ5_1#define dequantFuncA_v dequantFuncQ5_1_v#elif defined(DATA_A_Q8_0)#define dequantFuncA dequantFuncQ8_0#define dequantFuncA_v dequantFuncQ8_0_v#elif defined(DATA_A_Q2_K)#define dequantFuncA dequantFuncQ2_K#define dequantFuncA_v dequantFuncQ2_K_v#elif defined(DATA_A_Q3_K)#define dequantFuncA dequantFuncQ3_K#define dequantFuncA_v dequantFuncQ3_K_v#elif defined(DATA_A_Q4_K)#define dequantFuncA dequantFuncQ4_K#define dequantFuncA_v dequantFuncQ4_K_v#define fetch_scales fetch_scalesQ4_K#define store_scales store_scalesQ4_K#elif defined(DATA_A_Q5_K)#define dequantFuncA dequantFuncQ5_K#define dequantFuncA_v dequantFuncQ5_K_v#define fetch_scales fetch_scalesQ5_K#define store_scales store_scalesQ4_K#elif defined(DATA_A_Q6_K)#define dequantFuncA dequantFuncQ6_K#define dequantFuncA_v dequantFuncQ6_K_v#elif defined(DATA_A_IQ1_S)#define dequantFuncA dequantFuncIQ1_S#define dequantFuncA_v dequantFuncIQ1_S_v#elif defined(DATA_A_IQ1_M)#define dequantFuncA dequantFuncIQ1_M#define dequantFuncA_v dequantFuncIQ1_M_v#elif defined(DATA_A_IQ2_XXS)#define dequantFuncA dequantFuncIQ2_XXS#define dequantFuncA_v dequantFuncIQ2_XXS_v#elif defined(DATA_A_IQ2_XS)#define dequantFuncA dequantFuncIQ2_XS#define dequantFuncA_v dequantFuncIQ2_XS_v#elif defined(DATA_A_IQ2_S)#define dequantFuncA dequantFuncIQ2_S#define dequantFuncA_v dequantFuncIQ2_S_v#elif defined(DATA_A_IQ3_XXS)#define dequantFuncA dequantFuncIQ3_XXS#define dequantFuncA_v dequantFuncIQ3_XXS_v#elif defined(DATA_A_IQ3_S)#define dequantFuncA dequantFuncIQ3_S#define dequantFuncA_v dequantFuncIQ3_S_v#elif defined(DATA_A_IQ4_XS)#define dequantFuncA dequantFuncIQ4_XS#define dequantFuncA_v dequantFuncIQ4_XS_v#elif defined(DATA_A_IQ4_NL)#define dequantFuncA dequantFuncIQ4_NL#define dequantFuncA_v dequantFuncIQ4_NL_v#elif defined(DATA_A_MXFP4)#define dequantFuncA dequantFuncMXFP4#define dequantFuncA_v dequantFuncMXFP4_v#elif defined(DATA_A_NVFP4)#define dequantFuncA dequantFuncNVFP4#define dequantFuncA_v dequantFuncNVFP4_v#elif defined(DATA_A_F32)#define dequantFuncA dequantFuncF32#endif12345678910111213#extension GL_EXT_control_flow_attributes : require#extension GL_EXT_shader_16bit_storage : require
layout (push_constant) uniform parameter{ uint M; uint K; uint stride_a; uint stride_b; uint nel;} p;
#include "types.glsl"123456789101112131415161718192021222324252627282930313233343536373839404142#version 450
#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require
#include "dequant_head.glsl"
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {block_iq1_m data_a[];};layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
void main() { // Each thread handles 1 subblock (32 values with 2 scales) const uint ib = gl_WorkGroupID.x * 32 + gl_LocalInvocationID.x / 8;
init_iq_shmem(gl_WorkGroupSize);
if (ib >= p.nel / 256) { return; }
const uint ib32 = gl_LocalInvocationID.x % 8; const uint ib64 = ib32 / 2; const uint b_idx = 256 * ib + 32 * ib32;
const uint16_t[4] scales = data_a[ib].scales; const u16vec4 s = u16vec4(scales[0], scales[1], scales[2], scales[3]) >> 12; const float d = float(unpackHalf2x16(s.x | (s.y << 4) | (s.z << 8) | (s.w << 12)).x);
const uint sc = data_a[ib].scales[ib64]; [[unroll]] for (int l = 0; l < 4; ++l) { const uint ib16 = 2 * ib32 + l / 2; const float dl = d * (2 * bitfieldExtract(sc, 3 * int(ib16 & 3), 3) + 1); const uint qh = data_a[ib].qh[ib16] >> (4 * (l & 1)); const uint qs = data_a[ib].qs[4 * ib32 + l]; const float delta = ((qh & 8) != 0) ? -IQ1M_DELTA : IQ1M_DELTA; const int16_t grid = int16_t(iq1s_grid[qs | ((qh & 7) << 8)]); [[unroll]] for (int j = 0; j < 8; ++j) { data_b[b_idx + 8 * l + j] = D_TYPE(dl * (bitfieldExtract(grid, 2*j, 2) + delta)); } }}1234567891011121314151617181920212223242526272829303132333435#version 450
#include "dequant_head.glsl"
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {block_iq1_s data_a[];};layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
void main() { // Each thread handles 1 subblock (32 values with 2 scales) const uint ib = gl_WorkGroupID.x * 32 + gl_LocalInvocationID.x / 8;
init_iq_shmem(gl_WorkGroupSize);
if (ib >= p.nel / 256) { return; }
const uint ib32 = gl_LocalInvocationID.x % 8; const uint b_idx = 256 * ib + 32 * ib32;
uint qh = data_a[ib].qh[ib32]; const float d = float(data_a[ib].d); const float dl = d * float(2 * bitfieldExtract(qh, 12, 3) + 1); const float delta = ((qh & 0x8000) != 0) ? -IQ1S_DELTA : IQ1S_DELTA; [[unroll]] for (uint l = 0; l < 4; ++l) { const uint qs = data_a[ib].qs[4 * ib32 + l]; const uint hi = bitfieldExtract(qh, 3 * int(l), 3); const int16_t grid = int16_t(iq1s_grid[qs | (hi << 8)]); [[unroll]] for (int j = 0; j < 8; ++j) { data_b[b_idx + 8 * l + j] = D_TYPE(dl * (bitfieldExtract(grid, 2*j, 2) + delta)); } }}.gitattributes+25
backend/llama.cpp/LICENSEAdded+21
backend/llama.cpp/MakefileAdded+9
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-apir.hAdded+15
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-backend.cppAdded+58
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-buffer-type.cppAdded+110
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-buffer.cppAdded+173
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-device.cppAdded+192
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward-impl.hAdded+36
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-forward.gen.hAdded+53
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-shm.cppAdded+99
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-shm.hAdded+23
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-utils.cppAdded+179
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu-utils.hAdded+86
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu.cppAdded+545
backend/llama.cpp/ggml/src/ggml-virtgpu/virtgpu.hAdded+115
backend/llama.cpp/ggml/src/ggml-vulkan/CMakeLists.txtAdded+236
backend/llama.cpp/ggml/src/ggml-vulkan/cmake/host-toolchain.cmake.inAdded+15
backend/llama.cpp/ggml/src/ggml-vulkan/ggml-vulkan.cppAdded
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txtAdded+35
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/acc.compAdded+37
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/add.compAdded+69
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/add1.compAdded+28
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/add_id.compAdded+42
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/arange.compAdded+20
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/argmax.compAdded+60
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/argsort.compAdded+86
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/argsort_large.compAdded+114
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/col2im_1d.compAdded+61
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/concat.compAdded+41
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/contig_copy.compAdded+53
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv2d_dw.compAdded+105
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv2d_mm.compAdded+480
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv3d_mm.compAdded+431
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/conv_transpose_1d.compAdded+98
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy.compAdded+25
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy_from_quant.compAdded+51
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy_to_quant.compAdded+320
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/copy_transpose.compAdded+67
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/count_equal.compAdded+31
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/count_experts.compAdded+51
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/cumsum.compAdded+83
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/cumsum_multipass1.compAdded+60
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/cumsum_multipass2.compAdded+66
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_f32.compAdded+20
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs.glslAdded+692
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_funcs_cm2.glslAdded+1376
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_head.glslAdded+13
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_iq1_m.compAdded+42
backend/llama.cpp/ggml/src/ggml-vulkan/vulkan-shaders/dequant_iq1_s.compAdded+35